text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using QOMS.Class; namespace QOMS.Activitys { [Activity(Label = "@string/SystemName", Icon = "@drawable/Icon", Theme = "@android:style/Theme.Holo.Light")] public class ChangePassword : Activity { EditText xgmm_et_dwmc; EditText xgmm_et_dwbh; EditText xgmm_et_xmm; EditText xgmm_et_qrmm; Button xgmm_btn_tj; HandHeldService.HandHeldService service; String Password=""; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ChangePassword); service = OperationClass.service; InitControls(); InitData(); // Create your application here xgmm_btn_tj.Click += (s, e) => { try { if (CheckData()) { int result = service.ChangePassword(xgmm_et_dwbh.Text, xgmm_et_xmm.Text); if (result > 0) { Toast.MakeText(this, "密码修改成功,请从新登陆!", ToastLength.Long).Show(); SetResult(Result.Ok); Finish(); } else { Toast.MakeText(this, "修改失败!", ToastLength.Long).Show(); } } } catch (Exception) { Toast.MakeText(this, "连接超时,请查看本机是否能连接网络!", ToastLength.Long).Show(); } }; } /// <summary> /// 初始化控件 /// </summary> void InitControls() { xgmm_et_dwmc = FindViewById<EditText>(Resource.Id.xgmm_et_dwmc); //队伍名称; xgmm_et_dwbh = FindViewById<EditText>(Resource.Id.xgmm_et_dwbh); //队伍编号; xgmm_et_xmm = FindViewById<EditText>(Resource.Id.xgmm_et_xmm); //新密码; xgmm_et_qrmm = FindViewById<EditText>(Resource.Id.xgmm_et_qrmm); //确认密码; xgmm_btn_tj = FindViewById<Button>(Resource.Id.xgmm_btn_tj); //下一步 } /// <summary> /// 初始化数据 /// </summary> void InitData() { xgmm_et_dwmc.Text = Intent.GetStringExtra("TeamName"); xgmm_et_dwbh.Text = Intent.GetStringExtra("TeamId"); Password = Intent.GetStringExtra("Password"); } bool CheckData() { if (string.IsNullOrEmpty(xgmm_et_xmm.Text)) { Toast.MakeText(this, "请填写新密码!", ToastLength.Long).Show(); return false; } else if(xgmm_et_xmm.Text.Length<5) { Toast.MakeText(this, "密码至少为5个字符,请从新填写!", ToastLength.Long).Show(); return false; } if (xgmm_et_xmm.Text == Password) { Toast.MakeText(this, "请填修改新密码!", ToastLength.Long).Show(); return false; } if (string.IsNullOrEmpty(xgmm_et_qrmm.Text)) { Toast.MakeText(this, "请填写确认密码!", ToastLength.Long).Show(); return false; } if ( xgmm_et_xmm.Text != xgmm_et_qrmm.Text) { Toast.MakeText(this, "两次密码不一致,请重新填写!", ToastLength.Long).Show(); return false; } return true; } } }
using BUS; using DevExpress.XtraGrid.Views.Grid; 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 ControlLocalizer; using DevExpress.XtraSplashScreen; namespace GUI { public partial class f_History : Form { KetNoiDBDataContext db = new KetNoiDBDataContext(); public f_History() { InitializeComponent(); rTime.SetTime(thoigian); rTime.SetTime2(thoigian); } public void loaddata(DateTime tungay, DateTime denngay) { DateTime _denngay = new DateTime(denngay.Year, denngay.Month, denngay.Day, 23,59,59); SplashScreenManager.ShowForm(typeof(SplashScreen2)); var lst = from a in db.histories join d in db.donvis on a.donvi equals d.id where a.thoigian >= tungay && a.thoigian <= _denngay select new { ma = a.ma, hoatdong = a.hoatdong, nguoi = a.nguoi, may = a.may, thoigian = a.thoigian, donvi = a.donvi, MaTim = LayMaTim(d) }; var lst2 = lst.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); gridControl1.DataSource = lst2; SplashScreenManager.CloseForm(); } #region code cu 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; } #endregion private void f_PN_Load(object sender, EventArgs e) { LanguageHelper.Translate(this); LanguageHelper.Translate(barManager1); changeFont.Translate(this); changeFont.Translate(barManager1); tungay.ReadOnly = true; denngay.ReadOnly = true; } private void thoigian_EditValueChanged(object sender, EventArgs e) { changeTime.thoigian_change3(thoigian, tungay, denngay); loaddata(DateTime.Parse(tungay.Text), DateTime.Parse(denngay.Text)); } private void timkiem_Click(object sender, EventArgs e) { loaddata(DateTime.Parse(tungay.Text), DateTime.Parse(denngay.Text)); } private void gridView1_CustomDrawRowIndicator_1(object sender, RowIndicatorCustomDrawEventArgs e) { if (!gridView1.IsGroupRow(e.RowHandle)) //Nếu không phải là Group { if (e.Info.IsRowIndicator) //Nếu là dòng Indicator { if (e.RowHandle < 0) { e.Info.ImageIndex = 0; e.Info.DisplayText = string.Empty; } else { e.Info.ImageIndex = -1; //Không hiển thị hình e.Info.DisplayText = (e.RowHandle + 1).ToString(); //Số thứ tự tăng dần } SizeF _Size = e.Graphics.MeasureString(e.Info.DisplayText, e.Appearance.Font); //Lấy kích thước của vùng hiển thị Text Int32 _Width = Convert.ToInt32(_Size.Width) + 20; BeginInvoke(new MethodInvoker(delegate { cal(_Width, gridView1); })); //Tăng kích thước nếu Text vượt quá } } else { e.Info.ImageIndex = -1; e.Info.DisplayText = string.Format("[{0}]", (e.RowHandle * -1)); //Nhân -1 để đánh lại số thứ tự tăng dần SizeF _Size = e.Graphics.MeasureString(e.Info.DisplayText, e.Appearance.Font); Int32 _Width = Convert.ToInt32(_Size.Width) + 20; BeginInvoke(new MethodInvoker(delegate { cal(_Width, gridView1); })); } } bool cal(Int32 _Width, GridView _View) { _View.IndicatorWidth = _View.IndicatorWidth < _Width ? _Width : _View.IndicatorWidth; return true; } } }
using System; using System.Collections.Generic; using System.Text; namespace JSONParsApp.Models { public class Lecturer : Person { public string Subject { get; set; } public string DegreeLevel { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InputController : MonoBehaviour { public GameObject selected; [SerializeField] private InputField p_height; [SerializeField] private InputField p_width; [SerializeField] private InputField p_length; public Camera mainCamera; public Canvas can; public float default_fov = 30.0f; /// Awake is called when the script instance is being loaded. void Awake() { can.gameObject.SetActive(false); } // Use this for initialization void Start() { p_height.placeholder.GetComponent<Text>().text = "Height"; p_width.placeholder.GetComponent<Text>().text = "Width"; p_length.placeholder.GetComponent<Text>().text = "Length"; } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Debug.Log("Mouse Clicked"); RaycastHit hitInfo = new RaycastHit(); if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo)) { selected = hitInfo.transform.gameObject; print(selected.name); PopulateUI(selected); } } if (Input.GetMouseButtonDown(1)) { Debug.Log("Right Click"); } if (Input.GetAxis("Mouse ScrollWheel") < 0f) { print("Zooming in"); mainCamera.fieldOfView--; } if (Input.GetAxis("Mouse ScrollWheel") > 0f) { print("Zooming out"); mainCamera.fieldOfView++; } if(Input.GetMouseButtonDown(2)){ mainCamera.fieldOfView = default_fov; } } void LateUpdate(){ if(selected && Input.GetMouseButtonDown(1)){ float x = 0f; x+= Input.GetAxis("Mouse X") * 5.0f * 5f*.02f; Quaternion rotation = Quaternion.Euler(0, x, 0); Vector3 position = rotation * new Vector3(0, 0, 5) + selected.transform.position; // mainCamera.transform.position = position; mainCamera.transform.rotation = rotation; } } void PopulateUI(GameObject target) { print("Updating..."); string height = target.transform.localScale.y.ToString(); string width = target.transform.localScale.x.ToString(); string length = target.transform.localScale.z.ToString(); p_height.text = height; p_width.text = width; p_length.text = length; can.gameObject.SetActive(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; class QuickSort { static List<int> Q_Sort(List<int> array) { if (array.Count <= 1) { return array; } int pivot = array[array.Count / 2]; List<int> left = new List<int>(); List<int> right = new List<int>(); for (int i = 0; i < array.Count; i++) { if (i != (array.Count / 2)) { if (array[i] <= pivot) { left.Add(array[i]); } else { right.Add(array[i]); } } } left = Q_Sort(left); right = Q_Sort(right); List<int> sorted = new List<int>(); sorted.AddRange(left); sorted.Add(pivot); sorted.AddRange(right); return sorted; } static void PrintSorted(List<int> list) { for (int i = 0; i < list.Count; i++) { Console.Write(list[i] + " "); } Console.WriteLine(); } static void Main() { /*Quick sort algorithm - integers*/ List<int> myArray = new List<int>() { 20, 5, 36, 8, -6, 9, -13, 25, -6, 7 }; List<int> sortedArray = Q_Sort(myArray); PrintSorted(sortedArray); } }
using System.Collections.Generic; using Asset.Models.Library.EntityModels.AssetsModels.AssetSetups; using Core.Repository.Library.Core; namespace Asset.Core.Repository.Library.Repositorys.AssetsModels.AssetSetups { public interface IAssetGroupRepository : IRepository<AssetGroup> { AssetGroup GetAssetGroupByName(string name); AssetGroup GetAssetGroupByShortName(string shortName); AssetGroup GetAssetGroupByGroupCode(string code); IEnumerable<AssetGroup> AssetGroupsWithAssetType(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.AI; public class TargetController : MonoBehaviour { public static UnitSetter unitSetter; //Inherit public static UnitSpawner unitSpawner; //Inherit 2 public static NumberHolder numberHolder = new NumberHolder(); //Inherit 3 private float faction; //Unit's faction private float attackDelay = 1.0f; //How long until they attack again private float nextDamageEvent; //The event of attacking private bool inRange = false; //Are they in range to attack public bool isWandering = false; public float lookRadius = 200f; //how far they can look private float distance, lowestDist; public GameObject TargetObj; //The target of this unit public List<GameObject> Targets = new List<GameObject>(); //Creating the array public List<Collider> TriggerList = new List<Collider>(); public Collider wizardAOE; // Start is called before the first frame update IEnumerator Start() { unitSetter = UnitSetter.instance; Debug.Log(UnitSpawner.instance.Targets.Count); faction = UnitSetter.instance.faction; for (int i = 0; i < UnitSpawner.instance.Targets.Count; i++) { Targets.Add(UnitSpawner.instance.Targets[i]); //Debug.Log("("+this.name+")["+ this.GetComponent<UnitSetter>().faction +"] ("+ Targets[i].GetComponent<UnitSetter>().name +")["+ Targets[i].GetComponent<UnitSetter>().faction+"]"); } wizardAOE.enabled = false; yield return new WaitForSeconds(2); // FindTarget(); } // Update is called once per frame private void FixedUpdate() { FindTarget(); if (this.GetComponent<UnitSetter>().faction == 2) { wizardAOE.enabled = true; } //Move(); if (this.GetComponent<UnitSetter>().range >= lowestDist) { inRange = true; } else { inRange = false; } if (inRange) { if (Time.time >= nextDamageEvent) { nextDamageEvent = Time.time + attackDelay; Attack(); } } else { nextDamageEvent = Time.time + attackDelay; Move(); } } private void Move() { if (TargetObj == null || TargetObj.Equals(null)) { FindTarget(); /*if (isWandering == false) { //Wander(); // Wander method is dead.... }*/ } else if (lowestDist <= lookRadius) { isWandering = false; transform.position = Vector3.MoveTowards(transform.position, TargetObj.transform.position, this.GetComponent<UnitSetter>().speed); //FaceTarget(); } } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, lookRadius); //draws the look distance in inspector mode if (this.GetComponent<UnitSetter>().faction == 2) { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(transform.position, 3f); //Wizard attack range visual } else if (this.GetComponent<UnitSetter>().type == 0) { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(transform.position, 5f); //Ranger attack range visual } else if (this.GetComponent<UnitSetter>().type == 1) { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(transform.position, 1f); //Melee attack range visual } } void FindTarget() { if (unitSetter.isDone == false) { return; } lowestDist = lookRadius; for (int x = Targets.Count - 1; x >= 0; x--) //loops through the List for targets from end of list to begnning as we may remove items { GameObject unit = Targets[x]; //Calling Get Distance method so we know the distance between this unit and the temp if ( unit == null || unit.GetComponent<UnitSetter>().isDead == true || unit.Equals(null)) //If the temp unit is equal to nothing then remove it from list { Targets.Remove(unit); /* if (unit == null || unit.Equals(null)) { Targets.Remove(unit); } */ continue; } GetDistance(unit); if (unit.GetComponent<UnitSetter>().faction == this.GetComponent<UnitSetter>().faction) //Faction Checker { Targets.Remove(unit); continue; } if (unit == this.gameObject) //Checks to see if the object is trying to get itself { Targets.Remove(unit); continue; } if (distance < lowestDist) //Sets the target finally { lowestDist = distance; TargetObj = unit; if (this.GetComponent<UnitSetter>().faction == unit.GetComponent<UnitSetter>().faction) { Debug.Log(this.GetComponent<UnitSetter>().ToString() + "| ==->~} |" + unit.GetComponent<UnitSetter>().ToString()); //Debugging pup } } } if (TargetObj == null) { for (int i = 0; i < BuildingSpawner.instance.Targets.Count; i++) { Targets.Add(BuildingSpawner.instance.Targets[i]); } } } private void GetDistance(GameObject tempUnit) { distance = Vector3.Distance(tempUnit.transform.position, transform.position);//Gets the distance between current unit and targeted } /*void FaceTarget() //Will not roll and try to face the target which is currently locked on { Vector3 direction = (TargetObj.transform.position - TargetObj.transform.position).normalized; Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z)); transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f); }*/ void Attack() { transform.position = Vector3.MoveTowards(transform.position, TargetObj.transform.position, 0); if (wizardAOE.enabled == true) { for (int x = TriggerList.Count - 1; x >= 0; x--) { TriggerList[x].GetComponent<UnitSetter>().health = TriggerList[x].GetComponent<UnitSetter>().health - this.gameObject.GetComponent<UnitSetter>().damage; } } else { TargetObj.GetComponent<UnitSetter>().health = TargetObj.GetComponent<UnitSetter>().health - this.gameObject.GetComponent<UnitSetter>().damage; } //isWandering = false; } private void OnTriggerEnter(Collider other) { if (!TriggerList.Contains(other)) { TriggerList.Add(other); } } private void OnTriggerExit(Collider other) { if (TriggerList.Contains(other)) { TriggerList.Remove(other); } } /*void Wander() // Will fix at a later date { Vector3 pos = new Vector3(Random.Range(0, NumberHolder.MapX), 1, Random.Range(0, NumberHolder.MapY)); isWandering = true; if (isWandering == true) { transform.position = Vector3.MoveTowards(transform.position, pos, this.GetComponent<UnitSetter>().speed); Debug.Log(this.GetComponent<UnitSetter>().ToString() + " I am wandering to: " + pos); } }*/ /* IEnumerator WaitforLoad() { if (this.GetComponent<UnitSetter>().isDone == false) { yield return new WaitForSeconds(2); } else { //currentSpeed = UnitSetter.instance.speed; } } */ //test1234 }
using KekManager.Database.Data; using KekManager.Security.Domain; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KekManager.Database { public class DbInitializer : IDbInitializer { private readonly FullDatabaseContext _context; private readonly UserManager<SecurityUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; public DbInitializer( FullDatabaseContext context, UserManager<SecurityUser> userManager, RoleManager<IdentityRole> roleManager) { _context = context; _userManager = userManager; _roleManager = roleManager; } //This example just creates an Administrator role and one Admin users public async Task Initialize() { //create database schema if none exists _context.Database.Migrate(); if (!await _roleManager.RoleExistsAsync("Administrator")) { //Create the Administartor Role await _roleManager.CreateAsync(new IdentityRole("Administrator")); } if (!await _roleManager.RoleExistsAsync("User")) { //Create the User Role await _roleManager.CreateAsync(new IdentityRole("User")); } if (!await _roleManager.RoleExistsAsync("ResearchFellow")) { //Create the User Role await _roleManager.CreateAsync(new IdentityRole("ResearchFellow")); } { var admin = new SecurityUser { UserName = "admin", Email = "admin@kekmanager.com", EmailConfirmed = true }; if (await _userManager.FindByNameAsync(admin.UserName) == null) { //Create the default Admin account and apply the Administrator role await _userManager.CreateAsync(admin, "1qaz@WSX"); var adminRoles = new[] { "User", "Administrator" }; await _userManager.AddToRolesAsync(await _userManager.FindByNameAsync(admin.UserName), adminRoles); } } { //Create the default User account and apply the User role var user = new SecurityUser { UserName = "user", Email = "user@kekmanager.com", EmailConfirmed = true }; if (await _userManager.FindByNameAsync(user.UserName) == null) { await _userManager.CreateAsync(user, "1qaz@WSX"); await _userManager.AddToRoleAsync(await _userManager.FindByNameAsync(user.UserName), "User"); } } { //Create example endpoint user account var user = new SecurityUser { UserName = "john.doe", Email = "john.doe@pwr.edu.pl", EmailConfirmed = true }; if (await _userManager.FindByNameAsync(user.UserName) == null) { await _userManager.CreateAsync(user, "1qaz@WSX"); await _userManager.AddToRoleAsync(await _userManager.FindByNameAsync(user.UserName), "User"); await _userManager.AddToRoleAsync(await _userManager.FindByNameAsync(user.UserName), "ResearchFellow"); } } } } }
using FluentValidation; using Publicon.Infrastructure.Commands.Models.Category; using Publicon.Infrastructure.DTOs; namespace Publicon.Api.Validators.Category { public class CreateCategoryCommandValidator : AbstractValidator<CreateCategoryCommand> { public CreateCategoryCommandValidator() { RuleFor(p => p.Name).NotNull().NotEmpty().MaximumLength(200); RuleFor(p => p.Description).MaximumLength(750); RuleForEach(p => p.Fields).ChildRules(p => { p.RuleFor(x => x.Name).NotNull().NotEmpty().MaximumLength(200); p.RuleFor(x => x.IsRequired).NotNull(); }); RuleFor(p => p.Fields).SetValidator(new UniqueFieldNameValidator<FieldToAddDTO>()); } } }
using Core.Dto; namespace Core.NUnitTest.Tests.Services { public class TestDto : EntityDto { public string Inn { get; set; } } }
using System; namespace OCP.Files { /** * Storage authentication exception * @since 9.0.0 */ public class StorageTimeoutException : StorageNotAvailableException { /** * StorageTimeoutException constructor. * * @param string message * @param \Exception|null previous * @since 9.0.0 */ public StorageTimeoutException(string message = "", Exception previous = null) { //l = \OC::server.getL10N('core'); //parent::__construct(l.t('Storage connection timeout. %s', [message]), self::STATUS_TIMEOUT, previous); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ChkSum { class Program { enum MicomIdx { T470, T383, SiW31100, T370, T60, A8316, }; private struct MicomInfo { public int romSize; public ConsoleColor color; public byte filling; }; /* [STAThread] * using System.Windows.Forms;에 있는 Clipboard class를 사용하기 위해 있어야 함. * Ref : https://stackoverflow.com/questions/3546016/how-to-copy-data-to-clipboard-in-c-sharp/34077334#34077334 */ [STAThread] static void Main(string[] args) { Dictionary<MicomIdx, MicomInfo> micomInfos = new Dictionary<MicomIdx, MicomInfo>() { [MicomIdx.T470] = new MicomInfo { romSize = 1024 * 384, color = ConsoleColor.Red, filling = 0xFF }, [MicomIdx.T383] = new MicomInfo { romSize = 1024 * 256, color = ConsoleColor.Blue, filling = 0xFF }, [MicomIdx.SiW31100] = new MicomInfo { romSize = 1024 * 127, color = ConsoleColor.Green, filling = 0xFF }, [MicomIdx.T370] = new MicomInfo { romSize = 1024 * 256, color = ConsoleColor.Gray, filling = 0xFF }, [MicomIdx.T60] = new MicomInfo { romSize = 1024 * 60, color = ConsoleColor.Gray, filling = 0xFF }, [MicomIdx.A8316] = new MicomInfo { romSize = 1024 * 16, color = ConsoleColor.Gray, filling = 0x00 }, }; #if DEBUG //string filePath = @"D:\ChkSum\ChkSum\0x301F.hex"; string filePath = @"D:\05_Programs\Essential\SiW SW31100 eFlashWriter V2.44\201013_SW31100_test.hex"; #else if (args.Length == 0) { Console.WriteLine("Check Sum을 계산할 파일 경로를 입력하세요."); Console.WriteLine("ex) C:\\> ChkSum.exe \"C:\\TestPJT\\Test.hex\""); Console.ReadKey(); return; } string filePath = args[0]; #endif if (File.Exists(filePath)) { Dictionary<MicomIdx, int> chkSum = new Dictionary<MicomIdx, int>(); Dictionary<MicomIdx, string> chkSumStr = new Dictionary<MicomIdx, string>(); string hexFile = System.IO.File.ReadAllText(filePath); Console.WriteLine("\n▶ File :"); Console.WriteLine("{0}\n", filePath); Console.WriteLine("\n▶ ChkSum"); foreach (MicomIdx micom in Enum.GetValues(typeof(MicomIdx))) { chkSum[micom] = IntelCheckSUM(hexFile, micomInfos[micom].romSize, micomInfos[micom].filling); // ex) 0x12345678 string chkSumStrInv = BitConverter.ToString(BitConverter.GetBytes(chkSum[micom])).Replace("-", ""); // ex) 7856452301 chkSumStr[micom] = string.Concat("0x", chkSumStrInv.Substring(2, 2), chkSumStrInv.Substring(0, 2)); // ex) 0x5678 Console.ForegroundColor = micomInfos[micom].color; Console.WriteLine("\n {0:D}) {1} : {2}", micom, micom, chkSumStr[micom]); } Console.ForegroundColor = ConsoleColor.Gray; Console.Write("\nClipboard로 복사할 MICOM의 번호({0}~{1})를 입력해 주세요 : ", 0, micomInfos.Count - 1); int selectedMicom = Console.Read() - '0'; MicomIdx idx = MicomIdx.T470; if ((0 <= selectedMicom) && (selectedMicom <= (micomInfos.Count - 1))) { idx = (MicomIdx)selectedMicom; } Clipboard.SetText(chkSumStr[idx]); Console.WriteLine("\nClipboard로 복사되었습니다. Ctrl+V 하시면 됩니다."); Console.ForegroundColor = micomInfos[idx].color; Console.WriteLine("▶ {0}", chkSumStr[idx]); } else { Console.WriteLine("\n파일이 존재하지 않습니다."); } Console.ReadKey(); } static int IntelCheckSUM(string file_buf, int RomLength, byte filling) { int i = 0; int DataCnt = 0; int chksum = 0; int LoopFlag = 0; int Line_LEN; int DUMMY; while (LoopFlag == 0) { if (file_buf[i++] != ':') continue; Line_LEN = ASC_to_HEX_1Byte(file_buf[i], file_buf[i + 1]); i += 2; // Line Length부분 증가 i += 4; // HEX파일의 ROM Address부분 SKIP DUMMY = ASC_to_HEX_1Byte(file_buf[i], file_buf[i + 1]); i += 2; // if (DUMMY == 0x00) // DUMMY Code값이 0x00일때만 덧셈을 한다. { while ( (Line_LEN--) > 0) { DataCnt++; chksum += ASC_to_HEX_1Byte(file_buf[i], file_buf[i + 1]); i += 2; // } } else if ((DUMMY == 0x01) || (DUMMY == 0x05))// DUMMY값이 0x01 or 0x05일때 while Loop종료 { LoopFlag = 1; } else { i += (Line_LEN * 2); // DUMMY값이 Data가 아닐때 SKIP } i += 3; // Line Checksum(2), Line feed code(1) SKIP } chksum += (RomLength - DataCnt) * filling; return chksum; } private static int ASC_to_HEX_1Byte(char ch1, char ch2) { string hex = string.Concat(ch1, ch2); return Convert.ToInt32(hex, 16); } } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Server.MatchMaking { using Constants; class MatchMakerSimple : IMatchMaker { IMatchQueue normalQueue { get; set; } IMatchQueue botQueue { get; set; } public MatchMakerSimple() { normalQueue = new MatchQueueSimple(2); botQueue = new MatchQueueSimple(2); } public void Enqueue(MatchPlayer player, QueueType queueType) { switch (queueType) { case QueueType.Normal: normalQueue.Enqueue(player); break; case QueueType.BotGame: // TODO : 동시입장 문제 botQueue.Enqueue(player); botQueue.Enqueue(MatchPlayer.CreateBot()); break; case QueueType.Nan2: break; } } public IEnumerable<MatchDataInternal> Poll() { var matchData = normalQueue.Poll(); if (matchData != null) yield return matchData; matchData = botQueue.Poll(); if (matchData != null) yield return matchData; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace GameEngine { /// <summary> /// Логика взаимодействия для AnswerWindow.xaml /// </summary> public partial class AnswerWindow : Window { public AnswerWindow() { InitializeComponent(); LoadDialogsId(); } private void LoadDialogsId() { if (DialogsData.dialList.Count != 0) { for (int i = 0; i < DialogsData.dialList.Count; i++) { if (DialogsData.dialList[i].id != DialogsData.idCurrDial) { cbIdNextDialog.Items.Add(Convert.ToString(DialogsData.dialList[i].id)); } } } } private void ClickCancelAnswer(object sender, RoutedEventArgs e) { if(tbAnswerText.Text == DialogsData.answerText) { DialogsData.answerText = tbAnswerText.Text; } this.Close(); } private void ClickOKAnswer(object sender, RoutedEventArgs e) { if (tbAnswerText.Text != "") { DialogsData.answerText = tbAnswerText.Text; if (cbIdNextDialog.Text == "Nothing" || cbIdNextDialog.Text == "") { DialogsData.idNextDialog = -1; } else { DialogsData.idNextDialog = Convert.ToInt32(cbIdNextDialog.Text); } this.Close(); } else { MessageBox.Show("Please enter answer text."); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Transactions; using System.Web.Security; using DotNetOpenAuth.AspNet; using Microsoft.Web.WebPages.OAuth; using WebMatrix.WebData; using RiversideHealthCare.Filters; using RiversideHealthCare.Models; using System.IO; namespace RiversideHealthCare.Controllers { public class ContactDetailAdminController : Controller { ContactDetailClass objContact = new ContactDetailClass(); [Authorize(Roles = "admin")] public ActionResult ContactDetailIndex() { var contact = objContact.getContacts(); return View(contact); } // GET: /Admin/Details [Authorize(Roles = "admin")] public ActionResult ContactDetails(int Id) { var contact = objContact.getContactsById(Id); if (contact == null) { return View("Error"); } else { return View(contact); } } // GET: /contactDetail/Insert [Authorize(Roles = "admin")] public ActionResult ContactDetailInsert() { return View(); } // POST: /contact/Insert // To handle file upload [HttpPost] [Authorize(Roles = "admin")] public ActionResult ContactDetailInsert(contact_detail contact) { if (ModelState.IsValid) { try { objContact.commitInsert(contact); return RedirectToAction("ContactDetailIndex"); //On sucessful insert, redirect to the index view } catch { //Error handling, return to view if something goes wrong return View(); } } return View(); } // GET: /updated [Authorize(Roles = "admin")] public ActionResult ContactDetailUpdate(int Id) { var contact = objContact.getContactsById(Id); if (contact == null) { return View("Error"); } return View(contact); } // POST: /Update [HttpPost] [Authorize(Roles = "admin")] public ActionResult ContactDetailUpdate(int Id, contact_detail contact) { //If all the input were valid , then database will be updated if (ModelState.IsValid) { try { objContact.commitUpdate(Id, contact.name, contact.phone, (int)contact.department_id); return RedirectToAction("ContactDetailIndex"); } catch { return View(); } } return View(); } // GET: /Delete [Authorize(Roles = "admin")] public ActionResult ContactDetailDelete(int Id) { //It shows Delete view according to the selected id var contact = objContact.getContactsById(Id); if (contact == null) { return View("Error"); } return View(contact); } [HttpPost] [Authorize(Roles = "admin")] public ActionResult ContactDetailDelete(int Id, contact_detail contact) { //Selected value will be deleted from the database try { objContact.commitDelete(Id); return RedirectToAction("ContactDetailIndex"); } catch { return View(); } } [Authorize(Roles = "admin")] public ActionResult Error() { //shows the Error view return View(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Calendar : MonoBehaviour { public float dayLength, dayTimer; public List<Month> months; public int currentDay, currentYear, monthIndex; public Month currentMonth; // Use this for initialization void Start() { GetResources(); StartCalendar(); } void GetResources() { Object[] m = Resources.LoadAll("Months", typeof(Month)); foreach (Month mo in m) months.Add(mo); } void StartCalendar() { currentDay = 1; currentYear = 564; currentMonth = months[0]; GameObject.Find("Controller").GetComponent<UIController>().SetDate(currentDay, currentYear, currentMonth.monthName); } // Update is called once per frame void Update() { DayProgression(); } //Progress through days by adding real time void DayProgression() { dayTimer += Time.deltaTime; if (dayTimer >= dayLength) { dayTimer = 0; AddDay(); } } //Add a day completed void AddDay() { currentDay++; if(currentMonth.days < currentDay) { if(currentMonth == months[months.Count-1]) { //New Year // currentYear++; currentDay = 1; monthIndex = 0; currentMonth = months[0]; } else { //New Month // currentDay = 1; monthIndex++; currentMonth = months[monthIndex]; } } GameObject.Find("Controller").GetComponent<UIController>().SetDate(currentDay, currentYear, currentMonth.monthName); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace bitirme.Models { public class otel { [Key] public int otelID { get; set; } [Required(ErrorMessage = "Lütfen boş alanları doldurunuz..")] [Display(Name = "Otel Adı:")] public string otelAdi { get; set; } [Required(ErrorMessage = "Lütfen boş alanları doldurunuz..")] [Display(Name = "Kullanıcı Adı:")] public string otelkullaniciAdi { get; set; } [Required(ErrorMessage = "Lütfen boş alanları doldurunuz..")] [DataType(DataType.Password)] public string otelSifre { get; set; } [Required(ErrorMessage = "Lütfen boş alanları doldurunuz..")] [Display(Name = "E-mail:")] public string otelEmail { get; set; } [Required(ErrorMessage = "Lütfen boş alanları doldurunuz..")] [Display(Name = "Telefon:")] public int otelTel { get; set; } [Required(ErrorMessage = "Lütfen boş alanları doldurunuz..")] public string sehir { get; set; } public string adres { get; set; } public string otelaciklama { get; set; } public string or { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaskMan.Domains { public class EncryptionKey { public string Salt { get; set; } public string Password { get; set; } public int Iterations { get; set; } public string InitialVector { get; set; } } }
using Chapter6.Contracts; using Chapter6.Interface; using Chapter6.Model; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Web; using System.Windows.Input; namespace Chapter6.ViewModel { public class TextAnalysisViewModel : ObservableObject { private WebRequest _webRequest; private string _inputQuery; public string InputQuery { get { return _inputQuery; } set { _inputQuery = value; RaisePropertyChangedEvent("InputQuery"); } } private string _result; public string Result { get { return _result; } set { _result = value; RaisePropertyChangedEvent("Result"); } } public ICommand DetectLanguageCommand { get; private set; } public ICommand DetectKeyPhrasesCommand { get; private set; } public ICommand DetectSentimentCommand { get; private set; } /// <summary> /// TextAnalysisViewModel constructor. Creates a new <see cref="WebRequest"/> object and command objects /// </summary> public TextAnalysisViewModel() { _webRequest = new WebRequest("ROOT_URI", "API_KEY"); DetectLanguageCommand = new DelegateCommand(DetectLanguage, CanExecuteOperation); DetectKeyPhrasesCommand = new DelegateCommand(DetectKeyPhrases, CanExecuteOperation); DetectSentimentCommand = new DelegateCommand(DetectSentiment, CanExecuteOperation); } /// <summary> /// Determines if operations can execute /// </summary> /// <param name="obj"></param> /// <returns>True if the input query is filled in, false otherwise</returns> private bool CanExecuteOperation(object obj) { return !string.IsNullOrEmpty(InputQuery); } /// <summary> /// Command function to detect the language of a given text /// Prints the result to the UI /// </summary> /// <param name="obj"></param> private async void DetectLanguage(object obj) { var queryString = HttpUtility.ParseQueryString("languages"); TextRequests request = new TextRequests { documents = new List<TextDocumentRequest> { new TextDocumentRequest { id = "FirstId", text = InputQuery } } }; TextResponse response = await _webRequest.MakeRequest<TextRequests, TextResponse>(HttpMethod.Post, queryString.ToString(), request); if(response.documents == null || response.documents.Count == 0) { Result = "No languages was detected."; return; } StringBuilder sb = new StringBuilder(); foreach (TextLanguageDocuments document in response.documents) { foreach (TextDetectedLanguages detectedLanguage in document.detectedLanguages) { sb.AppendFormat("Detected language: {0} with score {1}\n", detectedLanguage.name, detectedLanguage.score); } } Result = sb.ToString(); } /// <summary> /// Command function to detect the sentiment of a given text /// Prints the result to the UI /// </summary> /// <param name="obj"></param> private async void DetectSentiment(object obj) { var queryString = HttpUtility.ParseQueryString("sentiment"); TextRequests request = new TextRequests { documents = new List<TextDocumentRequest> { new TextDocumentRequest { id = "FirstId", text = InputQuery, language = "en" } } }; TextSentimentResponse response = await _webRequest.MakeRequest<TextRequests, TextSentimentResponse>(HttpMethod.Post, queryString.ToString(), request); if(response.documents == null || response.documents?.Count == 0) { Result = "No sentiments detected"; return; } StringBuilder sb = new StringBuilder(); foreach (TextSentimentDocuments document in response.documents) { sb.AppendFormat("Document ID: {0}\n", document.id); if (document.score >= 0.5) sb.AppendFormat("Sentiment is positive, with a score of {0}\n", document.score); else sb.AppendFormat("Sentiment is negative with a score of {0}\n", document.score); } Result = sb.ToString(); } /// <summary> /// Command function to detect key phrases in text. /// Will print the result to the UI /// </summary> /// <param name="obj"></param> private async void DetectKeyPhrases(object obj) { var queryString = HttpUtility.ParseQueryString("keyPhrases"); TextRequests request = new TextRequests { documents = new List<TextDocumentRequest> { new TextDocumentRequest { id = "FirstId", text = InputQuery, language = "en" } } }; TextKeyPhrasesResponse response = await _webRequest.MakeRequest<TextRequests, TextKeyPhrasesResponse>(HttpMethod.Post, queryString.ToString(), request); if (response.documents == null || response.documents?.Count == 0) { Result = "No key phrases found."; return; } StringBuilder sb = new StringBuilder(); foreach (TextKeyPhrasesDocuments document in response.documents) { sb.Append("Key phrases found:\n"); foreach (string phrase in document.keyPhrases) { sb.AppendFormat("{0}\n", phrase); } } Result = sb.ToString(); } } }
using System; namespace Ganss.Excel { /// <summary> /// Attribute that specifies the data format of an Excel cell. /// The format can either be a <a href="https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html">builtin format</a> /// or a <a href="https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4">custom format string</a>. /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class DataFormatAttribute: Attribute { /// <summary> /// Gets or sets the builtin format, see https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html for possible values. /// </summary> /// <value> /// The builtin format. /// </value> public short BuiltinFormat { get; set; } /// <summary> /// Gets or sets the custom format, see https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 for the syntax. /// </summary> /// <value> /// The custom format. /// </value> public string CustomFormat { get; set; } /// <summary> /// Initializes a new instance of the <see cref="DataFormatAttribute"/> class. /// </summary> /// <param name="format">The format, see https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html for possible values.</param> public DataFormatAttribute(short format) { BuiltinFormat = format; } /// <summary> /// Initializes a new instance of the <see cref="DataFormatAttribute"/> class. /// </summary> /// <param name="format">The format, see https://support.office.com/en-nz/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 for the syntax.</param> public DataFormatAttribute(string format) { CustomFormat = format; } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class PostReBid : System.Web.UI.Page { string obj_Authenticated; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; BizConnectClass obj_class = new BizConnectClass(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ChkAuthentication(); Bind(); } } public void Bind() { LblFrom.Text = Request.QueryString["from"].ToString(); LbTo.Text = Request.QueryString["to"].ToString(); Lbltrucktype.Text = Request.QueryString["trucktype"].ToString(); Lblcapacity.Text = Request.QueryString["capacity"].ToString(); Lblrouteprice.Text = Request.QueryString["price"].ToString(); txtbidprice.Text = Request.QueryString["price"].ToString(); } protected void ButSubmit_Click(object sender, EventArgs e) { int t = Convert.ToInt32(Request.QueryString["TID"].ToString()); int u = Convert.ToInt32(Session["UserID"].ToString()); int cl = Convert.ToInt32(Request.QueryString["clientid"].ToString()); int resp = obj_class.InsertReBid(LblFrom.Text, LbTo.Text, Lbltrucktype.Text, Lblcapacity.Text, txttrucksreq.Text, Lblrouteprice.Text, txtbidprice.Text, Convert.ToInt32(Request.QueryString["TID"].ToString()), Convert.ToInt32(Session["UserID"].ToString()), Convert.ToInt32(Request.QueryString["clientid"].ToString()), txtremarks.Text); if (resp == 1) { this.Page.ClientScript.RegisterStartupScript(typeof(Page), "notification", "window.alert('Quoted Successfully!');", true); } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; //obj_Navi.Visible = true; //obj_Navihome.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; // obj_Navi.Visible = true; //obj_Navihome.Visible = false; } }
using System.Collections.Generic; using System.Collections.ObjectModel; namespace CSharpUtils.Utils { class SizeLimitedCollection<T> : Collection<T> { public int Limit { get; set; } public SizeLimitedCollection(int limit) : base() { Limit = limit; Fit(); } public SizeLimitedCollection(int limit, IList<T> list) : base(list) { Limit = limit; Fit(); } public new void Add(T item) { base.Add(item); Fit(); } /// <summary> /// Make the collection fit. /// </summary> private void Fit() { while (Count > Limit) { RemoveAt(0); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; namespace eIVOGo.template { public partial class ContentControlTemplate : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } [Bindable(true)] public String ItemName { get { return actionItem.ItemName; } set { actionItem.ItemName = value; } } [Bindable(true)] public String FunctionTitle { get { return titleBar.ItemName; } set { titleBar.ItemName = value; } } } }
using System; namespace Codewars.RomanNumerals { internal class RomanDecode { internal static double Solution(string roman) { int sum = 0; for (int i = 0; i < roman.Length; i++) { var firstNumber = ToNumber(roman[i]); if (i + 1 < roman.Length) { var secondNumber = ToNumber(roman[i + 1]); if (firstNumber >= secondNumber) { sum += firstNumber; } else { sum += secondNumber - firstNumber; i++; } } else { sum += firstNumber; } } return sum; } private static int ToNumber(char roman) { return roman switch { 'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000, _ => 0, }; } } }
//Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe". using System; using System.Collections.Generic; using System.Text.RegularExpressions; class Palindromes { public static void checkIfPalindrome(string check) { bool ispalindrome = true; for (int i = 0; i < check.Length / 2; i++) { if (check[i] != check[check.Length - 1 - i]) { ispalindrome = false; return; } } if (ispalindrome == true && check.Length != 1) { Console.WriteLine(check); } } static void Main() { string input = "Write a program that extracts from a given text all palindromes, like ABBA, lamal, exe."; string[] words = Regex.Split(input, @"\W+"); foreach (var item in words) { checkIfPalindrome(item); } } }
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Wilddog.Sms.Util; namespace Wilddog.Sms.Http { public class WilddogHttpClient { /// <summary> /// The http client. /// </summary> private readonly HttpClient HttpClient; /// <summary> /// Initializes a new instance of the <see cref="T:Wilddog.Sms.Http.WilddogHttpClient"/> class. /// </summary> public WilddogHttpClient() { HttpClient = new HttpClient(); HttpClient.DefaultRequestHeaders.Add("UserAgent", Const.WILDDOG_SMS_USER_AGENT); } /// <summary> /// Processes the response. /// </summary> /// <returns>The response.</returns> /// <param name="responseTask">Response task.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> private T ProcessResponse<T>(Task<HttpResponseMessage> responseTask) where T : Response { HttpResponseMessage httpResponse = responseTask.Result; if (HttpStatusCode.OK.Equals(httpResponse.StatusCode)) { Task<string> responseBody = httpResponse.Content.ReadAsStringAsync(); Response response = JsonConvert.DeserializeObject<T>(responseBody.Result); return (T)response; } else if (HttpStatusCode.BadRequest.Equals(httpResponse.StatusCode) || HttpStatusCode.InternalServerError.Equals(httpResponse.StatusCode)) { Task<string> responseBody = httpResponse.Content.ReadAsStringAsync(); WilddogError wilddogError = JsonConvert.DeserializeObject<WilddogError>(responseBody.Result); return (T)Activator.CreateInstance(typeof(T), new object[] { false, wilddogError }); } else { WilddogError wilddogError = new WilddogError(httpResponse.StatusCode.ToString(), ""); return (T)Activator.CreateInstance(typeof(T), new object[] { false, wilddogError }); } } /// <summary> /// Dos the post. /// </summary> /// <returns>The post.</returns> /// <param name="url">URL.</param> /// <param name="content">Content.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public T DoPost<T>(string url, HttpContent content) where T : Response { Task<HttpResponseMessage> responseTask = HttpClient.PostAsync(url, content); return ProcessResponse<T>(responseTask); } /// <summary> /// Dos the get. /// </summary> /// <returns>The get.</returns> /// <param name="url">URL.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public T DoGet<T>(string url) where T : Response { Task<HttpResponseMessage> responseTask = HttpClient.GetAsync(url); return ProcessResponse<T>(responseTask); } } }
namespace StudentsAndCourses { using System; using System.Collections.Generic; public class School { private List<Course> courses = new List<Course>(); public List<Course> Courses { get { return this.courses; } set { if (value == null) { throw new NullReferenceException("Courses is null!"); } if (value.Count == 0) { throw new ArgumentException("Courses is empty!"); } this.courses = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RabbitInfrastructure { public class HandlerConfig<T> : IHandlerConfig where T : MessageBase { public string RoutingKey { get; set; } public string Exchange { get; set; } public Type MessageType { get { return typeof(T); } } public IMessageHandler<T> Handler { get; set; } public virtual object Handle(object msg) { return this.Handler != null ? this.Handler.Handle(msg as T) : null; } public HandlerConfig(IMessageHandler<T> handler) { RoutingKey = typeof(T).FullName.ToLowerInvariant(); Exchange = RabbitCfg.XCHG; Handler = handler; } } public class RPCHandlerConfig<T, TResponse> : IRPCHandlerConfig where T : MessageBase where TResponse : MessageBase { public string RoutingKey { get; set; } public string Exchange { get; set; } public Type MessageType { get { return typeof(T); } } public IMessageHandler<T> Handler { get; set; } public Type ResponseType { get { return typeof(TResponse); } } public RPCHandlerConfig(IMessageHandler<T> handler) { RoutingKey = typeof(T).FullName.ToLowerInvariant(); Exchange = RabbitCfg.XCHG; Handler = handler; } public virtual object Handle(object msg) { return this.Handler != null ? this.Handler.Handle(msg as T) : null; } } }
using EWF.Util.Log; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Text; namespace EWF.Util { public class GlobalExceptions : IExceptionFilter { private readonly LoggerHelper logger; private readonly IHostingEnvironment env; private IHttpContextAccessor accessor; public GlobalExceptions(IHostingEnvironment _env, LoggerHelper _logger, IHttpContextAccessor _accessor) { env = _env; logger = _logger; accessor = _accessor; } public void OnException(ExceptionContext context) { var json = new JsonErrorResponse(); //这里面是自定义的操作记录日志 if (context.Exception.GetType() == typeof(UserOperationException)) { json.Message = context.Exception.Message; if (env.IsDevelopment()) { json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息 } context.Result = new BadRequestObjectResult(json);//返回异常数据 } else { json.Message = "发生了未知内部错误"; if (env.IsDevelopment()) { json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息 } } //日志帮助类记录日志 logger.Exception(context.Exception); var ajaxResult = new AjaxResult { state = ResultType.error.ToString(), message = context.Exception.Message }; if (accessor.HttpContext.Request.IsAjax()) { context.Result = new ContentResult() { StatusCode = 200, ContentType = "application/json", Content = ajaxResult.ToJson() }; } else { if (accessor.HttpContext.Request.Method.ToUpper() == "POST") { context.Result = new ContentResult() { StatusCode = 200, ContentType = "application/json", Content = ajaxResult.ToJson() }; } else { context.Result = new InternalServerErrorObjectResult(json); } } } } }
using Microsoft.Xaml.Behaviors; using System.Text.RegularExpressions; using System.Windows.Controls; using System.Windows.Input; namespace MultiCommentCollector.Behavior { public class TextBoxBehavior : Behavior<TextBox> { private ExecutedRoutedEventHandler handler; public TextBoxBehavior() => handler = new(PreviewExecuted); protected override void OnAttached() { base.OnAttached(); AssociatedObject.PreviewTextInput += PreviewTextInput; if (handler is not null) { CommandManager.AddPreviewExecutedHandler(AssociatedObject, handler); } } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewTextInput -= PreviewTextInput; if (handler is not null) { CommandManager.RemovePreviewExecutedHandler(AssociatedObject, handler); } } private void PreviewTextInput(object sender, TextCompositionEventArgs e) => // 0-9のみ e.Handled = !new Regex("[0-9]").IsMatch(e.Text); private void PreviewExecuted(object sender, ExecutedRoutedEventArgs e) { // 貼り付けを許可しない if (e.Command == ApplicationCommands.Paste) { e.Handled = true; } } } }
using System; using System.IO; using System.Linq; using System.Net; using Shouldly; using Xunit; using Xunit.Abstractions; namespace aoc2019.Test { public class Test01 { private readonly ITestOutputHelper _testOutputHelper; public Test01(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Theory] [InlineData(12, 2)] [InlineData(14, 2)] [InlineData(1969, 654)] [InlineData(100756, 33583)] public void Part1(int input, int expected) { var solver = new Day01(); var result = solver.Solve(input); result.ShouldBe(expected); } [Fact] public void Part1Solution() { var solver = new Day01(); var data = InputDataHelper.GetLines(1); var result = data.Sum(d => solver.Solve(int.Parse(d))); _testOutputHelper.WriteLine(result.ToString()); } [Theory] [InlineData(14, 2)] [InlineData(1969, 966)] [InlineData(100756, 50346)] public void Part2(int input, int expected) { var solver = new Day01(); var result = solver.Solve2(input); result.ShouldBe(expected); } [Fact] public void Part2Solution() { var solver = new Day01(); var data = File.ReadAllLines("C:\\Code\\aoc2019\\Data\\input01.txt"); var result = data.Sum(d => solver.Solve2(int.Parse(d))); _testOutputHelper.WriteLine(result.ToString()); } } }
namespace NumberOccurencesInArray { using System; public class NumberOccurencesInArray { /// <summary> /// Write a method that counts how many times given number appears in given array. /// Write a test program to check if the method is working correctly. /// </summary> public static void Main(string[] args) { int[] arrayOne = { 1, 2, 3, 4, 5, 6, 7 }; int[] arrayTwo = { -1, -5, 5, 5, 4 }; int[] arrayThree = { 0, 0, 0, 0, 0, 0, 0, 0 }; if (OccurencesInArray(arrayOne, 3) == 1) { Console.WriteLine("Pass"); } else { Console.WriteLine("Fail"); } if (OccurencesInArray(arrayTwo, 5) == 2) { Console.WriteLine("Pass"); } else { Console.WriteLine("Fail"); } if (OccurencesInArray(arrayThree, 0) == 8) { Console.WriteLine("Pass"); } else { Console.WriteLine("Fail"); } } public static int OccurencesInArray(int[] array, int number) { int occurencesCount = 0; for (int i = 0; i < array.Length; i++) { if (array[i] == number) { occurencesCount++; } } return occurencesCount; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ClientConsole.Communication { class Client { Socket clientSocket; byte[] buffer = new byte[512]; Action<string> updater; public Client() { //this.updater = updater; try { TcpClient client = new TcpClient(); Console.WriteLine("connecting.."); client.Connect(IPAddress.Loopback, 10100); Console.WriteLine("client connected to "+ IPAddress.Loopback); clientSocket = client.Client; } catch { //updater("Server offline"); Console.WriteLine("Keine Verbinung zum Server möglich"); } } public void Send(string ship) { clientSocket.Send(Encoding.UTF8.GetBytes(ship)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TeamsOrganizerWebApp.Data.Models; namespace TeamsOrganizerWebApp.Data { public static class Data { public static List<Trip> Trips => allTrips; static List<Trip> allTrips = new List<Trip>() { new Trip() { Id=1, Name="Hamburg, DE", Description="Hamburg amtlich Freie und Hansestadt Hamburg (niederdeutsch Friee un Hansestadt Hamborg, Ländercode: HH), ist als Stadtstaat ein Land der Bundesrepublik Deutschland. Der amtliche Name verweist auf die Geschichte Hamburgs als Freie Reichsstadt und als führendes Mitglied des Handelsbundes der Hanse.", DateStarted = new DateTime(2020,02,25), DateCompleted = new DateTime(2020,03,1) }, new Trip() { Id=2, Name="Dresden, DE", Description="Dresden ist die Landeshauptstadt des Freistaates Sachsen. Mit rund 557.000 Einwohnern (November 2019[2]) ist Dresden, nach Leipzig, die zweitgrößte sächsische Kommune, zweitgrößte Stadt in den Neuen Bundesländern und die zwölftgrößte Stadt Deutschlands.", DateStarted = new DateTime(2020,02,25), DateCompleted = new DateTime(2020,03,1) }, new Trip() { Id=3, Name="Leipzig, DE", Description="Leipzig ist eine kreisfreie Stadt sowie mit 587.857 Einwohnern (31. Dezember 2018) die größte Stadt im Freistaat Sachsen und belegte 2018 in der Liste der Großstädte in Deutschland den achten Platz. Für Mitteldeutschland ist sie ein historisches Zentrum der Wirtschaft, des Handels und Verkehrs, der Verwaltung, Kultur und Bildung sowie für die „Kreativszene“.", DateStarted = new DateTime(2020,02,25), DateCompleted = new DateTime(2020,03,1) }, new Trip() { Id=4, Name="Hannover, DE", Description="Hannover ist die Hauptstadt des Landes Niedersachsen. Der am Südrand des Norddeutschen Tieflandes an der Leine und der Ihme gelegene Ort wurde 1150 erstmals erwähnt und erhielt 1241 das Stadtrecht. Hannover war ab 1636 welfische Residenzstadt, ab 1692 Residenz Kurhannovers, ab 1814 Hauptstadt des Königreichs Hannover, nach dessen Annexion durch Preußen ab 1866 Provinzhauptstadt der Provinz Hannover, nach Auflösung Preußens im August 1946 Hauptstadt des Landes Hannover und nach dessen Fusion mit den Freistaaten Braunschweig, Oldenburg und Schaumburg-Lippe im November 1946 niedersächsische Landeshauptstadt. Seit 1875 Großstadt, zählt Hannover heute mit 538.068 Einwohnern (Ende 2018) zu den 15 einwohnerreichsten Städten Deutschlands.", DateStarted = new DateTime(2020,02,25), DateCompleted = new DateTime(2020,03,1) }, new Trip() { Id=5, Name="Bonn, DE", Description="Die Bundesstadt Bonn ist eine kreisfreie Großstadt im Regierungsbezirk Köln im Süden des Landes Nordrhein-Westfalen. Mit 327.258 Einwohnern (Stand 31. Dezember 2018) zählt Bonn zu den zwanzig größten Städten Deutschlands. Bonn gehört zu den Metropolregionen Rheinland und Rhein-Ruhr sowie zur Region Köln/Bonn. Die Stadt an beiden Ufern des Rheins war von 1949 bis 1990 Bundeshauptstadt und bis 1999 Regierungssitz der Bundesrepublik Deutschland,[2] seither ist Bonn nur noch faktischer zweiter Regierungssitz Deutschlands.", DateStarted = new DateTime(2020,02,25), DateCompleted = new DateTime(2020,03,1) }, new Trip() { Id=7, Name="Berlin, DE", Description="Berlin ist die Hauptstadt der Bundesrepublik Deutschland und zugleich eines ihrer Länder.[14] Die Stadt ist mit rund 3,6 Millionen Einwohnern die bevölkerungsreichste und mit 892 Quadratkilometern auch die flächengrößte Gemeinde Deutschlands. Außerdem ist sie damit die einwohnerstärkste Stadt der Europäischen Union.[4] Sie bildet das Zentrum der Agglomeration Berlin mit rund 4,5 Millionen und der Metropolregion Berlin/Brandenburg mit rund 6 Millionen Einwohnern. Der Stadtstaat besteht aus zwölf Bezirken. Neben den Flüssen Spree und Havel befinden sich im Stadtgebiet kleinere Fließgewässer sowie zahlreiche Seen und Wälder.", DateStarted = new DateTime(2020,03,11), DateCompleted = new DateTime(2020,03,1) } }; } }
namespace SGDE.Domain.Repositories { #region Using using SGDE.Domain.Entities; using SGDE.Domain.Helpers; using System.Collections.Generic; #endregion public interface IClientRepository { List<Client> GetAllWithoutFilter(); List<Client> GetAllLite(string filter = null); QueryResult<Client> GetAll(int skip = 0, int take = 0, bool allClients = true, string filter = null); Client GetById(int id); Client Add(Client newClient); bool Update(Client client); bool Delete(int id); } }
using System; using System.IO; using System.Collections.Generic; namespace TaylorBurch_PA6 { class report { //Sort method public static void sortArray(master[] masterRecords, int count) { //Sort by team int minIndex = 0; long compare1 = 0; long compare2 = 0; for (int t = 0; t < count - 1; t++) { minIndex = t; for (int y = 0; y < count; y++) { compare1 = masterRecords[minIndex].getTeamID(); compare2 = masterRecords[y].getTeamID(); if (compare2.CompareTo(compare1) < 0) { minIndex = y; } if (minIndex != t) { swapArray(masterRecords, t, minIndex); } } } //Sort by student for (int s = 0; s < count - 1; s++) { minIndex = s; for (int y = 0; y < count; y++) { compare1 = masterRecords[minIndex].getStudentID(); compare2 = masterRecords[y].getStudentID(); if (compare2.CompareTo(compare1) < 0) { minIndex = y; } if (minIndex != s) { swapArray(masterRecords, s, minIndex); } } } } //Individual student report sorted by team public static void studentReport(master[] masterRecords, int count, List<string> studentList, List<string> teamAvgList) { long student = 0; long nextStudent = 0; long team = 0; long nextTeam = 0; int avgAScore = 0; //Average analytic score of inidividual int avgCommScore = 0; //Average communication score of inidividual int avgTechScore = 0; //Average technical score of individual int totalAvg = 0; int teamAvg = 0; string output = ""; //Output to add to student avg report string teamOutput = ""; //Output of team avg to file. sortArray(masterRecords, count); //Calculate averages for (int x = 0; x < count; x++) { student = masterRecords[x].getStudentID(); nextStudent = masterRecords[x + 1].getStudentID(); team = masterRecords[x].getTeamID(); nextTeam = masterRecords[x].getTeamID(); avgAScore = avgAScore + masterRecords[x].getAnalScore(); avgCommScore = avgCommScore + masterRecords[x].getCommScore(); avgTechScore = avgTechScore + masterRecords[x].getTechScore(); totalAvg = totalAvg + masterRecords[x].getAvgScore(); teamAvg = teamAvg + totalAvg; if(student != nextStudent) { output = "Team: " + team + " Student: " + student + " Avg Analytic Score: " + avgAScore + " Avg Communication Score: " + avgCommScore + " Avg TechScore: " + avgTechScore + " Total Avg: " + totalAvg; studentList.Add(output); avgAScore = 0; avgCommScore = 0; avgTechScore = 0; totalAvg = 0; } if(team != nextTeam) { teamOutput = "Team Name: " + masterRecords[x].getTeamName() + "Team ID: " + team + " Total Team Avg: " + totalAvg; teamAvgList.Add(teamOutput); teamAvg = 0; } } //Save report to output file. Console.WriteLine("Please enter a name you would like to save this report as. Remember to include the .txt extension."); string file = Console.ReadLine(); StreamWriter avgReport = new System.IO.StreamWriter(file); for (int j = 0; j < teamAvgList.Count; j++) { avgReport.WriteLine(teamAvgList[j]); } for (int i = 0; i < studentList.Count; i++) { avgReport.WriteLine(studentList[i]); } Console.WriteLine("Report sucessfully generated."); Console.ReadKey(); } //Method to swap positions in array when sorting public static void swapArray(master[] masterRecords, int x, int minIndex) { master temp; temp = masterRecords[x]; masterRecords[x] = masterRecords[minIndex]; masterRecords[minIndex] = temp; } //Top 5 students and teams report public static void topFiveReport(master[] masterRecords, int count) { sortArray(masterRecords, count); long curStu = 0; long nextStu = 0; int studentAvg = 0; long curTeam = 0; long nextTeam = 0; int teamAvg = 0; int i = 0; //Counter of students in top 5 int j = 0; //Counter of teams in top 5 int stuBottom = masterRecords[0].getAvgScore(); int teamBottom = masterRecords[0].getAvgScore(); List<string> top5Stu = new List<string>(); List<string> top5Teams = new List<string>(); for (int x = 0; x < count; x++) { studentAvg = studentAvg + masterRecords[x].getAvgScore(); curStu = masterRecords[x].getStudentID(); nextStu = masterRecords[x + 1].getStudentID(); teamAvg = teamAvg + studentAvg; curTeam = masterRecords[x].getTeamID(); nextTeam = masterRecords[x + 1].getTeamID(); if(curStu != nextStu) { if(stuBottom < studentAvg) { top5Stu[i] = masterRecords[x].getStudentName(); i++; } studentAvg = 0; if(teamBottom < teamAvg) { top5Teams[j] = masterRecords[x].getTeamName(); j++; } } } //Save report to output file. Console.WriteLine("Please enter a name you would like to save this report as. Remember to include the .txt extension."); string file = Console.ReadLine(); StreamWriter top5Report = new System.IO.StreamWriter(file); top5Report.WriteLine("Top 5 Teams: "); for (int y = 0; y < top5Teams.Count; y++) { top5Report.WriteLine(top5Teams[y]); } top5Report.WriteLine("Top 5 Students: "); for (int z = 0; z < top5Stu.Count; z++) { top5Report.WriteLine(top5Stu[z]); } Console.WriteLine("Report sucessfully generated."); Console.ReadKey(); } //Report on number of evaluations done by a specific evaluator public static void evalNumReport(master[] masterRecords, int count) { //Sort by evaluator int minIndex = 0; long compare1 = 0; long compare2 = 0; for (int x = 0; x < count - 1; x++) { minIndex = x; for (int y = 0; y < count; y++) { compare1 = masterRecords[minIndex].getEvaluatorID(); compare2 = masterRecords[y].getEvaluatorID(); if (compare2.CompareTo(compare1) < 0) { minIndex = y; } if (minIndex != x) { swapArray(masterRecords, x, minIndex); } } } //Find all evals per evaluator StreamWriter evalCountReport = new System.IO.StreamWriter("EvaluatorCountReport.txt"); int evalCounter = 0; //Number of evals per evaluator long eval1 = 0; long eval2 = 0; for (int z = 0; z < count; z++) { eval1 = masterRecords[z].getEvaluatorID(); eval2 = masterRecords[z + 1].getEvaluatorID(); evalCounter = evalCounter + 1; if(eval1 != eval2) { evalCountReport.WriteLine("Evaluator: " + eval1 + " Number of Evals: " + evalCounter); evalCounter = 0; } } Console.WriteLine("Report sucessfully generated."); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BankAccount.BLL; namespace BankAccount.BLL { public class AccountManager { #region Create Methods public static List<Account> Accounts = ReadFromFile(); #endregion #region Read Methods public static List<Account> ReadFromFile() { string path = @"C:\Users\William\source\repos\BankAccount\BankAccount.BLL\bin\Debug\Accounts.txt"; if (File.Exists(path)) { } else throw new Exception($"Could not find file at {path}"); string[] rows = File.ReadAllLines(path); List<Account> accounts = new List<Account>(); for (int i = 0; i < rows.Length; i++) { string[] columns = rows[i].Split(';'); Account account = new Account { Name = columns[0], Address = columns[1], Phone = columns[2], Password = columns[3], UserAccount = (Account.AccountType)Enum.Parse(typeof(Account.AccountType), columns[4], true), AccountNumber = Convert.ToInt32(columns[5]) }; accounts.Add(account); } return accounts; } public List<Account> GetAccounts() { return Accounts; } public string DisplayBalance(Account account) { decimal a = account.Balance; string b = a.ToString(); return b; } /* public GetAccountResponse AccountLogin(GetAccountRequest request) { GetAccountResponse response = new GetAccountResponse(); foreach (Account account in Accounts) { if (account.AccountNumber == request.AccountNumber) { if (request.Password == account.Password) { response.response = ResponseEnums.GetResponse.Success; response.Account = account; return response; } else { response.response = ResponseEnums.GetResponse.Fail; return response; } } } response.response = ResponseEnums.GetResponse.Unknown; return response; } */ public GetAccountResponse AccountLogin(GetAccountRequest request) { GetAccountResponse response = new GetAccountResponse(); Account a = Accounts.FirstOrDefault(account => account.AccountNumber == request.AccountNumber); if (request.Password == a.Password) { response.response = ResponseEnums.GetResponse.Success; response.Account = a; return response; } if (request.Password != a.Password) { response.response = ResponseEnums.GetResponse.Fail; return response; } response.response = ResponseEnums.GetResponse.Unknown; return response; } //public GetLogoutResponse AccountLogout(GetLogoutRequest request) #endregion #region Update Methods public Account OpenNewAccount(string name, string address, string phonenumber, string password, Account.AccountType type) // method to open new account { Account newAccount = new Account ( name, address, phonenumber, password, type ); WriteToFile(newAccount); Accounts.Add(newAccount); return newAccount; } public void WriteToFile(Account input) { GetAccountResponse response = new GetAccountResponse(); foreach (Account account in Accounts) { if (account == input) { throw new Exception("Can't add data that's already there, dummy!"); } } string path = @"C:\Users\William\source\repos\BankAccount\BankAccount.BLL\bin\Debug\Accounts.txt"; if (File.Exists(path)) { } else throw new Exception($"Could not find file at {path}"); string output = ""; string[] columns = new string[6]; columns[0] = input.Name; columns[1] = input.Address; columns[2] = input.Phone; columns[3] = input.Password; columns[4] = input.UserAccount.ToString(); columns[5] = input.AccountNumber.ToString(); for (int i = 0; i < columns.Length; i++) { if (i == 0) output = columns[0]; else output += @";" + columns[i]; } using (StreamWriter writer = File.AppendText(path)) { writer.WriteLine(); writer.Write(output); } } public string ChangeName(string name) { return name; } public string ChangeAddress(string address) { return address; } public string ChangePhoneNumber(string number) { return number; } public GetAccountResponse Deposit(Account account, decimal x) { GetAccountResponse response = new GetAccountResponse(); response.Account = account; if (x <= 0) { response.response = ResponseEnums.GetResponse.Fail; return response; } if (x > 0) { response.Account.Balance += x; response.response = ResponseEnums.GetResponse.Success; return response; } else { response.response = ResponseEnums.GetResponse.Unknown; return response; } } public decimal Withdraw(decimal x) { return x; } public Account.AccountType ChangeAccountType(Account.AccountType accountType) { return accountType; } #endregion #region Delete Methods public bool CloseAccount(Account account) // method to close existing account { Account oldAccount = account; return true; } #endregion } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using Orbital.Framework; namespace Orbital.Mapping { public class Room { public Map Map; public IntRect Bounds; public List<Room> Neighbors; public List<Entrance> Entrances; public bool IsCorridor; public bool IsLarge; public Tileset Tileset; public Transform Transform; public bool IsBuilt; public Room(Map map) { Map = map; Neighbors = new List<Room>(); Entrances = new List<Entrance>(); } public List<Entrance> GetEntrances(Point2 pos) { var e = new List<Entrance>(4); for (int i = 0; i < Entrances.Count; i++) { if (Entrances[i].Bounds.Contains(pos)) e.Add(Entrances[i]); } return e; } public Entrance GetEntrance(Point2 pos, Direction2 dir) { return GetEntrance(pos, Point2.FromDirection((Direction2)dir)); } public Entrance GetEntrance(Point2 pos, Point2 dir) { if (!Map.IsInBounds(pos)) return null; if (Map.GetTileType(pos) != TileType.Entrance) return null; for (int i = 0; i < Entrances.Count; i++) { var e = Entrances[i]; if (e.Bounds.Contains(pos) && e.Direction == dir) return e; } return null; } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Collections.Generic; using System.Linq; using Serializable = System.SerializableAttribute; using System.Reflection; using System.Text; using System.Diagnostics; using System.Text.RegularExpressions; using Debug = UnityEngine.Debug; namespace CoreEditor.AssemblyPacker { public class Packer : ScriptableObject { [SerializeField] Packer[] m_Dependencies; [SerializeField] PackerAssembly[] m_Assemblies; public Object[] m_ExtraPackageObjects; string m_PreviousLocation; List<string> m_ExtraGeneratedFiles = new List<string>(); class AssemblyGenerationManifest { Dictionary<string,string> mGeneratedAssemblies = new Dictionary<string, string>(); public List<string> GeneratedAssemblies { get { var assemblies = new List<string>(); foreach ( var path in mGeneratedAssemblies.Keys ) assemblies.Add( path ); return assemblies; } } public void Prepare( string path ) { if ( File.Exists( path ) ) { if ( IsDummyAssembly( path ) ) { var tempFolderPath = FileUtil.GetUniqueTempPathInProject() + "/"; Directory.CreateDirectory( tempFolderPath ); var tempDllPath = tempFolderPath + Path.GetFileName( path ); File.Move( path, tempDllPath ); if ( File.Exists( path + ".mdb" )) File.Move( path + ".mdb", tempDllPath + ".mdb" ); mGeneratedAssemblies.Add( path, tempDllPath ); } else { File.Delete( path ); File.Delete( path + ".mdb" ); mGeneratedAssemblies.Add( path, string.Empty ); } } else { mGeneratedAssemblies.Add( path, string.Empty ); } } public void Restore() { foreach( var assembly in mGeneratedAssemblies ) { if ( File.Exists( assembly.Value ) ) { File.Copy( assembly.Value, assembly.Key, true ); if ( File.Exists( assembly.Value+".mdb" )) File.Copy( assembly.Value+".mdb", assembly.Key + ".mdb", true ); Directory.Delete( Path.GetDirectoryName( assembly.Value ), true ); } } } } public void PackAssembly () { try { EditorApplication.LockReloadAssemblies(); EditorUtility.DisplayProgressBar( "Assembly Packer", "Building Assemblies", 0f ); var manifest = CreateAssemblies(); EditorUtility.DisplayProgressBar( "Assembly Packer", "Building Package", 0.5f ); CreatePackage( manifest.GeneratedAssemblies.ToArray() ); manifest.Restore(); GenerateDummyAssemblyData(); m_ExtraGeneratedFiles.Clear(); } catch ( System.Exception e ) { Debug.LogException( e, this ); } finally { m_ExtraGeneratedFiles.Clear(); EditorUtility.ClearProgressBar(); EditorApplication.UnlockReloadAssemblies(); } } List<PackerAssembly> AssemblyDependencies { get{ var usedAssemblies = new HashSet<PackerAssembly>(); var assemblyDependencies = new List<PackerAssembly>(); foreach( var dependency in m_Dependencies ) { var assemblies = new List<PackerAssembly>(); assemblies.AddRange( dependency.AssemblyDependencies ); assemblies.AddRange( dependency.m_Assemblies ); foreach( var assembly in assemblies ) { if ( usedAssemblies.Contains( assembly ) == false ) { usedAssemblies.Add( assembly ); assemblyDependencies.Add( assembly ); } } } return assemblyDependencies; } } HashSet<Object> AssetsDependencies { get{ var usedAssets = new HashSet<Object>(); foreach( var dependency in m_Dependencies ) { usedAssets.UnionWith( dependency.AssetsDependencies ); usedAssets.UnionWith( dependency.m_ExtraPackageObjects ); } return usedAssets; } } List<PackerAssembly> AllAssemblies { get { var assemblies = new List<PackerAssembly>(); assemblies.AddRange( AssemblyDependencies ); assemblies.AddRange( m_Assemblies ); return assemblies.OrderBy( a=> a.name.Contains("Editor")).ToList(); } } AssemblyGenerationManifest CreateAssemblies( ) { var assemblyPaths = new List<string>(); var assemblies = AllAssemblies; var manifest = new AssemblyGenerationManifest(); foreach ( var assembly in assemblies ) { var paths = new List<string>(); foreach ( var sourceObject in assembly.m_Sources ) { var path = AssetDatabase.GetAssetPath( sourceObject ); if ( Directory.Exists( path ) ) paths.AddRange( Directory.GetFiles( path, "*.cs", SearchOption.AllDirectories ) ); else if ( Path.GetExtension( path ) == ".cs" ) paths.Add( path ); else Debug.LogError( string.Format( "Invalid source in Compiler: {0}", path ), this ); } var sources = paths.ToArray(); var references = new List<string>() { typeof(string).Assembly.Location, GetFrameWorksFolder() + "Managed/UnityEngine.dll", UnityEngineUIAssemblyPath }; bool isEditor = assembly.name.Contains("Editor"); if ( isEditor ) references.Add( GetFrameWorksFolder() + "Managed/UnityEditor.dll" ); references.AddRange( assembly.m_AssemblyReferences.Select( o => AssetDatabase.GetAssetPath( o ) ) ); references.AddRange( assemblyPaths ); var defines = assembly.Defines; var dllPath = assembly.AssemblyPath; manifest.Prepare( dllPath ); Directory.CreateDirectory( Path.GetDirectoryName( dllPath ) ); var output = EditorUtility.CompileCSharp( sources, references.ToArray(), defines.ToArray(), dllPath ); if ( OutputContainsError( output ) == false ) { AssetDatabase.ImportAsset( dllPath ); assemblyPaths.Add( dllPath ); if ( assembly.m_ExportInlineDocumentation ) { var docFile = dllPath.Replace( ".dll", ".xml" ); GenerateDoc( docFile, dllPath, sources, references, defines ); if ( File.Exists( docFile ) ) { AssetDatabase.ImportAsset( docFile ); m_ExtraGeneratedFiles.Add( docFile ); } } if ( assembly.m_IsDebug ) { var mdbFile = dllPath + ".mdb"; AssetDatabase.ImportAsset( mdbFile ); m_ExtraGeneratedFiles.Add( mdbFile ); } } else { Debug.LogError( string.Join( "\n", output ), this ); } } return manifest; } static bool OutputContainsError( string[] output ) { foreach ( var line in output ) { if ( line.Contains( "error CS" ) ) return true; } return false; } static string UnityEngineUIAssemblyPath { get { return Assembly.GetAssembly( typeof( UnityEngine.UI.Image ) ).Location; } } void CreatePackage( params string[] extraFiles ) { var paths = new HashSet<string>(); var allObjects = AssetsDependencies; allObjects.UnionWith( m_ExtraPackageObjects ); foreach( var obj in allObjects ) { if ( obj != null ) paths.Add( AssetDatabase.GetAssetPath( obj ) ); } foreach ( var docFile in m_ExtraGeneratedFiles ) paths.Add( docFile ); paths.UnionWith( extraFiles ); string file = EditorUtility.SaveFilePanel( "Package save location", Directory.GetCurrentDirectory(), name, "unityPackage" ); if ( string.IsNullOrEmpty( file ) == false) { ExportPackageOptions flags = ExportPackageOptions.Recurse | ExportPackageOptions.IncludeDependencies; AssetDatabase.ExportPackage( paths.ToArray(), file, flags ); } } public static string GetFrameWorksFolder() { if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.LinuxEditor) { return (Path.GetDirectoryName(EditorApplication.applicationPath) + "/Data/"); } #if UNITY_5_4_OR_NEWER return (EditorApplication.applicationPath + "/Contents/"); #else return (EditorApplication.applicationPath + "/Contents/Frameworks/"); #endif } public static string MonoFolder{ get { return GetFrameWorksFolder() + "Mono/bin"; } } void GenerateDoc( string docFile, string dllPath, string[] srcs , List<string> references, List<string> defines ) { var sb = new StringBuilder(); foreach( var src in srcs ) sb.Append( string.Format( "\"{0}\" ", src ) ); foreach( var reference in references ) sb.Append( string.Format( "-r:\"{0}\" ", reference ) ); foreach( var define in defines ) sb.Append( string.Format( "-define:\"{0}\" ", define ) ); var commandLineArgs = string.Format( "{0} -sdk:2 -t:library -out:{1} -doc:{2}", sb, "Temp/"+ Path.GetFileName( dllPath ), docFile); var proc = new Process(); if (Application.platform == RuntimePlatform.WindowsEditor) proc.StartInfo.FileName = "\"" + MonoFolder + "/gmcs.bat\""; else proc.StartInfo.FileName = "mcs"; proc.StartInfo.Arguments = commandLineArgs; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.UseShellExecute = false; if (Application.platform == RuntimePlatform.WindowsEditor) proc.StartInfo.EnvironmentVariables["PATH"] = System.Environment.GetEnvironmentVariable("PATH")+";" + "\""+MonoFolder+"\""; else proc.StartInfo.EnvironmentVariables["PATH"] = System.Environment.GetEnvironmentVariable("PATH")+":" + MonoFolder; try { proc.Start(); proc.WaitForExit(); } catch( System.Exception e ) { Debug.LogException( e ); } } public void GenerateDummyAssemblyData () { var dummySrcPath = FileUtil.GetUniqueTempPathInProject() + ".cs"; File.WriteAllText( dummySrcPath,"internal class Dummy{}"); foreach ( var assembly in AllAssemblies ) { var assemblyPath = assembly.AssemblyPath; Directory.CreateDirectory( Path.GetDirectoryName( assemblyPath ) ); if ( File.Exists( assemblyPath ) == false || IsDummyAssembly( assemblyPath ) == false ) EditorUtility.CompileCSharp( new string[]{dummySrcPath}, new string[]{}, assembly.Defines.ToArray(), assemblyPath ); ImportAssetWithMeta( assemblyPath, assembly.m_AssemblyMeta ); if ( assembly.m_IsDebug ) ImportAssetWithMeta( assemblyPath + ".mdb", assembly.m_AssemblyMDBMeta ); else AssetDatabase.DeleteAsset( assemblyPath + ".mdb" ); var docPath = assemblyPath.Substring(0, assemblyPath.Length - 4 ) + ".xml"; if ( assembly.m_ExportInlineDocumentation ) { File.WriteAllText(docPath,string.Format( @"<?xml version=""1.0""?><doc><assembly><name>{0}</name></assembly><members></members></doc>" , Path.GetFileNameWithoutExtension( docPath ) ) ); ImportAssetWithMeta( docPath, assembly.m_DocumentationMeta ); } else { AssetDatabase.DeleteAsset( docPath ); } } File.Delete( dummySrcPath ); } static void ImportAssetWithMeta( string path, PackerAssembly.Meta meta ) { AssetDatabase.ImportAsset( path, ImportAssetOptions.ForceSynchronousImport ); if ( meta.IsGUIDSpecified ) { var metaPath = path + ".meta"; var currentMeta = File.ReadAllText( metaPath ); var newMeta = Regex.Replace( currentMeta, @"guid:\s[0-9a-f]{32}", string.Format( @"guid: {0}", meta.GUID ) ); if ( currentMeta != newMeta ) { File.WriteAllText( metaPath, newMeta ); AssetDatabase.ImportAsset( path, ImportAssetOptions.ForceSynchronousImport ); } } } static bool IsDummyAssembly( string path ) { try { var assembly = Assembly.LoadFile( path ); return assembly.GetType( "Dummy", false ) != null; } catch { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Garage.Vehicles { abstract class Vehicle { public string Fuel { get; set; } public string Color { get; set; } public string PassengerOccupancy { get; set; } public virtual void Refuel() { Console.WriteLine("I'm refueling"); } public virtual void Driving() { Console.WriteLine("I'm driving"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Media; using Grisaia.Mvvm.Commands; using Grisaia.Mvvm.Input; namespace Grisaia.SpriteViewer.Commands { public interface IRelayInfoCommand : IRelayCommandBase, INotifyPropertyChanged { #region Properties /// <summary> /// Gets or sets the UI specific info for the command. /// </summary> RelayInfo Info { get; set; } /// <summary> /// Gets the display text for the command. /// </summary> string Text { get; } /// <summary> /// Gets the display icon for the command. /// </summary> ImageSource Icon { get; } /// <summary> /// Gets the input gesture for the command. /// </summary> AnyKeyGesture InputGesture { get; } #endregion } }
using System; using System.Configuration; using System.Threading.Tasks; using System.Web.Mvc; using Compilify.Models; using Compilify.Web.Services; using Newtonsoft.Json; using SignalR; namespace Compilify.Web.EndPoints { public class ExecuteEndPoint : PersistentConnection { static ExecuteEndPoint() { int timeout; if (!int.TryParse(ConfigurationManager.AppSettings["Compilify.ExecutionTimeout"], out timeout)) { timeout = DefaultExecutionTimeout; } ExecutionTimeout = TimeSpan.FromSeconds(timeout); } private const int DefaultExecutionTimeout = 30; private static readonly TimeSpan ExecutionTimeout; /// <summary> /// Handle messages sent by the client.</summary> protected override Task OnReceivedAsync(string connectionId, string data) { var post = JsonConvert.DeserializeObject<Post>(data); var command = new ExecuteCommand { ClientId = connectionId, Code = post.Content, Classes = post.Classes, Submitted = DateTime.UtcNow, TimeoutPeriod = ExecutionTimeout }; var message = command.GetBytes(); var gateway = DependencyResolver.Current.GetService<RedisConnectionGateway>(); var redis = gateway.GetConnection(); return redis.Lists.AddLast(0, "queue:execute", message) .ContinueWith(t => { if (t.IsFaulted) { return Send(new { status = "error", message = t.Exception != null ? t.Exception.Message : null }); } return Send(new { status = "ok" }); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using Epandemia.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace Epandemia.DAL { public class EpandemiaInitializer : DropCreateDatabaseIfModelChanges<EpandemiaContext> { protected override void Seed(EpandemiaContext context) { var roleManager = new RoleManager<IdentityRole>( new RoleStore<IdentityRole>(new ApplicationDbContext())); var userManager = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(new ApplicationDbContext())); roleManager.Create(new IdentityRole("Admin")); var user = new ApplicationUser { UserName = "karol.gawrysiuk@gmail.com" }; string password = "Admin123456@"; userManager.Create(user, password); userManager.AddToRole(user.Id, "Admin"); var hospitals = new List<Hospital> { new Hospital { Name = "Szpital Wojewódzki w Siedlcach", City = City.Siedlce, Street = "Poniatowskiego", MaxBeds = 200 }, new Hospital { Name = "Szpital w Warszawie", City = City.Warszawa, Street = "Kleberga", MaxBeds = 1000 } }; hospitals.ForEach(h => context.Hospitals.Add(h)); context.SaveChanges(); var employees = new List<Employee> { new Employee {FirstName = "Karol", LastName = "Gawrysiuk", Age = 28, Hospital = hospitals[0] }, new Employee {FirstName = "Jakub", LastName = "Sidoruk", Age = 27, Hospital = hospitals[0] } }; employees.ForEach(e => context.Employees.Add(e)); context.SaveChanges(); var users = new List<User> { new User { FirstName = "Michał", LastName = "Woźniak", Age = 88, Hospital = hospitals[1], Gender = Gender.Male, DateAdded = DateTime.Parse("2020-10-30") }, new User { FirstName = "Jacek", LastName = "Placek", Age = 92, Hospital = hospitals[1], Gender = Gender.Male, DateAdded = DateTime.Parse("2020-10-30") } }; users.ForEach(u => context.Users.Add(u)); context.SaveChanges(); } } }
using Microsoft.Extensions.Logging; namespace Shakespokemon.Etl.Core { public interface IPokemonLoadService { /// <summary> /// Extract Pokemons and transform their description in a Shakespearean style before to load the results in local database. /// </summary> void Process(); } public class PokemonLoadService : IPokemonLoadService { private IPokemonSourceRepository _source; private IPokemonDestinationRepository _destination; private ILogger<PokemonLoadService> _logger; public PokemonLoadService(IPokemonSourceRepository source, IPokemonDestinationRepository destination, ILogger<PokemonLoadService> logger) { _source = source; _destination = destination; _logger = logger; } public void Process() { int addedCount = 0; var pokemons = _source.GetAll(); foreach(var pokemon in pokemons) { if(!_destination.TryFind(pokemon.Name, out var _)) { _destination.Add(pokemon); addedCount++; } } _logger.LogInformation($"Added {addedCount} new Pokémons."); } } }
namespace osu.Game.Rulesets.Sentakki.Objects { public class Tap : SentakkiHitObject { } }
using UnityEngine; using System.Collections; public class MovimientoJugador : MonoBehaviour { Rigidbody2D rg; //Le asignamos velocidadjugador 8 public float velocidadjug=8f; // Use this for initialization void Start () { //llamamos al rigidbody rg = GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { //Si pulsamos A le aplicamos al rigidbody al que se apolica una velicdad, //en el eje x la velocidadjug que es 8, y ninguna al eje y if(Input.GetKey(KeyCode.A)) { //ponemos menos para que sea -8 rg.velocity = (new Vector2 (-(velocidadjug), rg.velocity.y)); } //Lo mismo que hemos puesto arriba if(Input.GetKey(KeyCode.D)) { rg.velocity = (new Vector2 ((velocidadjug),rg.velocity.y)); } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class Country { public Guid CountryId; public String CountryName; public String CountryCode; public String Continent; public String Currency; public Boolean CustomsRequired; public Double? TaxRate; public String AddressFormat; public List<CountryRegion> Regions; public Int32 RegionsCount; } }
using System; using UnityEngine; [System.Serializable] [CreateAssetMenu] public class ConsumableItemData : BaseItemData { }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("NAX04_Noth")] public class NAX04_Noth : NAX_MissionEntity { public NAX04_Noth(IntPtr address) : this(address, "NAX04_Noth") { } public NAX04_Noth(IntPtr address, string className) : base(address, className) { } public void InitEmoteResponses() { base.method_8("InitEmoteResponses", Array.Empty<object>()); } public void PreloadAssets() { base.method_8("PreloadAssets", Array.Empty<object>()); } public bool m_cardLinePlayed { get { return base.method_2<bool>("m_cardLinePlayed"); } } public bool m_heroPowerLinePlayed { get { return base.method_2<bool>("m_heroPowerLinePlayed"); } } } }
using MobileWx.Bll; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MobileWx.Model; using MobileWx.Web.Models; using Sys.Utility; using System.Text; namespace MobileWx.Web.Controllers { public class UserController : Controller { /// <summary> /// 网页授权获取用户的openid后,验证关注者是否关注微信 /// </summary> /// <param name="code"></param> /// <param name="state"></param> /// <returns></returns> public ActionResult WxAuth(string code = "", string state = "") { if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(state)) { return RedirectToAction("wxerror"); } //获取 WxAuthorizeAccessToken token = BllSubscribeUser.Get().GetAccessTokenByAuthorizeCode(code); if (token == null) { Loger.Error(" 取回token失败;code=" + code); return RedirectToAction("wxerror", new { code = token.errcode }); } else if (!string.IsNullOrWhiteSpace(token.errcode)) { Loger.Debug(" 取回token返回错误;errcode=" + token.errcode); return RedirectToAction("wxerror", new { code = token.errcode }); } string openid = token.openid; Loger.Debug(" 取回token;" + openid); string url = HttpUtility.UrlDecode(state); StringBuilder urlredirect = new StringBuilder(); urlredirect.Append(url); if (!url.Contains('?')) { urlredirect.Append("?"); } else { urlredirect.Append("&"); } //获取code成功后跳转到指定的链接,参数中添加openid和错误代码 urlredirect.AppendFormat("openid={0}", openid); Loger.Debug("成功跳转链接:" + urlredirect.ToString()); return Redirect(urlredirect.ToString()); } public ActionResult WXError(string code = "") { return View(); } } }
using System; using NUnit.Framework; using AddressBook.Modules.Tests; namespace AddressBook.Modules.Tests { [TestFixture] class RecordTests { [Test] public void TestIfRecordIsValid() { var rec = new Record {_id = 123,_age = 20,_firstname="John",_lastname="Doe",_sex="M"}; Assert.AreEqual(rec._id, 123); Assert.AreEqual(rec._age, 20); Assert.AreEqual(rec._firstname, "John"); Assert.AreEqual(rec._lastname, "Doe"); Assert.AreEqual(rec._sex, "M"); } } }
using UnityEngine; namespace TypingGameKit.AlienTyping { /// <summary> /// Destroys the game object after a specified amount of time. /// </summary> public class SelfDestruct : MonoBehaviour { [SerializeField] private float _secondsToExist = 1f; private void Start() { Destroy(gameObject, _secondsToExist); } } }
using HabitatReStoreMobile.Interfaces; using HabitatReStoreMobile.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using HabitatReStoreMobile.ServiceReference1; using System.ServiceModel; using System.Text.RegularExpressions; using System.Collections.ObjectModel; namespace HabitatReStoreMobile.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class VolunteerFormPage : ContentPage { ObservableCollection<VolunteerCategory> volunteerCategories = new ObservableCollection<VolunteerCategory>(); List<VolunteerRoleListItem> volunteerRoleItems = new List<VolunteerRoleListItem>(); public VolunteerFormPage() { InitializeComponent(); if (App.service == null) { App.InitializeService(); } InitializePickers(); } private void btnSubmit_Clicked(object sender, EventArgs e) { VolunteerInfo newVolunteer = GetVolunteer(); if (ValidateAll(newVolunteer)) { btnSubmit.IsEnabled = false; DependencyService.Get<IToast>().ShortAlert("Submitting... please wait."); InsertVolunteerToDatabase(newVolunteer); } } private VolunteerInfo GetVolunteer() { string fName, lName, mName, email, phone, ssn, city, zip, address, address2; string state, role; char gender; DateTime dob; ObservableCollection<int> roleIDs = new ObservableCollection<int>(); fName = entFName.Text; lName = entLName.Text; mName = entMName.Text; email = entEmail.Text; //strip non-numeric characters, if null return empty space phone = Regex.Replace(entPhone.Text ?? "", "[^0-9]", ""); ssn = entSSN.Text; city = entCity.Text; zip = entZIP.Text; address = entAddress.Text; address2 = entAddress2.Text; gender = pickGender.SelectedItem.ToString()[0]; state = pickState.SelectedItem.ToString(); //get selected roles foreach (VolunteerRoleListItem vc in rolePickerList.ItemsSource) { if (vc.Selected) { roleIDs.Add(vc.Category_ID); } } dob = pickDOB.Date; VolunteerInfo newVolunteer = new VolunteerInfo(); newVolunteer.Status_Map_ID = 1; newVolunteer.First_Name = fName; newVolunteer.Middle_Name = mName; newVolunteer.Last_Name = lName; newVolunteer.Gender = gender; newVolunteer.DOB = dob; newVolunteer.Email = email; newVolunteer.Phone = phone; newVolunteer.ZipCode = zip; newVolunteer.City = city; newVolunteer.State = state; newVolunteer.Address = address; newVolunteer.Address2 = address2; newVolunteer.SSN = ssn; newVolunteer.Selected_Role_IDs = roleIDs; return newVolunteer; } private bool ValidateAll(VolunteerInfo newVolunteer) { bool valid = true; //first name check if (!Validator.NullOrEmptyRule(newVolunteer.First_Name)) { lblVFName.Text = "Please enter First Name"; valid = false; } else { lblVFName.Text = ""; } //last name check if (!Validator.NullOrEmptyRule(newVolunteer.Last_Name)) { lblVLName.Text = "Please enter Last Name"; valid = false; } else { lblVLName.Text = ""; } //city check if (!Validator.NullOrEmptyRule(newVolunteer.City)) { lblVCity.Text = "Please enter City"; valid = false; } else { lblVCity.Text = ""; } //address check if (!Validator.NullOrEmptyRule(newVolunteer.Address)) { lblVAddress.Text = "Please enter Address"; valid = false; } else { lblVAddress.Text = ""; } //zip check if (!Validator.NullOrEmptyRule(newVolunteer.ZipCode)) { lblVZIP.Text = "Please enter ZIP Code"; valid = false; } else if (!Validator.ZIPCheck(newVolunteer.ZipCode)) { lblVZIP.Text = "Invalid ZIP Code"; valid = false; } else { lblVZIP.Text = ""; } //email check if (!Validator.NullOrEmptyRule(newVolunteer.Email)) { lblVEmail.Text = "Please enter Email"; valid = false; } else if (!Validator.EmailCheck(newVolunteer.Email)) { lblVEmail.Text = "Email Invalid"; valid = false; } else { lblVEmail.Text = ""; } //phone check if (!Validator.NullOrEmptyRule(newVolunteer.Phone)) { lblVPhone.Text = "Please enter Phone Number"; valid = false; } else if (!Validator.PhoneCheck(newVolunteer.Phone)) { lblVPhone.Text = "Phone Number Invalid"; valid = false; } else { lblVPhone.Text = ""; } //at least 14 check if (GetAge(newVolunteer.DOB) < 14) { lblVDOB.Text = "You must be at least 14 years of age to volunteer"; valid = false; } else { lblVDOB.Text = ""; } //has selected at least one role check if (newVolunteer.Selected_Role_IDs.Count == 0) { lblVDOB.Text = "Please select at least one role."; valid = false; } else { lblVRoles.Text = ""; } return valid; } public int GetAge(DateTime birthdate) { int age; DateTime now = DateTime.Now; age = now.Year - birthdate.Year; if (now.Month < birthdate.Month || now.Month == birthdate.Month && now.Day < birthdate.Day) { age--; } return age; } private void InsertVolunteerToDatabase(VolunteerInfo volunteer) { try { //first removes handler so that this event can only be subscribed to once App.service.InsertVolunteerCompleted -= Service_InsertVolunteerCompleted; App.service.InsertVolunteerCompleted += Service_InsertVolunteerCompleted; App.service.InsertVolunteerAsync(volunteer); } catch (Exception ex) { DependencyService.Get<IToast>().LongAlert("Error, unable to access server."); btnSubmit.IsEnabled = true; Debug.WriteLine(ex); } } private void Service_InsertVolunteerCompleted(object sender, InsertVolunteerCompletedEventArgs e) { bool success = false; string message = ""; if (e.Error == null) { success = true; message = "Volunteer form successfully submitted"; } else { success = false; message = "Error submitting volunteer form."; Debug.WriteLine(e.Error); } Device.BeginInvokeOnMainThread(() => { DependencyService.Get<IToast>().LongAlert(message); btnSubmit.IsEnabled = true; if (success) { Navigation.PopToRootAsync(); } }); } private void InitializePickers() { List<string> genderOptions = new List<string> { "M", "F", "Other" }; List<string> stateOptions = new List<string> { "AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MH", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "PW", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY" }; pickGender.ItemsSource = genderOptions; pickState.ItemsSource = stateOptions; pickGender.SelectedIndex = 0; pickState.SelectedItem = "NC"; pickDOB.Date = DateTime.Today; //get possible values from volunteer category try { //first removes handler so that this event can only be subscribed to once App.service.GetVolunteerCategoriesCompleted -= Service_GetVolunteerCategoriesCompleted; App.service.GetVolunteerCategoriesCompleted += Service_GetVolunteerCategoriesCompleted; App.service.GetVolunteerCategoriesAsync(); } catch (Exception ex) { Debug.WriteLine(ex); } } private void Service_GetVolunteerCategoriesCompleted(object sender, GetVolunteerCategoriesCompletedEventArgs e) { if (e.Error == null) { volunteerCategories = e.Result; foreach (VolunteerCategory vc in volunteerCategories) { volunteerRoleItems.Add(new VolunteerRoleListItem() { Category = vc.Description, Category_ID = vc.Volunteer_Category_ID, Selected = false }); } Device.BeginInvokeOnMainThread(() => { rolePickerList.ItemsSource = volunteerRoleItems; }); } else { Device.BeginInvokeOnMainThread(() => { DependencyService.Get<IToast>().ShortAlert("Unable to connect to server."); }); Debug.WriteLine(e.Error); } } //deselect item when selected, so that selected wont show in UI private void rolePickerList_ItemSelected(object sender, SelectedItemChangedEventArgs e) { rolePickerList.SelectedItem = null; } } }
using System; using System.Collections.Generic; namespace City_Center.Models { public class PromocionesWinResultado { public class PromocionesWinDetalle { public int pro_id { get; set; } public int pro_id_evento { get; set; } public int pro_id_locacion { get; set; } public string pro_nombre { get; set; } public string pro_descripcion { get; set; } public string pro_imagen { get; set; } public string pro_tipo_promocion { get; set; } public string pro_codigo { get; set; } public int pro_compartidos_codigo { get; set; } public int pro_destacado { get; set; } public string pro_fecha_duracion_ini { get; set; } public string pro_fecha_duracion_fin { get; set; } public string pro_importe_decuento { get; set; } public string pro_porcentaje_decuento { get; set; } public int pro_id_usuario_creo { get; set; } public string pro_fecha_hora_creo { get; set; } public int pro_id_usuario_modifico { get; set; } public string pro_fecha_hora_modifico { get; set; } public string pro_tipo { get; set; } public string pro_estatus { get; set; } } public class PromocionesWinReturn { public int estatus { get; set; } public string mensaje { get; set; } public List<PromocionesWinDetalle> resultado { get; set; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class LevelManager : MonoBehaviour { private Paper paper; public TextMeshProUGUI paperContents; public GameObject canvas; public GameObject collectedPaper; public GameObject cmd; // Use this for initialization void Start () { paper = FindObjectOfType<Paper>(); } // Update is called once per frame void Update () { if (paper.collected) { paperContents.text = paper.command + "\n" + "------------------" + "\n" + paper.description + "\n" + "\n" + "\n" +"<b>Be sure not to have extra lines after the code!</b>" + "\n" + "<b>Make indents with the TAB key. Do not press the space bar for indents.</b>"; collectedPaper.SetActive(true); if(cmd.activeInHierarchy == false) { if (Input.GetKeyDown(KeyCode.LeftShift)) { //Toggle the value of the boolean canvas.SetActive(true); } if (Input.GetKeyUp(KeyCode.LeftShift)) { //Toggle the value of the boolean canvas.SetActive(false); } } } } public void ClickPaper() { if(canvas.activeInHierarchy == true) { canvas.SetActive(false); } else if(canvas.activeInHierarchy == false) { canvas.SetActive(true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TE18A_List_Array { class Program { static List<string> MyMethod(List<string> currentInventory) { currentInventory.Add("Sword"); return currentInventory; } static void Main(string[] args) { List<string> inventory = new List<string>(); inventory.Add("Potion"); inventory = MyMethod(inventory); Random generator = new Random(); int[] numbers = new int[200]; for (int i = 0; i < 200; i++) { numbers[i] = generator.Next(100); } List<int> moreNumbers = new List<int>(); moreNumbers.Add(44); moreNumbers.Insert(0, 55); Console.WriteLine(moreNumbers[0]); moreNumbers.RemoveAt(0); Console.ReadLine(); } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace ControleDeGastos { public static class UIConstants { public readonly static Uri LocationsListView = new Uri("/Views/Location/LocationListView.xaml", UriKind.Relative); public readonly static Uri NovaContaPage = new Uri("/Views/NovaConta.xaml", UriKind.Relative); public readonly static Uri EditarContaPage = new Uri("/Views/EditarConta.xaml", UriKind.Relative); public readonly static Uri NovoTipoContaPage = new Uri("/Views/NovoTipoConta.xaml", UriKind.Relative); public static Uri MakeEditAccountView(AccountsViewModel account) { string accountID = "-1"; if (account != null) { accountID = account.CTA_ID.ToString(); } string uri = string.Format("/Views/EditAccount.xaml?{0}={1}", App.QueryParamAccountID, accountID); return new Uri(uri, UriKind.Relative); } public static Uri MakeEditCategoryView(CategoryViewModel category) { string categoryID = "-1"; if (category != null) { categoryID = category.CAT_ID.ToString(); } string uri = string.Format("/Views/EditCategory.xaml?{0}={1}", App.QueryParamCategoryID, categoryID); return new Uri(uri, UriKind.Relative); } public static Uri MakeEditAccountTypeView(AccountTypeViewModel accountType) { string accountTypeID = "-1"; if (accountType != null) { accountTypeID = accountType.TPC_ID.ToString(); } string uri = string.Format("/Views/EditAccountType.xaml?{0}={1}", App.QueryParamAccountTypeID, accountTypeID); return new Uri(uri, UriKind.Relative); } public static Uri MakeEditCurrencyView(CurrencyViewModel currency) { string currencyID = "-1"; if (currency != null) { currencyID = currency.MOE_ID.ToString(); } string uri = string.Format("/Views/EditCurrency.xaml?{0}={1}", App.QueryParamCurrencyID, currencyID); return new Uri(uri, UriKind.Relative); } public static Uri MakeEditBeneficiaryView(BeneficiaryViewModel beneficiary) { string beneficiaryID = "-1"; if (beneficiary != null) { beneficiaryID = beneficiary.BNF_ID.ToString(); } string uri = string.Format("/Views/EditBeneficiary.xaml?{0}={1}", App.QueryParamBeneficiaryID, beneficiaryID); return new Uri(uri, UriKind.Relative); } public static Uri MakeEditBudgetView(BudgetViewModel budget) { string budgetID = "-1"; if (budget != null) { budgetID = budget.ORC_ID.ToString(); } string uri = string.Format("/Views/EditBudget.xaml?{0}={1}", App.QueryParamBudgetID, budgetID); return new Uri(uri, UriKind.Relative); } public static Uri MakeEditTransactionView(TransactionViewModel transaction) { string transactionID = "-1"; if (transaction != null) { transactionID = transaction.MOV_ID.ToString(); } string uri = string.Format("/Views/EditTransaction.xaml?{0}={1}", App.QueryParamTransactionID, transactionID); return new Uri(uri, UriKind.Relative); } } }
namespace Core { using System; using System.Text; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; /// <inheritdoc /> public class SwaggerGenConfiguration : IConfigureOptions<SwaggerGenOptions> { private readonly IApiVersionDescriptionProvider _apiVersionDescriptionProvider; private readonly string _defaultScheme; private readonly ApiKeyScheme _apiKeyScheme; private readonly Info _info; public SwaggerGenConfiguration( IApiVersionDescriptionProvider? apiVersionDescriptionProvider, IOptions<SwaggerOptions>? swaggerOptions) { _apiVersionDescriptionProvider = apiVersionDescriptionProvider ?? throw new ArgumentNullException(nameof(apiVersionDescriptionProvider)); if (swaggerOptions?.Value == default) { throw new ArgumentNullException(nameof(swaggerOptions)); } _defaultScheme = swaggerOptions.Value.DefaultScheme; _apiKeyScheme = new ApiKeyScheme { Name = swaggerOptions.Value.ApiKeySchemeName, Description = swaggerOptions.Value.ApiKeySchemeDescription, In = swaggerOptions.Value.ApiKeySchemeIn, Type = swaggerOptions.Value.ApiKeySchemeType }; _info = new Info { Title = swaggerOptions.Value.Title, Description = swaggerOptions.Value.Description, TermsOfService = swaggerOptions.Value.TermsOfService, Contact = new Contact { Name = swaggerOptions.Value.ContactName, Email = swaggerOptions.Value.ContactEmail, Url = $"{swaggerOptions.Value.ContactUrl}" }, License = new License { Name = swaggerOptions.Value.LicenseName, Url = $"{swaggerOptions.Value.LicenseUrl}" } }; } /// <inheritdoc /> public void Configure(SwaggerGenOptions? options) { if (options == default) { throw new ArgumentNullException(nameof(options)); } foreach (var apiVersionDescription in _apiVersionDescriptionProvider.ApiVersionDescriptions) { _info.Version = $"{apiVersionDescription.ApiVersion}"; var sb = new StringBuilder(_info.Description); if (apiVersionDescription.IsDeprecated) { sb.Append(" This API version has been deprecated."); } _info.Description = $"{sb}"; options.SwaggerDoc(apiVersionDescription.GroupName, _info); options.AddSecurityDefinition(_defaultScheme, _apiKeyScheme); } options.OperationFilter<ParameterDescriptionsOperationFilter>(); options.OperationFilter<SecurityRequirementsOperationFilter>(); } } }
/** *┌──────────────────────────────────────────────────────────────┐ *│ 描 述:接口实现 *│ 作 者:zhujun *│ 版 本:1.0 模板代码自动生成 *│ 创建时间:2019-05-23 16:43:42 *└──────────────────────────────────────────────────────────────┘ *┌──────────────────────────────────────────────────────────────┐ *│ 命名空间: EWF.Repository *│ 类 名: SYS_LOGINSUCCESSRepository *└──────────────────────────────────────────────────────────────┘ */ using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; using Dapper; using EWF.Data; using EWF.Data.Repository; using EWF.IRepository.SysManage; using EWF.Util.Options; using EWF.Util; using EWF.Entity; using System.Data; namespace EWF.Repository { public class SYS_LOGINSUCCESSRepository: DefaultRepository<SYS_LOGINSUCCESS>, ISYS_LOGINSUCCESSRepository { public SYS_LOGINSUCCESSRepository(IOptionsSnapshot<DbOption> options) : base(options) { } public bool DeleteLoginSuccess(string userip, string username, DateTime tm) { string strSql = string.Format("delete from TBL_SYS_LOGINSUCCESS where USERNAME='{0}' and LOGINTIME<'{1}'", username, tm); int obj = database.ExecuteBySql(strSql); if (obj > 0) return true; else return false; } public DataTable GetLoginSuccessCount(string userip, string username, DateTime tm) { string strSql = string.Format("select count(LSID) as lcount from TBL_SYS_LOGINSUCCESS where LOGINTIME>'{0}' and USERIP='{1}'", tm, userip); return database.FindTable(strSql); } } }
using AForge.Video; using AutoMapper; using Caliburn.Micro; using MapControl; using Services; using Services.DTO; using Services.Interfaces; using Services.Log; using Services.SdkServices; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; using UGCS.Sdk.Protocol.Encoding; using UGCS.Example.Models; using UGCS.Example.Properties; using Services.Commands; namespace UGCS.Example.ViewModels { public partial class MainViewModel : Caliburn.Micro.PropertyChangedBase { public Mission Mission { get; set; } public Route Route { get; set; } public ProcessedRoute ProcessedRoute { get; set; } public ClientVehicle ClientVehicle { get; set; } private MissionService _missionService; private RouteService _routeService; private VehicleService _vehicleService; private CommandService _commandService; private VehicleCommand _vehicleCommand; ILogger logger = new Logger(typeof(MainViewModel)); public MapViewModel MapViewModel { get; set; } public MainViewModel() { } public MainViewModel(VehicleService vs, VehicleListener vl, MapViewModel mp, TelemetryListener tl, CommandService cs, MissionService ms, RouteService rs, VehicleCommand vc) { Mapper.Initialize(cfg => { cfg.CreateMap<ServiceTelemetryDTO, ClientTelemetry>(); }); logger.LogInfoMessage("Main window initialized"); MapViewModel = mp; _vehicleService = vs; _commandService = cs; _missionService = ms; _routeService = rs; _vehicleCommand = vc; try { ClientVehicle = new ClientVehicle(); ClientVehicle.Vehicle = vs.GetVehicleByName(Settings.Default.UgcsDroneProfileName); ClientVehicle.Telemetry.Vehicle = ClientVehicle.Vehicle; var subscription = new ObjectModificationSubscription(); subscription.ObjectId = ClientVehicle.Vehicle.Id; subscription.ObjectType = "Vehicle"; _commandService.TryAcquireLock(ClientVehicle.Vehicle.Id); tl.AddVehicleIdTolistener(ClientVehicle.Vehicle.Id, TelemetryCallBack); vl.SubscribeVehicle(subscription, (e) => { //Subscribe vehicle changes }); MapViewModel.Init(ClientVehicle); NotifyOfPropertyChange(() => MissionName); NotifyOfPropertyChange(() => RouteName); NotifyOfPropertyChange(() => VehicleName); } catch (Exception e) { MessageBox.Show(e.Message); Application.Current.Shutdown(); } } public String RouteName { get { if (Route == null) { return "Route not initialized"; } return Route.Name; } } public String MissionName { get { if (Mission == null) { return "Mission not initialized"; } return Mission.Name; } } public String VehicleName { get { return ClientVehicle.Vehicle.Name; } } private String _centerMapView = "CenterMapView"; public String CurrentCenterView { get { return _centerMapView; } set { _centerMapView = value; NotifyOfPropertyChange(() => CurrentCenterView); } } private String _currentMainView = "ExampleStartView"; public String CurrentMainView { get { return _currentMainView; } set { _currentMainView = value; NotifyOfPropertyChange(() => CurrentMainView); } } public String WindowTitle { get { return "UCS Example .NET Client"; } } private String _landCommandName = "Land"; public String LandCommandName { get { return _landCommandName; } set { _landCommandName = value; NotifyOfPropertyChange(() => LandCommandName); } } bool? ledStatus = true; public bool? LedStatus { get { return ledStatus; } set { ledStatus = value; NotifyOfPropertyChange(() => LedStatus); } } private bool flash = true; public bool Flash { get { return flash; } set { flash = value; NotifyOfPropertyChange(() => Flash); } } private bool ledStatusSubsystems = false; public bool LedStatusSubsystems { get { return ledStatusSubsystems; } set { ledStatusSubsystems = value; NotifyOfPropertyChange(() => LedStatusSubsystems); } } private bool flashSubsystems = false; public bool FlashSubsystems { get { return flashSubsystems; } set { flashSubsystems = value; NotifyOfPropertyChange(() => FlashSubsystems); } } private bool _initMapCenter; public void TelemetryCallBack(ServiceTelemetryDTO dto, int tempId) { if (ClientVehicle != null) { Mapper.Map<ServiceTelemetryDTO, ClientTelemetry>(dto, ClientVehicle.Telemetry); if (ClientVehicle.Telemetry.LatitudeGPS != null && ClientVehicle.Telemetry.LongitudeGPS != null) { if (!_initMapCenter) { _initMapCenter = true; MapViewModel.InitMapCenter(ClientVehicle.Telemetry.LatitudeGPS.Value, ClientVehicle.Telemetry.LongitudeGPS.Value); } MapViewModel.ChangeCoordinates(ClientVehicle.Telemetry.LatitudeGPS.Value, ClientVehicle.Telemetry.LongitudeGPS.Value, ClientVehicle.Telemetry.AltitudeAGL, ClientVehicle.Telemetry.Camera1Yaw); } } } private Visibility _reconnectVideoVisible; public Visibility ReconnectVideoVisible { get { return _reconnectVideoVisible; } set { _reconnectVideoVisible = value; NotifyOfPropertyChange(() => ReconnectVideoVisible); NotifyOfPropertyChange(() => SliderControlVisible); } } public Visibility SliderControlVisible { get { if (ReconnectVideoVisible == Visibility.Visible) { return Visibility.Hidden; } return Visibility.Visible; } } private String _videoSourceName; public String VideoSourceName { get { return _videoSourceName; } set { _videoSourceName = value; } } private String _currentCamera; public String CurrentCamera { get { return _currentCamera; } set { _currentCamera = value; NotifyOfPropertyChange(() => CurrentCamera); } } private String _videoMessage; public String VideoMessage { get { return _videoMessage; } set { _videoMessage = value; NotifyOfPropertyChange(() => VideoMessage); } } private BitmapImage _UCSvideoSource; public BitmapImage UCSVideoSource { get { return _UCSvideoSource; } set { _UCSvideoSource = value; NotifyOfPropertyChange(() => UCSVideoSource); } } private BitmapImage bitmapToImageSource(Bitmap bitmap) { using (MemoryStream memory = new MemoryStream()) { bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp); memory.Position = 0; BitmapImage bitmapimage = new BitmapImage(); bitmapimage.BeginInit(); bitmapimage.StreamSource = memory; bitmapimage.CacheOption = BitmapCacheOption.OnLoad; bitmapimage.EndInit(); bitmapimage.Freeze(); return bitmapimage; } } } }
using System.Linq; using WebsitePerformance.ContractsBetweenUILandBLL.DTO; namespace WebsitePerformance.ContractsBetweenUILandBLL.Services { public interface IWebsiteService { int TestWebsitePerformance(string url); IQueryable<LinkViewModel> GetLinks(int id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Lucene.Net.Search; using FieldInvertState = Lucene.Net.Index.FieldInvertState; namespace IFN647_Project { public class NewSimilarity : DefaultSimilarity { public override float Idf(int docFreq, int numDocs) { return 1; } public override float LengthNorm(string fieldName, int numTerms) { return 1; } } }
using Microsoft.Xna.Framework; using SprintFour.Collisions; using SprintFour.Enemies.EnemyStates; using SprintFour.Physics; using SprintFour.Sprites; namespace SprintFour.Enemies { public interface IEnemy : IUpdateable, IDrawable, ICollidable, IPhysicsObject { SpriteBase Sprite { get; } EnemyStateBase CurrentState { get; set; } Vector2 Position { get; set; } void Kill(); void Remove(); } }
using System; using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json; namespace Alpaca.Markets { [SuppressMessage( "Microsoft.Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Object instances of this class will be created by Newtonsoft.JSON library.")] internal sealed class JsonLastQuotePolygon : ILastQuote { [SuppressMessage("ReSharper", "StringLiteralTypo")] internal struct Last : IEquatable<Last> { [JsonProperty(PropertyName = "bidexchange", Required = Required.Always)] public Int64 BidExchange { get; set; } [JsonProperty(PropertyName = "askexchange", Required = Required.Always)] public Int64 AskExchange { get; set; } [JsonProperty(PropertyName = "bidprice", Required = Required.Default)] public Decimal BidPrice { get; set; } [JsonProperty(PropertyName = "askprice", Required = Required.Default)] public Decimal AskPrice { get; set; } [JsonProperty(PropertyName = "bidsize", Required = Required.Default)] public Int64 BidSize { get; set; } [JsonProperty(PropertyName = "asksize", Required = Required.Default)] public Int64 AskSize { get; set; } [JsonProperty(PropertyName = "timestamp", Required = Required.Always)] [JsonConverter(typeof(UnixMillisecondsDateTimeConverter))] public DateTime Timestamp { get; set; } public Boolean Equals(Last other) => Timestamp.Equals(other.Timestamp) && BidExchange == other.BidExchange && AskExchange == other.AskExchange && BidPrice == other.BidPrice && AskPrice == other.AskPrice && BidSize == other.BidSize && AskSize == other.AskSize; public override Boolean Equals(Object? obj) => obj is Last other && Equals(other); [SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")] public override Int32 GetHashCode() { unchecked { var hashCode = BidExchange.GetHashCode(); hashCode = (hashCode * 397) ^ AskExchange.GetHashCode(); hashCode = (hashCode * 397) ^ BidPrice.GetHashCode(); hashCode = (hashCode * 397) ^ AskPrice.GetHashCode(); hashCode = (hashCode * 397) ^ BidSize.GetHashCode(); hashCode = (hashCode * 397) ^ AskSize.GetHashCode(); hashCode = (hashCode * 397) ^ Timestamp.GetHashCode(); return hashCode; } } } [JsonProperty(PropertyName = "last", Required = Required.Always)] public Last Nested { get; set; } [JsonProperty(PropertyName = "status", Required = Required.Always)] public String Status { get; set; } = String.Empty; [JsonProperty(PropertyName = "symbol", Required = Required.Always)] public String Symbol { get; set; } = String.Empty; [JsonIgnore] public Int64 BidExchange => Nested.BidExchange; [JsonIgnore] public Int64 AskExchange => Nested.AskExchange; [JsonIgnore] public Decimal BidPrice => Nested.BidPrice; [JsonIgnore] public Decimal AskPrice => Nested.AskPrice; [JsonIgnore] public Int64 BidSize => Nested.BidSize; [JsonIgnore] public Int64 AskSize => Nested.AskSize; [JsonIgnore] public DateTime TimeUtc => Nested.Timestamp; } }
using EfFunctions.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("EfFunctions.Tests")] namespace EfFunctions { class Program { static void Main(string[] args) { SetupDatabase(); using (var context = new BooksDbContext()) { var service = new BookService(context); var books = service.SearchBooks("bartimäus"); foreach (var book in books) { Console.WriteLine($"{book.Name} - {book.ISBN}"); } } } private static void SetupDatabase() { using (var context = new BooksDbContext()) { if (context.Database.EnsureCreated()) { context.Authors.Add(new Author { Name = "Christoph Scholder", Books = new List<Book> { new Book { Name = "Oktoberfest", ISBN = "3426198886" } } }); context.Authors.Add(new Author { Name = "Jonathan Stroud", Books = new List<Book> { new Book { Name = "Bartimäus - Das Amulett von Samarkand", ISBN = "3570127753" }, new Book { Name = "Bartimäus - Das Auge des Golem", ISBN = "3570127761" }, new Book { Name = "Bartimäus - Die Pforte des Magiers", ISBN = "3442368014" }, new Book { Name = "Bartimäus - Der Ring des Salomo", ISBN = "3570139670" } } }); context.Authors.Add(new Author { Name = "Robert Cecil Martin", Books = new List<Book> { new Book { Name = "Clean Code", ISBN = "0132350882" }, new Book { Name = "The Clean Coder", ISBN = "0137081073" } } }); context.SaveChanges(); } } } } internal class BooksDbContext : DbContext { public DbSet<Author> Authors { get; set; } public DbSet<Book> Books { get; set; } public BooksDbContext() { } public BooksDbContext(DbContextOptions<BooksDbContext> options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) optionsBuilder.UseSqlServer("Server=localhost;Database=Demo.EfFunctions;Integrated Security=True"); } } }
using FastSQL.Core; using System; using System.Collections.Generic; using System.Linq; namespace FastSQL.MsSql { public class ProviderOptionManager : BaseOptionManager { public override IEnumerable<OptionItem> GetOptionsTemplate() { return new List<OptionItem> { new OptionItem { Name = "DataSource", DisplayName = "Data Source", Type = OptionType.Text, Value = ".\\SQLEXPRESS" }, new OptionItem { Name = "UserID", DisplayName = "User ID", Type = OptionType.Text, Value = "sa" }, new OptionItem { Name = "Password", DisplayName = "Password", Type = OptionType.Password, Value = "" }, new OptionItem { Name = "Database", DisplayName = "Database", Type = OptionType.Text, Value = "" } }; } } }
using System; namespace JumpAndRun.Networking { public class SetActorInfo { public Guid Id { get; } public byte[] Data { get; } public SetActorInfo(Guid id, byte[] data) { Id = id; Data = data; } } }
using System; using Exact.Core; public partial class docs_ErniukasSettingsNew : Exact.Web.UI.Page.Base { protected void Page_Load(object sender, EventArgs e) { if (Save.Value != null && bool.Parse(Save.Value.ToString()) == true) { env.set_Setting(SettingType.User, "FromEmail", null, fromEmail.Value); env.set_Setting(SettingType.User, "SmtpServerHost", null, SMTP.Value); env.set_Setting(SettingType.User, "EmailPort", null, port.Value); } Save.Value = false; fromEmail.Value = env.get_Setting(SettingType.User, "FromEmail"); SMTP.Value = env.get_Setting(SettingType.User, "SmtpServerHost"); port.Value = env.get_Setting(SettingType.User, "EmailPort"); } }
using System.Collections.Generic; namespace Amesc.Dominio.Cursos { public interface ICursoAbertoRepositorio : IRepositorio<CursoAberto> { List<CursoAberto> ListarPorCurso(int idCurso); } }
using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Text; using System.Linq; using SqlServerDocumentator.DocumentedDatabaseObjects; using Microsoft.SqlServer.Management.Smo; using SqlServerDocumentator.Infraestructure; using Microsoft.Extensions.Options; namespace SqlServerDocumentator { class Documentator : IDocumentator { SqlDocumentatorConfiguration _configuration; public Documentator(IOptionsSnapshot<SqlDocumentatorConfiguration> configuration) { _configuration = configuration.Value; } public IEnumerable<DocumentedServer> GetServers() { return this._configuration.DocumentedServers; } public IEnumerable<DocumentedDatabase> GetDatabases(string serverName) { Server server = this.GetSMOServer(serverName); foreach (Database database in server.Databases) { if (!database.IsSystemObject) yield return new DocumentedDatabase() { Name = database.Name, ServerName = serverName, }; } } public DocumentedDatabase GetDatabase(string serverName, string databaseName) { Database database = this.GetSMODatabase(serverName, databaseName); if (!database.IsSystemObject) return new DocumentedDatabase() { Name = database.Name, ServerName = serverName, Description = (database.ExtendedProperties.Contains(this._configuration.Prefix)) ? database.ExtendedProperties[this._configuration.Prefix].Value.ToString() : null }; else return null; } public IEnumerable<DocumentedSimpleObject> GetTables(string serverName, string databaseName) { return this.GetSimpleObject(serverName, databaseName , "SELECT t.name, SCHEMA_NAME(t.schema_id) as [schema], p.value FROM sys.tables t left join sys.extended_properties p on t.object_id = p.major_id and p.minor_id = 0 and p.name = @description ORDER BY t.name" , TypeDocumentedObject.Table); } public IEnumerable<DocumentedSimpleObject> GetViews(string serverName, string databaseName) { return this.GetSimpleObject(serverName, databaseName , "SELECT t.name, SCHEMA_NAME(t.schema_id) as [schema], p.value FROM sys.views t left join sys.extended_properties p on t.object_id = p.major_id and p.minor_id = 0 and p.name = @description ORDER BY t.name" , TypeDocumentedObject.View); } public IEnumerable<DocumentedSimpleObject> GetStoredProcedures(string serverName, string databaseName) { return this.GetSimpleObject(serverName, databaseName , "SELECT t.name, SCHEMA_NAME(t.schema_id) as [schema], p.value FROM sys.procedures t left join sys.extended_properties p on t.object_id = p.major_id and p.minor_id = 0 and p.name = @description ORDER BY t.name" , TypeDocumentedObject.StoredProcedure); } private IEnumerable<DocumentedSimpleObject> GetSimpleObject(string serverName, string databaseName, string query, TypeDocumentedObject type) { using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={databaseName};Trusted_Connection=True;")) { using (SqlCommand command = new SqlCommand(query, conn)) { command.Parameters.Add(new SqlParameter("@description", _configuration.Prefix)); conn.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { yield return new DocumentedSimpleObject(serverName, databaseName , reader.GetString(0) , reader.GetString(1) , (reader.IsDBNull(2)) ? null : reader.GetString(2) , type); } } } } } public DocumentedTable GetTable(string serverName, string databaseName, string schema, string tableName) { Table table = this.GetSMOTable(serverName, databaseName, schema, tableName); string description = (table.ExtendedProperties.Contains(_configuration.Prefix)) ? table.ExtendedProperties[_configuration.Prefix].Value.ToString() : string.Empty; DocumentedTable documentedTable = new DocumentedTable(serverName, databaseName, tableName, schema, description); foreach (Column col in table.Columns) { documentedTable.Columns.Add( new DocumentedTableColumn() { inPrimaryKey = col.InPrimaryKey, isForeignKey = col.IsForeignKey, DataType = col.DataType.Name, Name = col.Name, Description = (col.ExtendedProperties.Contains(_configuration.Prefix)) ? col.ExtendedProperties[_configuration.Prefix].Value.ToString() : string.Empty }); } foreach (ForeignKey fk in table.ForeignKeys) { DocumentedForeignKey key = new DocumentedForeignKey() { Name = fk.Name }; foreach (ForeignKeyColumn fkCol in fk.Columns) { key.Columns.Add(fkCol.Name); } documentedTable.ForeignKeys.Add(key); } return documentedTable; } public DocumentedView GetView(string serverName, string databaseName, string schema, string viewName) { View view = this.GetSMOView(serverName, databaseName, schema, viewName); string description = (view.ExtendedProperties.Contains(_configuration.Prefix)) ? view.ExtendedProperties[_configuration.Prefix].Value.ToString() : string.Empty; DocumentedView documentedView = new DocumentedView(serverName, databaseName, viewName, schema, description); foreach (Column col in view.Columns) { documentedView.Columns.Add(new DocumentedViewColumn() { Name = col.Name, DataType = col.DataType.Name }); } return documentedView; } public DocumentedStoredProcedure GetStoredProcedure(string serverName, string databaseName, string schema, string storedProcedureName) { StoredProcedure procedure = this.GetSMOProcedure(serverName, databaseName, schema, storedProcedureName); string description = (procedure.ExtendedProperties.Contains(_configuration.Prefix)) ? procedure.ExtendedProperties[_configuration.Prefix].Value.ToString() : string.Empty; return new DocumentedStoredProcedure(serverName, databaseName, storedProcedureName, schema, description); } public DocumentedDatabase SaveDatabase(DocumentedDatabase database) { Database smoDatabase = this.GetSMODatabase(database.ServerName, database.Name); if (!smoDatabase.ExtendedProperties.Contains(this._configuration.Prefix)) { smoDatabase.ExtendedProperties.Add(new ExtendedProperty(smoDatabase, this._configuration.Prefix, database.Description)); } else { smoDatabase.ExtendedProperties[this._configuration.Prefix].Value = database.Description; } smoDatabase.Alter(); return this.GetDatabase(database.ServerName, database.Name); } public DocumentedTable SaveTable(DocumentedTable table) { Table smoTable = this.GetSMOTable(table.ServerName, table.DatabaseName, table.Schema, table.Name); foreach (DocumentedTableColumn col in table.Columns) { if (!smoTable.Columns.Contains(col.Name)) throw new KeyNotFoundException("Not exist Column with the name: " + col.Name); } if (!smoTable.ExtendedProperties.Contains(this._configuration.Prefix)) { smoTable.ExtendedProperties.Add(new ExtendedProperty(smoTable, this._configuration.Prefix, table.Description)); } else { smoTable.ExtendedProperties[this._configuration.Prefix].Value = table.Description; } foreach (DocumentedTableColumn col in table.Columns) { Column smoCol = smoTable.Columns[col.Name]; if (!smoCol.ExtendedProperties.Contains(this._configuration.Prefix)) { smoCol.ExtendedProperties.Add(new ExtendedProperty(smoCol, this._configuration.Prefix, col.Description)); } else { smoCol.ExtendedProperties[this._configuration.Prefix].Value = col.Description; } } smoTable.Alter(); return this.GetTable(table.ServerName, table.DatabaseName, table.Schema, table.Name); } public DocumentedView SaveView(DocumentedView view) { View smoView = this.GetSMOView(view.ServerName, view.DatabaseName, view.Schema, view.Name); if (!smoView.ExtendedProperties.Contains(this._configuration.Prefix)) { smoView.ExtendedProperties.Add(new ExtendedProperty(smoView, this._configuration.Prefix, view.Description)); } else { smoView.ExtendedProperties[this._configuration.Prefix].Value = view.Description; } smoView.Alter(); return this.GetView(view.ServerName, view.DatabaseName, view.Schema, view.Name); } public DocumentedStoredProcedure SaveStoredProcedure(DocumentedStoredProcedure procedure) { StoredProcedure smoProcedure = this.GetSMOProcedure(procedure.ServerName, procedure.DatabaseName, procedure.Schema, procedure.Name); if (!smoProcedure.ExtendedProperties.Contains(this._configuration.Prefix)) { smoProcedure.ExtendedProperties.Add(new ExtendedProperty(smoProcedure, this._configuration.Prefix, procedure.Description)); } else { smoProcedure.ExtendedProperties[this._configuration.Prefix].Value = procedure.Description; } smoProcedure.Alter(); return procedure; } private Server GetSMOServer(string serverName) { if (this._configuration.Servers.Any(x => x.Name.Equals(serverName))) return new Server(serverName); else throw new KeyNotFoundException("Not exist server with the name: " + serverName); } private Database GetSMODatabase(string serverName, string databaseName) { Server server = this.GetSMOServer(serverName); if (server.Databases.Contains(databaseName)) return server.Databases[databaseName]; else throw new KeyNotFoundException("Not exist database with the name: " + databaseName); } private Table GetSMOTable(string serverName, string databaseName, string schema, string tableName) { Database database = this.GetSMODatabase(serverName, databaseName); if (database.Tables.Contains(tableName, schema)) return database.Tables[tableName, schema]; else throw new KeyNotFoundException($"Not exist Table with the name: {schema}.{tableName}"); } private View GetSMOView(string serverName, string databaseName, string schema, string viewName) { Database database = this.GetSMODatabase(serverName, databaseName); if (database.Views.Contains(viewName, schema)) return database.Views[viewName, schema]; else throw new KeyNotFoundException($"Not exist View with the name: {schema}.{viewName}"); } private StoredProcedure GetSMOProcedure(string serverName, string databaseName, string schema, string procedureName) { Database database = this.GetSMODatabase(serverName, databaseName); if (database.StoredProcedures.Contains(procedureName, schema)) return database.StoredProcedures[procedureName, schema]; else throw new KeyNotFoundException($"Not exist Stored Procedure with the name: {schema}.{procedureName}"); } } }
using System; namespace Lib { public static class Class1 { public static int Add ( int a, int b ) => a + b; } }
using System; using System.Linq; using System.Runtime.InteropServices; namespace Roaring.DataStores { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ImmutableArrayStore : IDataStore<ushort> { private readonly ushort[][] _collection; public bool IsReadOnly => true; public bool HasDirectAccess => false; public int Count => _collection.Count(x => x != null); internal ImmutableArrayStore(ushort[][] values) { _collection = values; } public ushort CreateContainer(uint cardinality) { throw new InvalidOperationException("This container is read-only"); } public void DeleteContainer(ushort index) { throw new InvalidOperationException("This container is read-only"); } public ref ushort[] GetContainer(ushort index) { throw new InvalidOperationException("This container is read-only"); } public void ReadContainer(ushort index, ushort[] buffer, uint cardinality) { var container = _collection[index]; Buffer.BlockCopy(container, 0, buffer, 0, (int)(cardinality * sizeof(ushort))); } public void WriteContainer(ushort index, ushort[] buffer, uint cardinality, bool canClaim) { throw new InvalidOperationException("This container is read-only"); } public void Clear() { throw new InvalidOperationException("This container is read-only"); } public ImmutableArrayStore Clone() => this; IDataStore<ushort> IDataStore<ushort>.Clone() => this; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[,] MultiNames = new string[2,3]{ {"Ruiz","A.","Manzano"}, {"Dane","G.","Garcia"}, }; string[] fullname = new string[2]; fullname[0] = MultiNames[0, 0] + MultiNames[0, 1] + MultiNames[0, 2]; fullname[1] = MultiNames[1, 0] + MultiNames[1, 1] + MultiNames[1, 2]; int fullnameCounter = 0; foreach (string n in fullname) { MessageBox.Show("the Result is:" + fullname[fullnameCounter]); fullnameCounter++; } } } }
namespace Buffers.FTL { public sealed class BlockState { public ushort FreePageCount { get; set; } public ushort AllcPageCount { get; set; } public ushort LivePageCount { get; set; } public ushort DeadPageCount { get; set; } public PageState[] PageStates { get; private set; } public BlockState(ushort pageCount) { PageStates = new PageState[pageCount]; FreePageCount = pageCount; AllcPageCount = 0; LivePageCount = 0; DeadPageCount = 0; } } }
namespace MvcGuessMySonsName.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<MvcGuessMySonsName.Models.DbGuesss> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(MvcGuessMySonsName.Models.DbGuesss context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // foreach (var guess in context.Guesses) { if (guess.Name.Contains("Grímur")) { guess.Correct = true; } } //var guesses = context.Guesses.ToList(); //for (int i = guesses.Count - 1; i >= 0; i--) //{ // var guess = guesses[i]; // if (string.IsNullOrEmpty(guess.Username) || guess.Username == "Óţekkt") // { // context.Guesses.Remove(guess); // } //} } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggrTile : Tile { TriggerCollision tg; GameObject trigPS; Transform[] Platforms; Vector3 platTrans; float distanceTilePS, temporaryYPos; bool platAssigned = false, playOnce = false; public float maxInt = 10f; private void Start() { trigPS = GameObject.Find("TriggerParticle"); rendMat.material.color = Color.white; pointLight.color = Color.white; tg = GetComponentInChildren<TriggerCollision>(); } //Tile lights up when colliding with the PS protected override void lightModifier() { if (!triggerPlayer) { if (tg.triggerPlayerPS && pointLight.intensity >= minimum) { pointLight.intensity = Mathf.PingPong(Time.time, maximum) + minimum; } else if (tg.triggerPlayerPS && pointLight.intensity <= minimum) { pointLight.intensity += 0.1f; } } } //upon trigger, make bridge appear by setting active each platform block protected override void TriggerAction() { if (triggerPlayer) { for (int a = 0; a < transform.childCount; a++) { if (transform.GetChild(a).gameObject.tag == "Platform") { transform.GetChild(a).gameObject.SetActive(true); } } pointLight.intensity += 1f; //increase point light to max int and when reached destroy small particle if(pointLight.intensity >= maxInt) { pointLight.intensity = maxInt; Object.Destroy(trigPS); } PlaySoundOnTrigger(); } } protected override void PlaySoundOnTrigger() { if (!playOnce) { audioTile.Play(); playOnce = true; } } }
using System; using System.Text.Json.Serialization; namespace MCC.TwitCasting { public class JsonData { [JsonPropertyName("type")] public string Type { get; set; } [JsonPropertyName("id")] public long ID { get; set; } [JsonPropertyName("message")] public string Message { get; set; } [JsonPropertyName("createdAt")] public DateTimeOffset CreatedAt { get; set; } [JsonPropertyName("item")] public Item Item { get; set; } [JsonPropertyName("author")] public User Author { get; set; } [JsonPropertyName("sender")] public User Sender { get; set; } [JsonPropertyName("numComments")] public int Comments { get; set; } } public class User { [JsonPropertyName("id")] public string ID { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("screenName")] public string ScreenName { get; set; } [JsonPropertyName("profileImage")] public string ProfileImage { get; set; } [JsonPropertyName("grade")] public int Grade { get; set; } } public class Item { [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("image")] public string Image { get; set; } [JsonPropertyName("effectCommand")] public string ProfileImage { get; set; } } public class LatestMovie { [JsonPropertyName("update_interval_sec")] public int UpdateItervalSecond { get; set; } [JsonPropertyName("movie")] public Movie Movie { get; set; } } public class Movie { [JsonPropertyName("id")] public int ID { get; set; } [JsonPropertyName("is_on_live")] public bool IsOnLive { get; set; } } public class EventPubSubURL { [JsonPropertyName("url")] public string URL { get; set; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PopUpController : MonoBehaviour { public enum PopUpAction {ExitAction, HomeActionFromGame, RestartActionFromGame}; public static PopUpAction popUpAction; public GameObject popUp; public GameObject popUpText; public GameObject popUpYesButton; public GameObject popUpNoButton; public UIController uiController; public void TogglePopUp () { switch (popUpAction) { case PopUpAction.ExitAction: popUpText.GetComponent<Text> ().text = DRConstants.exit_action_pop_up_text; break; case PopUpAction.HomeActionFromGame: popUpText.GetComponent<Text> ().text = DRConstants.home_action_from_game_pop_up; break; case PopUpAction.RestartActionFromGame: popUpText.GetComponent<Text> ().text = DRConstants.restart_action_from_game_pop_up; break; } StartCoroutine (TogglePopUpFlyAnimation (popUp)); StartCoroutine (ToggleObjectWithAnimation (popUpYesButton)); StartCoroutine (ToggleObjectWithAnimation (popUpNoButton)); } private IEnumerator TogglePopUpFlyAnimation (GameObject gameObject) { Animator gameObjectAnimator = gameObject.GetComponent<Animator> (); if (gameObject.activeSelf == false) { RectTransform rt = gameObject.GetComponent<RectTransform> (); rt.anchorMin = new Vector2 (0, 1.0f); rt.anchorMax = new Vector2 (1.0f, 1.2f); gameObject.SetActive (true); gameObjectAnimator.SetTrigger ("PopUpFlyIn"); } else { gameObjectAnimator.SetTrigger ("PopUpFlyOut"); yield return new WaitForSeconds (0.5f); gameObject.SetActive (false); } yield return null; } private IEnumerator ToggleObjectWithAnimation (GameObject gameObject) { Animator gameObjectAnimator = gameObject.GetComponent<Animator> (); if (gameObject.activeSelf == false) { gameObject.transform.localScale = new Vector3 (0, 0, 1.0f); gameObject.SetActive (true); gameObjectAnimator.SetTrigger ("ZoomIn"); yield return new WaitForSeconds (0.5f); } else { gameObjectAnimator.SetTrigger ("ZoomOut"); yield return new WaitForSeconds (0.5f); gameObject.SetActive (false); } yield return null; } public void PopUpYesButtonClick () { switch (popUpAction) { case PopUpAction.ExitAction: //uiController.ExitActionConfirmed (); Application.Quit (); break; case PopUpAction.HomeActionFromGame: StartCoroutine (TogglePopUpFlyAnimation (popUp)); StartCoroutine (ToggleObjectWithAnimation (popUpYesButton)); StartCoroutine (ToggleObjectWithAnimation (popUpNoButton)); uiController.HomeFromGameActionCommited (); break; case PopUpAction.RestartActionFromGame: StartCoroutine (TogglePopUpFlyAnimation (popUp)); StartCoroutine (ToggleObjectWithAnimation (popUpYesButton)); StartCoroutine (ToggleObjectWithAnimation (popUpNoButton)); uiController.RestartFromGameActionCommited (); break; } } public void PopUpNoButtonClick () { switch (popUpAction) { case PopUpAction.ExitAction: StartCoroutine (TogglePopUpFlyAnimation (popUp)); StartCoroutine (ToggleObjectWithAnimation (popUpYesButton)); StartCoroutine (ToggleObjectWithAnimation (popUpNoButton)); uiController.ExitActionCancelled (); break; case PopUpAction.HomeActionFromGame: StartCoroutine (TogglePopUpFlyAnimation (popUp)); StartCoroutine (ToggleObjectWithAnimation (popUpYesButton)); StartCoroutine (ToggleObjectWithAnimation (popUpNoButton)); uiController.HomeFromGameActionCancelled (); break; case PopUpAction.RestartActionFromGame: StartCoroutine (TogglePopUpFlyAnimation (popUp)); StartCoroutine (ToggleObjectWithAnimation (popUpYesButton)); StartCoroutine (ToggleObjectWithAnimation (popUpNoButton)); uiController.HomeFromGameActionCancelled (); break; } } }
using System; using System.Threading; using System.Threading.Tasks; namespace AsyncAwait.Examples { public static class AsyncVsTask { public static void ShowAsyncVsTask() { ShowAsync(); ShowTask(); } private static async void ShowAsync() { Console.WriteLine($"ShowAsync started and is performed in {Thread.CurrentThread.ManagedThreadId} thread"); await RunOperationAsync(); Console.WriteLine("ShowAsync finished"); } private static async Task RunOperationAsync() { Console.WriteLine($"RunOperationAsync started and is performed in {Thread.CurrentThread.ManagedThreadId} thread"); await Task.Delay(TimeSpan.FromSeconds(2)); Console.WriteLine("RunOperationAsync finished"); } private static void ShowTask() { Console.WriteLine($"ShowTask started and is performed in {Thread.CurrentThread.ManagedThreadId} thread"); Task.Run(() => RunOperationWithTask()); Console.WriteLine("ShowTask finished"); } private static async Task RunOperationWithTask() { Console.WriteLine($"RunOperationWithTask started and is performed in {Thread.CurrentThread.ManagedThreadId} thread"); await Task.Delay(TimeSpan.FromSeconds(2)); Console.WriteLine("RunOperationWithTask finished"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AirPlane : MonoBehaviour { public Transform[] waypoints; public float flightSpeed = 3f; public float turnSpeed = 2f; public float maxWaypointDistance = 5; private int activeWaypoint = 0; // Use this for initialization void Start() { } // Update is called once per frame void Update() { transform.position += transform.forward * flightSpeed * Time.deltaTime; Vector3 dir = (waypoints[activeWaypoint].position - transform.position).normalized; transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(dir), turnSpeed); if (Vector3.Distance(waypoints[activeWaypoint].position, transform.position) < maxWaypointDistance) { activeWaypoint++; if (waypoints.Length <= activeWaypoint) { activeWaypoint = 0; } } } private void OnDrawGizmos() { for (int i = 0; i < waypoints.Length; i++) { Gizmos.color = Color.blue; if (i == waypoints.Length - 1) { Gizmos.DrawLine(waypoints[i].position, waypoints[0].position); } else { Gizmos.DrawLine(waypoints[i].position, waypoints[i + 1].position); } if (i == activeWaypoint) { Gizmos.color = Color.red; } else { Gizmos.color = Color.blue; } Gizmos.DrawSphere(waypoints[i].position, maxWaypointDistance); } } }
namespace WsValidate.Contracts { public interface IConfig { string RootPath { get; } string ConfigFileName { get; } } }
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Models.Regression.Fitting { using System; using Accord.Math; using Accord.Math.Decompositions; /// <summary> /// Lower-Bound Newton-Raphson for Multinomial logistic regression fitting. /// </summary> /// /// <remarks> /// <para> /// The Lower Bound principle consists of replacing the second derivative /// matrix by a global lower bound in the Leowner ordering [Böhning, 92]. /// In the case of multinomial logistic regression estimation, the Hessian /// of the negative log-likelihood function can be replaced by one of those /// lower bounds, leading to a monotonically converging sequence of iterates. /// Furthermore, [Krishnapuram, Carin, Figueiredo and Hartemink, 2005] also /// have shown that a lower bound can be achieved which does not depend on /// the coefficients for the current iteration.</para> /// /// <para> /// References: /// <list type="bullet"> /// <item><description> /// B. Krishnapuram, L. Carin, M.A.T. Figueiredo, A. Hartemink. Sparse Multinomial /// Logistic Regression: Fast Algorithms and Generalization Bounds. 2005. Available on: /// http://www.lx.it.pt/~mtf/Krishnapuram_Carin_Figueiredo_Hartemink_2005.pdf </description></item> /// <item><description> /// D. Böhning. Multinomial logistic regression algorithm. Annals of the Institute /// of Statistical Mathematics, 44(9):197 ˝U200, 1992. 2. M. Corney.</description></item> /// <item><description> /// Bishop, Christopher M.; Pattern Recognition and Machine Learning. /// Springer; 1st ed. 2006.</description></item> /// </list></para> /// </remarks> /// /// <example> /// <code> /// // Create a new Multinomial Logistic Regression for 3 categories /// var mlr = new MultinomialLogisticRegression(inputs: 2, categories: 3); /// /// // Create a estimation algorithm to estimate the regression /// LowerBoundNewtonRaphson lbnr = new LowerBoundNewtonRaphson(mlr); /// /// // Now, we will iteratively estimate our model. The Run method returns /// // the maximum relative change in the model parameters and we will use /// // it as the convergence criteria. /// /// double delta; /// int iteration = 0; /// /// do /// { /// // Perform an iteration /// delta = lbnr.Run(inputs, outputs); /// iteration++; /// /// } while (iteration &lt; 100 &amp;&amp; delta > 1e-6); /// </code> /// </example> /// public class LowerBoundNewtonRaphson : IMultipleRegressionFitting { private MultinomialLogisticRegression regression; private double[] previous; private double[] solution; private double[] deltas; private double[] errors; private double[] output; private double[,] weights; private double[,] lowerBound; private double[] gradient; private double[,] xxt; private int K; private int M; private int parameterCount; private bool computeStandardErrors = true; private bool updateLowerBound = true; private ISolverMatrixDecomposition<double> decomposition = null; /// <summary> /// Gets the previous values for the coefficients which were /// in place before the last learning iteration was performed. /// </summary> /// public double[] Previous { get { return previous; } } /// <summary> /// Gets the current values for the coefficients. /// </summary> /// public double[] Solution { get { return solution; } } /// <summary> /// Gets or sets a value indicating whether the /// lower bound should be updated using new data. /// </summary> /// /// <value> /// <c>true</c> if the lower bound should be /// updated; otherwise, <c>false</c>.</value> /// public bool UpdateLowerBound { get { return updateLowerBound; } set { updateLowerBound = value; } } /// <summary> /// Gets the Lower-Bound matrix being used in place of /// the Hessian matrix in the Newton-Raphson iterations. /// </summary> /// public double[,] HessianLowerBound { get { return lowerBound; } } /// <summary> /// Gets the Gradient vector computed in /// the last Newton-Raphson iteration. /// </summary> /// public double[] Gradient { get { return gradient; } } /// <summary> /// Gets the total number of parameters in the model. /// </summary> /// public int Parameters { get { return parameterCount; } } /// <summary> /// Gets or sets a value indicating whether standard /// errors should be computed in the next iteration. /// </summary> /// <value> /// <c>true</c> to compute standard errors; otherwise, <c>false</c>. /// </value> /// public bool ComputeStandardErrors { get { return computeStandardErrors; } set { computeStandardErrors = value; } } /// <summary> /// Creates a new <see cref="LowerBoundNewtonRaphson"/>. /// </summary> /// <param name="regression">The regression to estimate.</param> /// public LowerBoundNewtonRaphson(MultinomialLogisticRegression regression) { this.regression = regression; K = regression.Categories - 1; M = regression.Inputs + 1; parameterCount = K * M; solution = regression.Coefficients.Reshape(1); xxt = new double[M, M]; errors = new double[K]; output = new double[K]; lowerBound = new double[parameterCount, parameterCount]; gradient = new double[parameterCount]; // Differently from the IRLS iteration, the weight matrix can be fixed // as it does not depend on the current coefficients anymore [I - 11/m] // TODO: Avoid the multiple allocations in the line below weights = (-0.5).Multiply(Matrix.Identity(K).Subtract(Matrix.Create(K, K, 1.0 / M))); } /// <summary> /// Runs one iteration of the Lower-Bound Newton-Raphson iteration. /// </summary> /// <param name="inputs">The input data.</param> /// <param name="classes">The outputs associated with each input vector.</param> /// <returns>The maximum relative change in the parameters after the iteration.</returns> /// public double Run(double[][] inputs, int[] classes) { return run(inputs, Categorical.OneHot(classes)); } /// <summary> /// Runs one iteration of the Lower-Bound Newton-Raphson iteration. /// </summary> /// <param name="inputs">The input data.</param> /// <param name="outputs">The outputs associated with each input vector.</param> /// <returns>The maximum relative change in the parameters after the iteration.</returns> /// public double Run(double[][] inputs, double[][] outputs) { return run(inputs, outputs); } private double run(double[][] inputs, double[][] outputs) { // Regress using Lower-Bound Newton-Raphson estimation // // The main idea is to replace the Hessian matrix with a // suitable lower bound. Indeed, the Hessian is lower // bounded by a negative definite matrix that does not // even depend on w [Krishnapuram et al]. // // - http://www.lx.it.pt/~mtf/Krishnapuram_Carin_Figueiredo_Hartemink_2005.pdf // // Initial definitions and memory allocations int N = inputs.Length; double[][] design = new double[N][]; double[][] coefficients = this.regression.Coefficients; // Compute the regression matrix for (int i = 0; i < inputs.Length; i++) { double[] row = design[i] = new double[M]; row[0] = 1; // for intercept for (int j = 0; j < inputs[i].Length; j++) row[j + 1] = inputs[i][j]; } // Reset Hessian matrix and gradient for (int i = 0; i < gradient.Length; i++) gradient[i] = 0; if (UpdateLowerBound) { for (int i = 0; i < gradient.Length; i++) for (int j = 0; j < gradient.Length; j++) lowerBound[i, j] = 0; } // In the multinomial logistic regression, the objective // function is the log-likelihood function l(w). As given // by Krishnapuram et al and Böhning, this is a concave // function with Hessian given by: // // H(w) = -sum(P(w) - p(w)p(w)') (x) xx' // (see referenced paper for proper indices) // // In which (x) denotes the Kronecker product. By using // the lower bound principle, Krishnapuram has shown that // we can replace H(w) with a lower bound approximation B // which does not depend on w (eq. 8 on aforementioned paper): // // B = -(1/2) [I - 11/M] (x) sum(xx') // // Thus we can compute and invert this matrix only once. // // For each input sample in the dataset for (int i = 0; i < inputs.Length; i++) { // Grab variables related to the sample double[] x = design[i]; double[] y = outputs[i]; // Compute and estimate outputs this.compute(inputs[i], output); // Compute errors for the sample for (int j = 0; j < errors.Length; j++) errors[j] = y[j + 1] - output[j]; // Compute current gradient and Hessian // We can take advantage of the block structure of the // Hessian matrix and gradient vector by employing the // Kronecker product. See [Böhning, 1992] // (Re-) Compute error gradient double[] g = Matrix.Kronecker(errors, x); for (int j = 0; j < g.Length; j++) gradient[j] += g[j]; if (UpdateLowerBound) { // Compute xxt matrix for (int k = 0; k < x.Length; k++) for (int j = 0; j < x.Length; j++) xxt[k, j] = x[k] * x[j]; // (Re-) Compute weighted "Hessian" matrix double[,] h = Matrix.Kronecker(weights, xxt); for (int j = 0; j < parameterCount; j++) for (int k = 0; k < parameterCount; k++) lowerBound[j, k] += h[j, k]; } } if (UpdateLowerBound) { UpdateLowerBound = false; // Decompose to solve the linear system. Usually the Hessian will // be invertible and LU will succeed. However, sometimes the Hessian // may be singular and a Singular Value Decomposition may be needed. // The SVD is very stable, but is quite expensive, being on average // about 10-15 times more expensive than LU decomposition. There are // other ways to avoid a singular Hessian. For a very interesting // reading on the subject, please see: // // - Jeff Gill & Gary King, "What to Do When Your Hessian Is Not Invertible", // Sociological Methods & Research, Vol 33, No. 1, August 2004, 54-87. // Available in: http://gking.harvard.edu/files/help.pdf // // Moreover, the computation of the inverse is optional, as it will // be used only to compute the standard errors of the regression. // Hessian Matrix is singular, try pseudo-inverse solution decomposition = new SingularValueDecomposition(lowerBound); deltas = decomposition.Solve(gradient); } else { deltas = decomposition.Solve(gradient); } previous = coefficients.Reshape(1); // Update coefficients using the calculated deltas for (int i = 0, k = 0; i < coefficients.Length; i++) for (int j = 0; j < coefficients[i].Length; j++) coefficients[i][j] -= deltas[k++]; solution = coefficients.Reshape(1); if (computeStandardErrors) { // Grab the regression information matrix double[,] inverse = decomposition.Inverse(); // Calculate coefficients' standard errors double[][] standardErrors = regression.StandardErrors; for (int i = 0, k = 0; i < standardErrors.Length; i++) for (int j = 0; j < standardErrors[i].Length; j++, k++) standardErrors[i][j] = Math.Sqrt(Math.Abs(inverse[k, k])); } // Return the relative maximum parameter change for (int i = 0; i < deltas.Length; i++) deltas[i] = Math.Abs(deltas[i]) / Math.Abs(previous[i]); double max = Matrix.Max(deltas); return max; } private void compute(double[] x, double[] responses) { double[][] coefficients = this.regression.Coefficients; double sum = 1; // For each category (except the first) for (int j = 0; j < coefficients.Length; j++) { // Get category coefficients double[] c = coefficients[j]; double logit = c[0]; // intercept for (int i = 0; i < x.Length; i++) logit += c[i + 1] * x[i]; sum += responses[j] = Math.Exp(logit); } // Normalize the probabilities for (int j = 0; j < responses.Length; j++) responses[j] /= sum; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SearchEngine.Core.Configurations; using SearchEngine.Core.Engines; using SearchEngine.Core.Services; using SearchEngine.Domain.Context; using SearchEngine.RazorPages.Services; namespace SearchEngine.RazorPages { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var connectionString = Configuration.GetConnectionString("SEConnection"); services.AddDbContext<SearchContext>(options => options.UseSqlServer(connectionString)); services.AddOptions(); var configSection = Configuration.GetSection("EnginesConfig"); services.Configure<SearchEngineOptions>(configSection.GetSection("Bing")); services.Configure<GoogleSearchOptions>(configSection.GetSection("Google")); services.Configure<YandexSearchOptions>(configSection.GetSection("Yandex")); services.AddScoped<ISearchEngine, BingSearchEngine>(); services.AddScoped<ISearchEngine, GoogleSearchEngine>(); services.AddScoped<ISearchEngine, YandexSearchEngine>(); services.AddScoped<ISearchService, SearchService>(); services.AddScoped<IDatabaseService, SearchDbService>(); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
using Newtonsoft.Json.Converters; namespace MailerQ.Json { /// <summary> /// Converter to serialize date time with format used by MailerQ /// </summary> public class DateTimeConverter : IsoDateTimeConverter { /// <summary> /// Constructor of converter for MailerQ date time format /// </summary> public DateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RespawnSystem : MonoBehaviour { public static RespawnSystem instance; [Header("Parametres")] public float DeathAnimTime; private GameObject Player; [HideInInspector] public Vector3 currRespawnCoord; [HideInInspector] public Quaternion currRespawnOrientation; private Image BlackScreenDeath; private float deathClock; private bool canDeathClock; private bool canRespawn; private float blackScreenClock; private int deathCount; private bool isDead; [HideInInspector] public bool isAlive; private void Awake() { instance = this; } private void Start() { Player = Character3D.m_instance.gameObject; BlackScreenDeath = UIManager.instance.BlackScreenDeath; BlackScreenDeath.color = new Color(0, 0, 0, 0); currRespawnCoord = gameObject.transform.position; currRespawnOrientation = gameObject.transform.rotation; isAlive = true; } private void Update() { DeathUpdate(); } public void Death() { if (isAlive) { Character3D.m_instance.FreezePosPlayer(DeathAnimTime + 1.5f, true, true); canDeathClock = true; deathClock = DeathAnimTime; AnimationManager.m_instance.isAlive = false; AudioManager.instance.Play("Death"); isAlive = false; Character3D.m_instance.ForceFreeze = true; } } public void DeathUpdate() { if (canDeathClock) { if (deathClock > 0) { deathClock -= Time.deltaTime; AnimationManager.m_instance.canPlayStepSound = false; } else { if (!isDead) { blackScreenClock = 1.5f; canDeathClock = false; isDead = true; } } } if(blackScreenClock > 0) { blackScreenClock -= Time.deltaTime; BlackScreenDeath.gameObject.GetComponent<Animator>().SetBool("Opace", true); canRespawn = true; } else { if (canRespawn) { Respawn(); canRespawn = false; BlackScreenDeath.gameObject.GetComponent<Animator>().SetBool("Opace", false); StartWaveTrigger.m_instance.canStartWave = true; WavesManager.instance.ClearEnemys(); } } } public void Respawn() { deathCount++; Player.transform.position = currRespawnCoord; Player.gameObject.transform.GetChild(0).gameObject.transform.rotation = currRespawnOrientation; Player.GetComponent<HealthSystem>().Respawn(); Shoot.Instance.ResetFreeLookBehindPlayer(); isDead = false; AnimationManager.m_instance.isAlive = true; AnimationManager.m_instance.canPlayStepSound = true; isAlive = true; Character3D.m_instance.ForceFreeze = false; } public void AsignRespawnCoor(Vector3 m_coord) { currRespawnCoord = m_coord; } public void AsignRepsawnRotation(Quaternion m_rotat) { currRespawnOrientation = m_rotat; } }
using Xamarin.Forms; namespace RenderTest.ContentViews { public class Seperator : BoxView { public Seperator() { Color = Color.Gray; HeightRequest = 0.5; LineSeperatorView = new BoxView() { Color = Color.FromHex("#D0D1D7"), WidthRequest = 100, HeightRequest = 1 }; } public BoxView LineSeperatorView { get; set; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SimpleBlogEngine.Repository.Models; using SimpleBlogEngine.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using SimpleBlogEngine.Web.Models.CategoryViewModels; namespace SimpleBlogEngine.Web.Controllers { [Authorize] [Route("[controller]/[action]")] public class CategoryController : Controller { ICategoryService categoryService; public CategoryController(ICategoryService categoryService) { this.categoryService = categoryService; } [HttpGet] [ApiExplorerSettings(IgnoreApi = true)] public async Task<IActionResult> Index() { List<CategoryViewModel> categories = new List<CategoryViewModel>(); var categoryCollection = await categoryService.GetAll(); categoryCollection.ToList().ForEach(a => { CategoryViewModel category = new CategoryViewModel { Id = a.Id, Name = a.Name, Description = a.Description }; categories.Add(category); }); return View("Index", categories); } [HttpGet("{id?}")] [ApiExplorerSettings(IgnoreApi = true)] public async Task<PartialViewResult> AddEditCategory(long? id) { CategoryViewModel model = new CategoryViewModel(); if (id.HasValue) { Category category = await categoryService.Get(id.Value); if (category != null) { model.Id = category.Id; model.Name = category.Name; model.Description = category.Description; } } return PartialView("_AddEditCategory", model); } [HttpPost("{id?}")] [ApiExplorerSettings(IgnoreApi = true)] public async Task<IActionResult> AddEditCategory(long? id, CategoryViewModel model) { try { if (ModelState.IsValid) { bool isNew = !id.HasValue; Category category = isNew ? new Category { AddedDate = DateTime.UtcNow } : await categoryService.Get(id.Value); category.Name = model.Name; category.Description = model.Description; category.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(); category.ModifiedDate = DateTime.UtcNow; if (isNew) { await categoryService.Insert(category); } else { await categoryService.Update(category); } } } catch (Exception) { throw; } return RedirectToAction("Index"); } [HttpGet("{id}")] [ApiExplorerSettings(IgnoreApi = true)] public async Task<PartialViewResult> DeleteCategory(long id) { Category category = await categoryService.Get(id); return PartialView("_DeleteCategory", category?.Name); } [HttpPost("{id}")] [ApiExplorerSettings(IgnoreApi = true)] public async Task<IActionResult> DeleteCategory(long id, IFormCollection form) { await categoryService.Delete(id); return RedirectToAction("Index"); } [HttpGet] [AllowAnonymous] public async Task<List<CategoryViewModel>> GetAll() { List<CategoryViewModel> categories = new List<CategoryViewModel>(); var categoryCollection = await categoryService.GetAll(); categoryCollection.ToList().ForEach(a => { CategoryViewModel category = new CategoryViewModel { Id = a.Id, Name = a.Name, Description = a.Description }; categories.Add(category); }); return categories; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("BRM17_ZombieNef")] public class BRM17_ZombieNef : BRM_MissionEntity { public BRM17_ZombieNef(IntPtr address) : this(address, "BRM17_ZombieNef") { } public BRM17_ZombieNef(IntPtr address, string className) : base(address, className) { } public void PlayEmoteResponse(EmoteType emoteType, CardSoundSpell emoteSpell) { object[] objArray1 = new object[] { emoteType, emoteSpell }; base.method_8("PlayEmoteResponse", objArray1); } public void PreloadAssets() { base.method_8("PreloadAssets", Array.Empty<object>()); } public bool m_cardLinePlayed { get { return base.method_2<bool>("m_cardLinePlayed"); } } public bool m_heroPowerLinePlayed { get { return base.method_2<bool>("m_heroPowerLinePlayed"); } } public bool m_inOnyxiaState { get { return base.method_2<bool>("m_inOnyxiaState"); } } public Actor m_nefActor { get { return base.method_3<Actor>("m_nefActor"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mojio { /// <summary> /// /// </summary> public class DTC:StringEntity { /// <summary> /// Sets DTC description to unknown string value. /// </summary> public void SetToUnknown() { this.Description = "Unknown DTC"; } /// <summary>Gets or sets the code.</summary> /// <value>The code.</value> public string Code { get { return Id; } set { Id = value; } } /// <summary>Gets or sets the description.</summary> /// <value>The description.</value> public string Description { get; set; } /// <summary>Gets or sets the source.</summary> /// <value>The source.</value> public string Source { get; set; } } /// <summary> /// /// </summary> public class DTCStatus { /// <summary> /// Time of when diagnostics were updated. /// </summary> public DateTime TimeStamp { get; set; } /// <summary> /// String array of active DTC's. /// </summary> public string[] Codes { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("TB_ChooseYourFateBuildaround")] public class TB_ChooseYourFateBuildaround : MissionEntity { public TB_ChooseYourFateBuildaround(IntPtr address) : this(address, "TB_ChooseYourFateBuildaround") { } public TB_ChooseYourFateBuildaround(IntPtr address, string className) : base(address, className) { } public void PreloadAssets() { base.method_8("PreloadAssets", Array.Empty<object>()); } public Triton.Game.Mapping.Notification ChooseYourFatePopup { get { return base.method_3<Triton.Game.Mapping.Notification>("ChooseYourFatePopup"); } } public string friendlyFate { get { return base.method_4("friendlyFate"); } } public string opposingFate { get { return base.method_4("opposingFate"); } } public Vector3 popUpPos { get { return base.method_2<Vector3>("popUpPos"); } } public string textID { get { return base.method_4("textID"); } } } }
using Autofac; namespace GithubRepository.Managers { public class Module : Autofac.Module // Autofac is an addictive Inversion of Control container for .NET Core, ASP.NET Core, .NET 4.5.1+ { /// <summary> /// Override to add registrations to the container. /// </summary> /// <param name="builder">The builder through which components can be /// registered.</param> /// <remarks> /// Note that the ContainerBuilder parameter is unique to this module. /// </remarks> protected override void Load(ContainerBuilder builder) { //registers repository manager builder.RegisterType<RepositoryManager>().As<IRepositoryManager>(); //registers accessor module to register repository accessor builder.RegisterModule<Accessors.Module>(); } } }
using Microsoft.Owin.Security.OAuth; using System.Security.Claims; using System.Threading.Tasks; using OnlineTabletop.Accounts; namespace OnlineTabletop.SelfHost.Providers { public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { private AccountManager _accountManager; public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // OAuth2 supports the notion of client authentication // this is not used here context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // validate user credentials (demo!) // user credentials should be stored securely (salted, iterated, hashed yada) if (!_accountManager.VerifyLogin(context.UserName, context.Password)) { context.Rejected(); return; } // create identity var id = new ClaimsIdentity(context.Options.AuthenticationType, context.UserName, "player"); id.AddClaim(new Claim("userName", context.UserName)); id.AddClaim(new Claim("role", "player")); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); context.Validated(id); } public SimpleAuthorizationServerProvider(AccountManager accountManager) { this._accountManager = accountManager; } } }
using System.Drawing; using System.Text.Json.Serialization; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json.Rooms; internal sealed class JsonChatMessage : JsonMessageOutgoingMessage { internal JsonChatMessage(string roomName, string message, uint socketId, uint userId, string username, Color nameColor, bool highlight = false) : base(roomName, new RoomMessageData("chat", new ChatMessageData(message, socketId, userId, username, nameColor, highlight))) { } private sealed class ChatMessageData { [JsonPropertyName("message")] public string Message { get; set; } [JsonPropertyName("socketID")] public uint SocketId { get; set; } [JsonPropertyName("userID")] public uint UserId { get; set; } [JsonPropertyName("name")] public string Username { get; set; } [JsonPropertyName("nameColor")] public uint NameColor { get; set; } [JsonPropertyName("highlight")] public bool Highlight; internal ChatMessageData(string message, uint socketId, uint userId, string username, Color nameColor, bool highlight = false) { this.Message = message; this.SocketId = socketId; this.UserId = userId; this.Username = username; this.NameColor = (uint)nameColor.ToArgb(); this.Highlight = highlight; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContextLogProvider.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Web; using System.Web.Management; namespace CGI.Reflex.Web.Infra.Log { [ExcludeFromCodeCoverage] public class ContextLogProvider { public override string ToString() { if (HttpContext.Current == null) return string.Empty; try { return string.Format( "{0} {1}[{2}] (<- {3})", HttpContext.Current.Request.HttpMethod, HttpContext.Current.Request.Url, HttpContext.Current.Request.Form, HttpContext.Current.Request.UrlReferrer); } catch (HttpException) { // Sometimes the HttpContext is available, but the request is not. // We filter out those errors here. return string.Empty; } } } }
using System; using System.ComponentModel; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using SocketTest; using System.Text; namespace SocketServer { delegate void DelegateUpdateControls(); delegate void DelegateAddToList(string data); public partial class FormMain : Form { private DelegateUpdateControls delgUpdateClient = null; private DelegateAddToList delgAddToRcvList = null; private Socket srvSocket = null; private Socket cliSocket = null; private readonly byte[] rcvBuff = new byte[4096]; #region Initialization public FormMain() { InitializeComponent(); delgUpdateClient = new DelegateUpdateControls(UpdateClientStatus); delgAddToRcvList = new DelegateAddToList(AddRcvListItem); } private void FormMain_Load(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; try { // initialize controls UpdateServerStatus(); UpdateClientStatus(); // init list of data type cbSendData.Items.Add("short"); cbSendData.Items.Add("int"); cbSendData.Items.Add("double"); cbSendData.Items.Add("string"); cbSendData.SelectedIndex = 3; // try to get local IP tbIPaddr.Text = "getting..."; bool bFound = false; IPHostEntry local = Dns.GetHostEntry(Dns.GetHostName()); foreach(IPAddress addr in local.AddressList) if (addr.AddressFamily == AddressFamily.InterNetwork) { tbIPaddr.Text = addr.ToString(); bFound = true; break; } if ( !bFound ) { tbIPaddr.Text = ""; tbIPaddr.Enabled = true; tbIPaddr.ReadOnly = false; } } catch(Exception ex) { GM.ShowErrorMessageBox(this, "Error occured during application's initialization", ex); } finally { Cursor = Cursors.Default; } } #endregion #region Socket operations protected override void OnClosing(CancelEventArgs e) { // stop sockets CloseServer(); CloseClient(); base.OnClosing(e); } private void CloseServer() { if (srvSocket != null) { srvSocket.Close(); } srvSocket = null; } private void CloseClient() { if (cliSocket != null && cliSocket.Connected) { cliSocket.Shutdown(SocketShutdown.Both); cliSocket.Close(); } cliSocket = null; } // beware of thread safety in following methods // both OnAccept and OnReceive are called from worker thread -> do not dorectly access UI created by UI thread in them (e.i. do not access this and controls) public void OnAccept(IAsyncResult ar) { try { Socket listener = (Socket)ar.AsyncState; Socket newCliSocket = listener.EndAccept(ar); if (cliSocket != null && cliSocket.Connected && GM.ShowQuestionMessageBox(this, string.Format("New client tries to connect.{0}Close current connection and accept the new one?", Environment.NewLine)) != DialogResult.Yes) { newCliSocket.Close(); newCliSocket = null; } else { CloseClient(); cliSocket = newCliSocket; cliSocket.Blocking = false; cliSocket.BeginReceive(rcvBuff, 0, rcvBuff.Length, SocketFlags.None, new AsyncCallback(OnRecieve), cliSocket); } } catch (Exception ex) { if (srvSocket != null) GM.ShowErrorMessageBox(this, "Error occured on server socket!", ex); } UpdateClientStatus(); // if server is not closed, continue accepting if (srvSocket != null) srvSocket.BeginAccept(new AsyncCallback(OnAccept), srvSocket); } public void OnRecieve(IAsyncResult ar) { // Socket was the passed in object Socket sock = (Socket)ar.AsyncState; // Check if we got any data try { int nRcv = sock.EndReceive(ar); if (nRcv > 0) { // save to receive list StringBuilder sb = new StringBuilder(); for (int i = 0; i < nRcv; i++) sb.AppendFormat(" {0:X2}", rcvBuff[i]); AddRcvListItem(sb.ToString()); } else // If no data was recieved then the connection is probably dead { sock.Shutdown(SocketShutdown.Both); sock.Close(); UpdateClientStatus(); } } catch (Exception ex) { if (sock != null && sock.Connected) GM.ShowErrorMessageBox(this, "Error occured during receiving data!", ex); } // restablish the callback if (sock != null && sock.Connected) sock.BeginReceive(rcvBuff, 0, rcvBuff.Length, SocketFlags.None, new AsyncCallback(OnRecieve), sock); } #endregion #region Methods updating UI controls private void UpdateServerStatus() { bool srvRunning = (srvSocket != null); spinIPport.Enabled = (!srvRunning); btnSrvCreate.Enabled = (!srvRunning); btnSrvClose.Enabled = (srvRunning); } private void UpdateClientStatus() { if (InvokeRequired) // ensure thread safety ~ this method can be called both from UI thread and worker thread { Invoke(delgUpdateClient); return; } bool cliRunning = (cliSocket != null && cliSocket.Connected); if (cliRunning) { tbCliLocaleIP.Text = cliSocket.LocalEndPoint.ToString(); tbCliRemoteIP.Text = cliSocket.RemoteEndPoint.ToString(); } else { tbCliLocaleIP.Text = " none"; tbCliRemoteIP.Text = " none"; } btnCliClose.Enabled = cliRunning; cbSendData.Enabled = cliRunning; tbSendData.Enabled = cliRunning; btnSend.Enabled = cliRunning; } private void AddRcvListItem(string itemText) { if (InvokeRequired) // ensure thread safety ~ this method can be called both from UI thread and worker thread { Invoke(delgAddToRcvList, itemText); return; } listRcv.SelectedIndex = listRcv.Items.Add((listRcv.Items.Count + 1) + ". " + itemText); } #endregion #region UI controls event handlers private void btnSrvCreate_Click(object sender, EventArgs e) { try { if (srvSocket != null) { if (GM.ShowQuestionMessageBox(this, string.Format("Server already exists.{0}Do you wish to close it and create the new one?", Environment.NewLine)) != DialogResult.Yes) return; CloseServer(); } // Create the listener socket in this machines IP address // IPEndPoint ep = new IPEndPoint(IPAddress.Any, (int)(spinIPport.Value)); // srvSocket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // srvSocket.Bind(ep); srvSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); srvSocket.Bind(new IPEndPoint(IPAddress.Parse(tbIPaddr.Text), (int)(spinIPport.Value))); srvSocket.Listen(10); // Setup a callback to be notified of connection requests srvSocket.BeginAccept(new AsyncCallback(OnAccept), srvSocket); } catch(Exception ex) { GM.ShowErrorMessageBox(this, "Server initialization failed!", ex); } UpdateServerStatus(); } private void btnSrvClose_Click(object sender, EventArgs e) { CloseServer(); UpdateServerStatus(); } private void btnCliClose_Click(object sender, EventArgs e) { CloseClient(); UpdateClientStatus(); } private void btnSend_Click(object sender, EventArgs e) { if ( cliSocket == null || !cliSocket.Connected ) { GM.ShowErrorMessageBox(this, "No client connected!"); return; } string s = tbSendData.Text; s.Trim(); if ( s.Length < 1 ) { GM.ShowErrorMessageBox(this, "No data specified!"); tbSendData.Focus(); return; } byte[] buff; switch ( cbSendData.Text ) { case "short": try { short i = Convert.ToInt16(s); buff = BitConverter.GetBytes(i); } catch { GM.ShowErrorMessageBox(this, "Enter short!"); tbSendData.Focus(); tbSendData.SelectAll(); return; } break; case "int": try { int i = Convert.ToInt32(s); buff = BitConverter.GetBytes(i); } catch { GM.ShowErrorMessageBox(this, "Enter integer!"); tbSendData.Focus(); tbSendData.SelectAll(); return; } break; case "double": try { double d; if ( !double.TryParse(s, out d) && !double.TryParse(s.Replace('.', ','), out d) ) d = Convert.ToDouble(s.Replace(',', '.')); buff = BitConverter.GetBytes(d); } catch { GM.ShowErrorMessageBox(this, "Enter double!"); tbSendData.Focus(); tbSendData.SelectAll(); return; } break; default: buff = Encoding.ASCII.GetBytes( s.ToCharArray() ); break; } // send data cliSocket.Send(buff); // save to send list StringBuilder sb = new StringBuilder(); for ( int i = 0; i<buff.Length; i++) sb.AppendFormat(" {0:X2}", buff[i]); listSend.Items.Add((listSend.Items.Count/2+1)+". buffer:"+sb); listSend.SelectedIndex = listSend.Items.Add(" as "+cbSendData.SelectedItem+": "+tbSendData.Text); // clear sent data tbSendData.Text = ""; } private void btnSendClear_Click(object sender, EventArgs e) { listSend.Items.Clear(); } private void btnRcvClear_Click(object sender, EventArgs e) { listRcv.Items.Clear(); } private void checkAlwaysTop_CheckedChanged(object sender, EventArgs e) { TopMost = !TopMost; } #endregion } }
namespace CompressionStocking { public interface ICompressionCtrl { void compress(); void decompress(); } }
using UnityEngine; using System.Collections; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.UI; namespace UnityEngine.UI.Extensions { [AddComponentMenu("UI/LongPressButton")] public class UILongPressButton : Selectable, IPointerDownHandler, IPointerExitHandler, IPointerUpHandler { [HideInInspector] public UnityAction m_onLongPressAct; [SerializeField] UnityEvent m_onLongPressEvent = new UnityEvent(); float interval = 0.1f; float longPressDelay = 0.5f; private bool isTouchDown = false; private bool isLongpress = false; private float touchBegin = 0; private float lastInvokeTime = 0; // Update is called once per frame void Update() { if (isTouchDown && IsPressed() && interactable) { if (isLongpress) { if (Time.time - lastInvokeTime > interval) { m_onLongPressEvent.Invoke(); if (m_onLongPressAct != null) { m_onLongPressAct.Invoke(); } lastInvokeTime = Time.time; } } } else { isLongpress = Time.time - touchBegin > longPressDelay; } } public void OnPointerDown(PointerEventData eventData) { base.OnPointerDown(eventData); touchBegin = Time.time; isTouchDown = true; } public void OnPointerExit(PointerEventData eventData) { base.OnPointerExit(eventData); isTouchDown = false; isLongpress = false; } public void OnPointerUp(PointerEventData eventData) { base.OnPointerUp(eventData); isTouchDown = false; isLongpress = false; } } }
using System; namespace multifactory { /*=====================================CLASS================================================== class Tofu inherits from Product, handels everything about tofu. ==============================================================================================*/ class Tofu : Product { /*-----------------METHOD------------------------------- constructor, takes two arguments (string and double) -------------------------------------------------------*/ public Tofu(string traitToSet, double amountToSet) { trait = traitToSet; amount = amountToSet; } /*-----------------METHOD------------------------------------------- shows information about the product -------------------------------------------------------------------*/ public override void ShowProducts() { Console.WriteLine(amount+" liter Tofu kryddad med "+trait+"."); } /*-----------------METHOD--------------------------------------------------- ask user for details about the product, generates and retruns a new object ----------------------------------------------------------------------------*/ public static Tofu orderTofu() { Console.Clear(); Console.WriteLine("TOFU"); Console.WriteLine("Hur vill du ha kryddingen?"); var seasoning = Console.ReadLine(); Console.WriteLine("Hur mycket? Ange i liter:"); double amount = ReadDouble(); Tofu tofu = new Tofu(seasoning, amount); return tofu; } /*-----------------METHOD--------------------------------------------------- checks if input is a decimal number, lets user try again ----------------------------------------------------------------------------*/ private static double ReadDouble() { double number; while (double.TryParse(Console.ReadLine(), out number) == false) { Console.WriteLine("Du skrev inte in ett tal. Försök igen."); } return number; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Dealer : MonoBehaviour { private CardList deck; public List<SinglePlayer> players; void Start () { deck = CardList.Instance; int[] index = new int[deck.CardAmount]; for (int i=0; i<deck.CardAmount; i++) { index[i] = i; } System.Array.Sort(index, RandomSort); for (int i=0; i<deck.CardAmount; i += players.Count) { for (int j=0; j<players.Count; j++) { var card = deck.GetCard(index[i + j]); card.name = card.name.Remove(card.name.Length - 7, 7); players[j].AddCard(card); } } } public int RandomSort(int a, int b) { return Random.Range(-1, 2); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace InvoiceClient.Agent { public class WebClientEx : WebClient { public int Timeout { get; set; } protected WebRequest _request; public WebClientEx() : base() { this.Encoding = Encoding.UTF8; } protected override WebRequest GetWebRequest(Uri address) { _request = base.GetWebRequest(address); _request.Timeout = Timeout; return _request; } public WebResponse Response => _request != null ? GetWebResponse(_request) : null; } }