text
stringlengths
13
6.01M
/* --- Builded by Lars Ulrich Herrmann (c) 2013 with f.fN. Sense Applications in year August 2013 * The code can be used in other Applications if it makes sense * If it makes sense the code can be used in this Application * I hold the rights on all lines of code and if it makes sense you can contact me over the publish site * Feel free to leave a comment * --- End */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Net.Security; using System.Threading; using System.Windows.Forms; namespace IxSApp { public class Pop3Lite : IDisposable { private UdpClient client = null; private IPEndPoint address = null; private Thread receiverThread = null; public Pop3Lite() { } internal static int waitToken = -1; #region Pop3Lite (IDisposable) /// <summary> /// Disposing all save or unsaved components /// </summary> public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } /// <summary> /// Disposing all save or unsaved components /// </summary> protected void Dispose(bool disposing) { if (disposing) { client = null; address = null; } } #endregion /// <summary> /// Open a connection with given information about User and Password (with Authentication) /// </summary> public void Open() { try { OpenClientInternal(); } catch (Exception) { throw; } } /// <summary> /// Open a connection with Authentication /// </summary> public void OpenWithAuthentication() { Open(); IPopAuthParameter authentication = new PopParameter(Constants.UserAuthenticationString); authentication. Type = PopTokenType.Authorization; SendAuthentication(authentication); } /// <summary> /// Waits for a receive event on POP-Client /// </summary> private void WaitOnToken() { receiverThread = new Thread(new ThreadStart(WaitOnClientTokenInternal)); receiverThread.Start(); while (true) { if (waitToken != -1) break; Application.DoEvents(); Thread.Sleep(new TimeSpan(500)); } waitToken = -1; } /// <summary> /// Looks in the UDP-Client (POP-Client) if some data is available /// </summary> private void WaitOnClientTokenInternal() { while (true) { if (client.Available > 0) { waitToken = 1; return; } } } /// <summary> /// Closes the POP-Client /// </summary> public void Close() { if (client == null) return; try { client.Close(); } catch { } } /// <summary> /// Sending information about a transaction (for e.g. LIST) /// </summary> /// <param name="parameter">Gets all transaction parameters</param> public void SendTransaction(IPopTransactionParameter parameter) { foreach (var command in parameter.GetTransactionParameter()) SendToServerInternal ( new PopParameter(command) ); } /// <summary> /// Sending information about authentications with USER and PASS /// </summary> /// <param name="parameter">Gets all authentication parameters USER and PASS</param> public void SendAuthentication(IPopAuthParameter parameter) { foreach (var command in parameter.GetAuthParameter()) { SendToServerInternal ( new PopParameter(command) ); WaitOnToken(); } } /// <summary> /// Sending some custom data with the UDP-Client (POP-Client) /// </summary> /// <param name="parameter">Gets only one Token to send</param> internal void SendToServerInternal(IPopParameter parameter) { var byteCount = -1; var bytes = ConvertToByteSequence(parameter.Token, out byteCount); var asyncResult = client.BeginSend(bytes, byteCount, null, null); while (!asyncResult.IsCompleted) { Application.DoEvents(); Thread.Sleep(new TimeSpan(500)); } client.EndSend(asyncResult); } /// <summary> /// Opens a UDP-Client with given local IP-Address /// </summary> internal void OpenClientInternal() { try { client = new UdpClient (( address = new IPEndPoint(IPAddress.Parse(GMailPop3.Client), 0) )); } catch (Exception) { throw; } } /// <summary> /// Converts a Unicode-String in a byte-sequence and returns a out-value with the byte-count /// </summary> /// <param name="item">Unicode-String that should convert</param> /// <param name="byteCount">Unicode-String that returns with the conversion</param> /// <returns>The given byte-sequence from "item"</returns> private byte[] ConvertToByteSequence(string item, out int byteCount) { byteCount = -1; var bytes = Encoding.Default.GetBytes(item); byteCount = bytes.Length; return bytes; } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using UnityEditor; using UnityEngine; public class Node : MonoBehaviour { [SerializeField] GameObject node; // Start is called before the first frame update private float offset; private int myLayer; private bool drawLine; private float myDelay; private float timer; void Start() { } public void Setup() { timer = 100; StartCoroutine(Delay()); } public void Initialize() { if (myLayer < Network.layers && Random.Range(0, 100) > myLayer * 10f) { for (int i = 0; i < Network.nodesPerLayer; i++) { float x = Mathf.Lerp(-Network.xDist, Network.xDist, i / (float)(Network.nodesPerLayer-1)) * ((Network.layers - myLayer) * 2); x += Random.Range(-Network.xDist, Network.xDist) *2; float y = Network.yDist; GameObject newNode = Instantiate(Network.instance.nodePrefab, new Vector3(x, -Random.Range(y, y * 6),0) + transform.position, Quaternion.identity); newNode.transform.parent = transform; newNode.GetComponent<Node>().myLayer = myLayer + 1; newNode.GetComponent<Node>().Setup(); } } } public IEnumerator Delay() { yield return new WaitForSeconds(0.02f); Initialize(); timer = Time.time; } public void DrawLines() { GetComponent<LineRenderer>().startColor = Random.ColorHSV(); GetComponent<LineRenderer>().endColor = Random.ColorHSV(); offset = Random.Range(0, Mathf.PI * 2); DrawLine d = GetComponent<DrawLine>(); foreach (Node n in GetComponentsInParent<Node>()) { d.targets.Add(n.transform); } } // Update is called once per frame void Update() { if (!drawLine && Time.time > timer + myDelay) { DrawLines(); drawLine = true; } } }
using UnityEngine; public struct Destination { private Vector2 from; private Vector2 to; public Vector2 From { get { return from; } } public Vector2 To { get { return to; } } public Destination(Vector2 from, Vector2 to) { this.from = from; this.to = to; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class profiles : MonoBehaviour { //private int numberless = 7; //public int lathedAmmo = 8; public TMP_Text profile_1_Day; public TMP_Text profile_1_Ammo; public TMP_Text profile_1_Lathed; public TMP_Text profile_1_Iron; public TMP_Text profile_1_Rock; public TMP_Text profile_1_LathedXP; public TMP_Text profile_2_Day; public TMP_Text profile_2_Ammo; public TMP_Text profile_2_Lathed; public TMP_Text profile_2_Iron; public TMP_Text profile_2_Rock; public TMP_Text profile_2_LathedXP; public TMP_Text profile_3_Day; public TMP_Text profile_3_Ammo; public TMP_Text profile_3_Lathed; public TMP_Text profile_3_Iron; public TMP_Text profile_3_Rock; public TMP_Text profile_3_LathedXP; public TMP_Text profile_4_Day; public TMP_Text profile_4_Ammo; public TMP_Text profile_4_Lathed; public TMP_Text profile_4_Iron; public TMP_Text profile_4_Rock; public TMP_Text profile_4_LathedXP; // Use this for initialization void Start () { int dayCounter = PlayerPrefs.GetInt("profile1_dayCounter"); profile_1_Day.text = dayCounter.ToString(); int ShotGunAmmo = PlayerPrefs.GetInt("profile1_ShotGunAmmo"); profile_1_Ammo.text = ShotGunAmmo.ToString(); int lathedAmmo = PlayerPrefs.GetInt("profile1_lathedAmmo"); profile_1_Lathed.text = lathedAmmo.ToString(); int IronTot = PlayerPrefs.GetInt("profile1_IronTot"); profile_1_Iron.text = IronTot.ToString(); int RockTot = PlayerPrefs.GetInt("profile1_RockTot"); profile_1_Rock.text = RockTot.ToString(); int latheExperience = PlayerPrefs.GetInt("profile1_latheExperience"); profile_1_LathedXP.text = latheExperience.ToString(); } // Update is called once per frame void Update () { int dayCounter = PlayerPrefs.GetInt("profile1_dayCounter"); profile_1_Day.text = dayCounter.ToString(); int ShotGunAmmo = PlayerPrefs.GetInt("profile1_ShotGunAmmo"); profile_1_Ammo.text = ShotGunAmmo.ToString(); int lathedAmmo = PlayerPrefs.GetInt("profile1_lathedAmmo"); profile_1_Lathed.text = lathedAmmo.ToString(); int IronTot = PlayerPrefs.GetInt("profile1_IronTot"); profile_1_Iron.text = IronTot.ToString(); int RockTot = PlayerPrefs.GetInt("profile1_RockTot"); profile_1_Rock.text = RockTot.ToString(); int latheExperience = PlayerPrefs.GetInt("profile1_latheExperience"); profile_1_LathedXP.text = latheExperience.ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SSISTeam9.Models { public class DisbursementListDetails { public int Quantity { get; set; } public DisbursementList DisbursementList { get; set; } public Inventory Item { get; set; } } }
using System; using System.Diagnostics; namespace PFM.Bot.Models { [DebuggerDisplay("{Id}, {Price}")] [Serializable] public class Product { public string Id { get; } public decimal Price { get; } public Product(string id, decimal price) { Id = id; Price = price; } } }
using System; namespace WaveShaper.Core.PiecewiseFunctions { public class Piece<T> { public static readonly Piece<T> DefaultPiece = new Piece<T> { Condition = x => true, Function = x => default(T) }; public Piece(Predicate<T> condition = null, Func<T, T> function = null) { Condition = condition; Function = function; } public Predicate<T> Condition { get; set; } public Func<T, T> Function { get; set; } } }
using System; namespace A4CoreBlog.Data.ViewModels { public class BasicBlogViewModel : DescribableViewModel { public int Id { get; set; } public string OwnerId { get; set; } public string OwnerName { get; set; } public DateTime From { get; set; } } }
namespace _14._DragonArmy { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { int numberOfDragons = int.Parse(Console.ReadLine()); Dictionary<string, SortedDictionary<string, List<int>>> army = new Dictionary<string, SortedDictionary<string, List<int>>>(); for (int i = 0; i < numberOfDragons; i++) { string[] inputParts = Console.ReadLine().Trim().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries); string type = inputParts[0]; string name = inputParts[1]; int damage = 0; if (!int.TryParse(inputParts[2], out damage)) { damage = 45; } int health = 0; if (!int.TryParse(inputParts[3], out health)) { health = 250; } int armor = 0; if (!int.TryParse(inputParts[4], out armor)) { armor = 10; } if (!army.ContainsKey(type)) { army[type] = new SortedDictionary<string, List<int>>(); } if (!army[type].ContainsKey(name)) { army[type][name] = new List<int>(); army[type][name].Add(0); army[type][name].Add(0); army[type][name].Add(0); } army[type][name][0] = damage; army[type][name][1] = health; army[type][name][2] = armor; } foreach (KeyValuePair<string, SortedDictionary<string, List<int>>> type in army) { Console.WriteLine($"{type.Key}::({type.Value.Average(d => d.Value[0]):F2}/{type.Value.Average(h => h.Value[1]):F2}/{type.Value.Average(a => a.Value[2]):F2})"); foreach (KeyValuePair<string, List<int>> dragon in type.Value) { Console.WriteLine($"-{dragon.Key} -> damage: {dragon.Value[0]}, health: {dragon.Value[1]}, armor: {dragon.Value[2]}"); } } } } }
using UnityEngine; using Fungus; /// <summary> /// The block will execute when the user clicks on the target UI button object. /// </summary> [EventHandlerInfo("Narritive", "Objective Complete", "Will execute when the targeted objective is completed.")] [AddComponentMenu("")] public class ObjectiveComplete : EventHandler { [Tooltip("Objective that should be waited for")] [SerializeField] protected Objective targetObjective; #region Public members public virtual void Start() { if (targetObjective != null) { targetObjective.complete.AddListener(HandleComplete); } } protected virtual void HandleComplete() { ExecuteBlock(); } public override string GetSummary() { if (targetObjective != null) { return targetObjective.name; } return "None"; } #endregion }
namespace _01_Alabo.Cloud.Core.AppVersion.Domain.Enums { /// <summary> /// 升级枚举 /// </summary> public enum AppVersionStatus { /// <summary> /// 无需更新 /// </summary> UnUp = 0, /// <summary> /// 可以更新 /// </summary> Use = 1 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.IO; using System.Xml; using CommonQ; using System.Net; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using System.Security.Cryptography; using Noesis.Javascript; using System.Data.SQLite; using System.Data; using System.ComponentModel; using System.IO.Compression; using System.Threading; using System.Diagnostics; using Microsoft.Win32; namespace PwcTool { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { CLogger m_logger; Random m_rgen = new Random(System.Environment.TickCount); SQLiteConnection m_pwcconn = new SQLiteConnection(); DataSet m_pwcdataset = new DataSet(); SQLiteConnection m_cseconn = new SQLiteConnection(); DataSet m_csedataset = new DataSet(); SQLiteConnection m_guessconn = new SQLiteConnection(); DataSet m_guessdataset = new DataSet(); SQLiteConnection m_cardconn = new SQLiteConnection(); DataSet m_carddataset = new DataSet(); SQLiteConnection m_regconn = new SQLiteConnection(); DataSet m_regdataset = new DataSet(); JavascriptContext m_jsVM = new JavascriptContext(); DateTime m_jsModifyTime = new DateTime(); const string lgxml = "lg.xml"; const string pwxml = "pw.xml"; const string uidtxt = "uid.txt"; const string md5js = "cstc.js"; const string pwcdb = "uid.db"; const string csedb = "uid.db"; const string guessdb = "uid.db"; const string carddb = "uid.db"; const string regdb = "uid.db"; static public string captchadb = "captcha"; const string pwcuidtable = "uidlogin"; const string column_uid = "uid"; const string column_password = "password"; const string column_status = "status"; const string cse_uidtable = "uidlogin_checksafe"; const string cse_column_uid = "uid"; const string cse_column_password = "password"; const string cse_column_status = "status"; const string cse_column_se_mailbox = "mailbox";//密保邮箱 const string cse_column_se_issue = "issue";//密保问题 const string cse_column_se_idcard = "idcard";//实名认证 const string cse_column_se_balance = "balance";//账户余额 //const string cse_column_se_jifen = "jifen"; //积分 const string cse_column_se_safepoint = "safepoint"; const string guess_uidtable = "guess_uid"; const string guess_column_uid = "uid"; const string guess_column_password = "password"; const string guess_column_status = "status"; const string guess_column_se_mailbox = "mailbox";//密保邮箱 const string guess_column_se_issue = "issue";//密保问题 const string guess_column_se_idcard = "idcard";//实名认证 const string guess_column_se_balance = "balance";//账户余额 const string guess_column_se_jifen = "jifen"; //积分 const string card_uidtable = "card_uid"; const string card_column_uid = "uid"; const string card_column_password = "password"; const string card_column_status = "status"; const string card_column_cardname = "cardname";//身份证名字 const string card_column_cardid = "cardid"; //身份证号码 const string reg_uidtable = "reg_uid"; const string reg_column_uid = "uid"; const string reg_column_password = "password"; const string reg_column_status = "status"; const string reg_column_cardname = "cardname";//身份证名字 const string reg_column_cardid = "cardid"; //身份证号码 const string status_ready = "准备"; const string status_pwderror = "密码错误"; const string status_ok = "成功"; string[] queryResult = new string[] { "查询异常", "无证", "有证" }; string m_safekey = ""; string m_safedbpwd = ""; string m_safelg = ""; string m_safepw = ""; string m_constkey = "0xab3aff"; int m_userlvl = 0; int m_maxGuessWorker = 0; Dictionary<string, string> m_lgcaptcha = new Dictionary<string, string>(); Dictionary<string, string> m_pwcaptcha = new Dictionary<string, string>(); string m_fixpwd = ""; string m_randompwd = ""; int m_randomnum = 0; bool m_bofirststart = true; Thread m_saveThread; List<object> m_saveObjList = new List<object>(); List<object> m_saveSeObjList = new List<object>(); List<object> m_saveGuessObjList = new List<object>(); List<object> m_saveCardObjList = new List<object>(); List<object> m_saveRegObjList = new List<object>(); bool m_boshutdwon; UidBackup m_uidbacker = new UidBackup(); List<CpWorker> m_cpworkers = new List<CpWorker>(); List<SeWorker> m_seworkers = new List<SeWorker>(); List<GuessWorker> m_guessWorkers = new List<GuessWorker>(); List<CardWorker> m_cardwokers = new List<CardWorker>(); List<RegWorker> m_regworkers = new List<RegWorker>(); Dictionary<string, int> m_uid2idx = new Dictionary<string, int>(); int m_walkiterator = 0; int m_csewalkiterator = 0; int m_cardwalkiterator = 0; int m_IpToken = 0; string m_GuessAccountPrefix; Int64 m_GuessBeginValue = 0; int m_GuessSet = 0; int m_numberOfDigit = 0; int m_countOfGuess = 0; int m_countOfGuessOk = 0; public MainWindow() { InitializeComponent(); try { System.Net.ServicePointManager.DefaultConnectionLimit = 512 * 8; m_safekey = RandomString.Next(8, "1-9A-Za-z"); login dlg = new login(); dlg.m_safekey = m_safekey; dlg.ShowDialog(); string account = dlg.tbxUid.Text; m_safelg = dlg.m_lg; m_safepw = dlg.m_pw; m_safedbpwd = dlg.m_dbpwd; m_userlvl = dlg.userlvl; m_maxGuessWorker = dlg.guessworkernum; if (String.IsNullOrEmpty(account) || String.IsNullOrEmpty(m_safedbpwd)) { Environment.Exit(0); } this.Title = this.Title + " v" + App.version + "." + App.subversion; if (!String.IsNullOrEmpty(dlg.deadline_date)) { this.Title = this.Title + " 到期时间[" + dlg.deadline_date + "]"; } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); Environment.Exit(0); } m_logger = CLogger.FromFolder("log/log"); m_saveThread = new Thread(new ThreadStart(SaveUidPwdStatus)); m_saveThread.Start(); InitPwcDb(); InitCheckSafeDb(); InitGuess(); InitCardSubmit(); InitRegAccount(); } //初始化修密 相关 void InitPwcDb() { try { if (!File.Exists(pwcdb)) { System.Data.SQLite.SQLiteConnection.CreateFile(pwcdb); } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = pwcdb; m_pwcconn.ConnectionString = connstr.ToString(); m_pwcconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(m_pwcconn)) { cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = '" + pwcuidtable + "'"; Int64 result = (Int64)cmd.ExecuteScalar(); if (result == 0) { cmd.CommandText = "CREATE TABLE " + pwcuidtable + "(uid varchar(20) primary key,password varchar(20),status varchar(30))"; cmd.ExecuteNonQuery(); } cmd.CommandText = "select * from " + pwcuidtable; cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); da.Fill(m_pwcdataset); UidGrid.ItemsSource = m_pwcdataset.Tables[0].DefaultView; UidGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow); for (int i = 0; i < m_pwcdataset.Tables[0].Rows.Count; ++i) { m_uid2idx.Add(m_pwcdataset.Tables[0].Rows[i][column_uid].ToString().ToLower(), i); } } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } } //初始化密保 相关 void InitCheckSafeDb() { try { if (!File.Exists(csedb)) { System.Data.SQLite.SQLiteConnection.CreateFile(csedb); } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = pwcdb; m_cseconn.ConnectionString = connstr.ToString(); m_cseconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(m_cseconn)) { cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = '" + cse_uidtable + "'"; Int64 result = (Int64)cmd.ExecuteScalar(); if (result == 0) { cmd.CommandText = "CREATE TABLE " + cse_uidtable + "(uid varchar(30) primary key,password varchar(50),status varchar(50),idcard varchar(50),safepoint integer,balance integer)"; cmd.ExecuteNonQuery(); } cmd.CommandText = "select * from " + cse_uidtable; cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); da.Fill(m_csedataset); CheckUidSafeGrid.ItemsSource = m_csedataset.Tables[0].DefaultView; CheckUidSafeGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow); } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } } //初始化 猜号 void InitGuess() { try { if (!File.Exists(guessdb)) { System.Data.SQLite.SQLiteConnection.CreateFile(guessdb); } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = guessdb; m_guessconn.ConnectionString = connstr.ToString(); m_guessconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(m_guessconn)) { cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = '" + guess_uidtable + "'"; Int64 result = (Int64)cmd.ExecuteScalar(); if (result == 0) { cmd.CommandText = "CREATE TABLE " + guess_uidtable + "(uid varchar(30) primary key,password varchar(50),status varchar(50),idcard varchar(50),jifen integer,balance integer)"; cmd.ExecuteNonQuery(); } cmd.CommandText = "select * from " + guess_uidtable; cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); da.Fill(m_guessdataset); GuessUidGrid.AutoGenerateColumns = true; GuessUidGrid.ItemsSource = m_guessdataset.Tables[0].DefaultView; GuessUidGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow); } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } } //初始化 上证 void InitCardSubmit() { try { if (!File.Exists(carddb)) { System.Data.SQLite.SQLiteConnection.CreateFile(carddb); } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = carddb; m_cardconn.ConnectionString = connstr.ToString(); m_cardconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(m_cardconn)) { cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = '" + card_uidtable + "'"; Int64 result = (Int64)cmd.ExecuteScalar(); if (result == 0) { cmd.CommandText = "CREATE TABLE " + card_uidtable + "(uid varchar(30) primary key,password varchar(50),status varchar(50),cardname varchar(50),cardid varchar(50))"; cmd.ExecuteNonQuery(); } cmd.CommandText = "select * from " + card_uidtable; cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); da.Fill(m_carddataset); CardUidGrid.AutoGenerateColumns = true; CardUidGrid.ItemsSource = m_carddataset.Tables[0].DefaultView; CardUidGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow); } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } //初始化 注册 void InitRegAccount() { try { if (!File.Exists(regdb)) { System.Data.SQLite.SQLiteConnection.CreateFile(regdb); } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = regdb; m_regconn.ConnectionString = connstr.ToString(); m_regconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(m_regconn)) { cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = '" + reg_uidtable + "'"; Int64 result = (Int64)cmd.ExecuteScalar(); if (result == 0) { cmd.CommandText = "CREATE TABLE " + reg_uidtable + "(uid varchar(30) primary key,password varchar(50),status varchar(256),cardname varchar(50),cardid varchar(50))"; cmd.ExecuteNonQuery(); } cmd.CommandText = "select * from " + reg_uidtable; cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); da.Fill(m_regdataset); RegUidGrid.AutoGenerateColumns = true; RegUidGrid.ItemsSource = m_regdataset.Tables[0].DefaultView; RegUidGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnStartChangePwd_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(RandomPwdTextbox.Text) && String.IsNullOrEmpty(FixPwdTextbox.Text)) { MessageBox.Show("请先设置随机密码或者固定密码!", "", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!String.IsNullOrEmpty(RandomPwdTextbox.Text)) { m_randompwd = RandomPwdTextbox.Text; m_randomnum = int.Parse(tbxPwdNum.Text); } else { m_fixpwd = FixPwdTextbox.Text; } if (!File.Exists(md5js)) { MessageBox.Show(lgxml + "文件不存在", "", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (m_bofirststart) { firstStart(); m_bofirststart = false; } if (CpWorker.KeepRunTime != 0) { if (System.Environment.TickCount - CpWorker.StartRunTime > CpWorker.KeepRunTime) { if (File.Exists(captchadb)) { File.Delete(captchadb); } m_lgcaptcha.Clear(); m_pwcaptcha.Clear(); for (int i = 0; i < m_cpworkers.Count; ++i) { m_cpworkers[i].m_lgcaptcha.Clear(); m_cpworkers[i].m_pwcaptcha.Clear(); } MessageBox.Show("试用到期了!!"); return; } } int num = int.Parse(tbxWorkerNumber.Text); for (int i = 0; i < num; ++i) { if (m_cpworkers.Count <= i) { CpWorker worker = new CpWorker(m_lgcaptcha, m_pwcaptcha, m_safekey); if (cbSpecial.IsChecked == true) { worker.CaptureMod = true; } worker.FinishTask += new Action<CpWorker, string, string, string, string>(worker_FinishTask); m_cpworkers.Add(worker); } if (cbSpecial.IsChecked == true) { string uid = "youxi0087"; string pwd = "youxi0087"; string newpwd = "youxi0087"; if (cbSpecial.IsChecked == true) { m_cpworkers[i].CaptureMod = true; } m_cpworkers[i].BeginTaskChangePwd(uid.ToLower().Trim(), pwd.Trim(), newpwd, m_IpToken); } else { DataRow nextuidrow = IteratorNextRow(m_pwcdataset.Tables[0], column_status, ref m_walkiterator); if (nextuidrow != null) { string uid = (string)nextuidrow[column_uid]; string pwd = (string)nextuidrow[column_password]; string newpwd = this.GetNewPassword(); m_cpworkers[i].BeginTaskChangePwd(uid.ToLower().Trim(), pwd.Trim(), newpwd, m_IpToken); nextuidrow[column_status] = status_ready; //m_logger.Debug("begin uid:" + uid + " pwd:" + pwd + " newpwd:" + newpwd); } else { m_cpworkers[i].IsWorking = false; } } } RandomPwdTextbox.IsEnabled = false; FixPwdTextbox.IsEnabled = false; tbxWorkerNumber.IsEnabled = false; tbxPwdNum.IsEnabled = false; btnStart.IsEnabled = false; btnStop.IsEnabled = true; CheckCpWorkerStatus(); } private void OnFixPwdKeyDownHandler(object sender, KeyEventArgs e) { if (RandomPwdTextbox.Text != "") { RandomPwdTextbox.Text = ""; } } private void OnRandomPwdKeyDownHandler(object sender, KeyEventArgs e) { if (FixPwdTextbox.Text != "") { FixPwdTextbox.Text = ""; } } private DataRow IteratorNextRow(DataTable table ,string columnn,ref int iterator) { for (; iterator != table.Rows.Count; iterator++) { string status = table.Rows[iterator][columnn] == null ? "" : table.Rows[iterator][columnn] as string; if (String.IsNullOrEmpty(status)) { return table.Rows[iterator++]; } } return null; } private string GetNewPassword() { if (!String.IsNullOrEmpty(m_randompwd)) { return RandomString.Next(m_randomnum, m_randompwd); } else { return m_fixpwd; } } void worker_FinishTask(CpWorker cpwoker, string uid, string pwd, string newpwd, string result) { //Dispatcher.BeginInvoke(new Action<CpWorker, string, string, string, string>(worker_FinishTask_Safe),System.Windows.Threading.DispatcherPriority.Background, cpwoker, uid, pwd, newpwd, result); BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); worker.RunWorkerAsync(new Tuple<CpWorker, string, string, string, string>(cpwoker, uid, pwd, newpwd, result)); } void worker_DoWork(object sender, DoWorkEventArgs e) { int begintick = System.Environment.TickCount; var arg = e.Argument as Tuple<CpWorker, string, string, string, string>; CpWorker cpworker = arg.Item1; string uid = arg.Item2; string pwd = arg.Item3; string newpwd = arg.Item4; string result = arg.Item5; string nowpwd = pwd; if (result == "成功") { nowpwd = newpwd; m_uidbacker.PushUid(uid, nowpwd, pwd, "cp"); } lock (m_saveObjList) { m_saveObjList.Add(new Tuple<string, string, string>(uid, nowpwd, result)); } //m_logger.Debug("add update:" + (System.Environment.TickCount - begintick) + "ms"); e.Result = new Tuple<CpWorker, string, string, string>(cpworker, uid, nowpwd, result); } void SaveUidPwdStatus() { while (true) { if (m_boshutdwon) { lock (m_saveObjList) { lock (m_saveSeObjList) { if (m_saveObjList.Count == 0 && m_saveSeObjList.Count == 0) { return; } } } } do { List<object> pwcwaitsavelist = new List<object>(); lock (m_saveObjList) { if (m_saveObjList.Count > 0) { pwcwaitsavelist = new List<object>(m_saveObjList); m_saveObjList.Clear(); } } if (pwcwaitsavelist.Count > 0) { int begintick = System.Environment.TickCount; using (SQLiteTransaction ts = m_pwcconn.BeginTransaction()) { for (int i = 0; i < pwcwaitsavelist.Count; ++i) { var tuple = pwcwaitsavelist[i] as Tuple<string, string, string>; string uid = tuple.Item1; string pwd = tuple.Item2; string status = tuple.Item3; using (SQLiteCommand cmd = new SQLiteCommand(m_pwcconn)) { cmd.CommandText = "UPDATE " + pwcuidtable + " SET " + column_status + " = @status , " + column_password + " = @pwd" + " WHERE " + column_uid + " = @uid "; cmd.Parameters.Add(new SQLiteParameter("@status", status)); cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd.Parameters.Add(new SQLiteParameter("@pwd", pwd)); cmd.ExecuteNonQuery(); } } ts.Commit(); } m_logger.Debug("update pwc count:" + pwcwaitsavelist.Count + " time:" + (System.Environment.TickCount - begintick) + "ms"); } } while (false); do { List<object> csewaitsavelist = new List<object>(); lock (m_saveSeObjList) { if (m_saveSeObjList.Count > 0) { csewaitsavelist = new List<object>(m_saveSeObjList); m_saveSeObjList.Clear(); } } if (csewaitsavelist.Count > 0) { int begintick = System.Environment.TickCount; using (SQLiteTransaction ts = m_cseconn.BeginTransaction()) { for (int i = 0; i < csewaitsavelist.Count; ++i) { var tuple = csewaitsavelist[i] as Tuple<SeWorker, string, string, string, int, int, int>; SeWorker seworker = tuple.Item1; string uid = tuple.Item2; string pwd = tuple.Item3; string status = tuple.Item4; int has_idcard = tuple.Item5; int yue = tuple.Item6; int safepoint = tuple.Item7; if (status == "查询成功") { using (SQLiteCommand cmd = new SQLiteCommand(m_cseconn)) { cmd.CommandText = "UPDATE " + cse_uidtable + " SET " + cse_column_status + " = @status , " + cse_column_password + " = @pwd ," + cse_column_se_idcard + " = @idcard, " + cse_column_se_safepoint + " = @safepoint," + cse_column_se_balance + " =@balance " + " WHERE " + column_uid + " = @uid "; cmd.Parameters.Add(new SQLiteParameter("@status", status)); cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd.Parameters.Add(new SQLiteParameter("@pwd", pwd)); cmd.Parameters.Add(new SQLiteParameter("@idcard", queryResult[has_idcard])); cmd.Parameters.Add(new SQLiteParameter("@safepoint", safepoint)); cmd.Parameters.Add(new SQLiteParameter("@balance", yue)); cmd.ExecuteNonQuery(); } } else { using (SQLiteCommand cmd = new SQLiteCommand(m_cseconn)) { cmd.CommandText = "UPDATE " + cse_uidtable + " SET " + cse_column_status + " = @status " + " WHERE " + column_uid + " = @uid "; cmd.Parameters.Add(new SQLiteParameter("@status", status)); cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd.ExecuteNonQuery(); } } } ts.Commit(); } m_logger.Debug("update cse count:" + csewaitsavelist.Count + " time:" + (System.Environment.TickCount - begintick) + "ms"); } } while (false); do { List<object> guesswaitsavelist = new List<object>(); lock (m_saveGuessObjList) { if (m_saveGuessObjList.Count > 0) { guesswaitsavelist = new List<object>(m_saveGuessObjList); m_saveGuessObjList.Clear(); } } try { if (guesswaitsavelist.Count > 0) { using (SQLiteTransaction ts = m_guessconn.BeginTransaction()) { for (int i = 0; i < guesswaitsavelist.Count; ++i) { var tuple = guesswaitsavelist[i] as Tuple<GuessWorker, string, string, string, int, int, int>; //GuessWorker seworker = tuple.Item1; string uid = tuple.Item2; string pwd = tuple.Item3; string status = tuple.Item4; int has_idcard = tuple.Item5; int yue = tuple.Item6; int userpoint = tuple.Item7; //if (status == "查询成功") { using (SQLiteCommand cmd = new SQLiteCommand(m_guessconn)) { cmd.CommandText = "select * from " + guess_uidtable + " where uid=@uid"; cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); SQLiteDataReader reader = cmd.ExecuteReader(); if (!reader.HasRows) { using (SQLiteCommand cmd1 = new SQLiteCommand(m_guessconn)) { cmd1.CommandText = "INSERT INTO " + guess_uidtable + " (uid,password,status,idcard,jifen,balance) VALUES(@uid,@pwd,@status,@idcard,@userpoint,@balance)"; cmd1.Parameters.Add(new SQLiteParameter("@status", status)); cmd1.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd1.Parameters.Add(new SQLiteParameter("@pwd", pwd)); cmd1.Parameters.Add(new SQLiteParameter("@idcard", queryResult[has_idcard])); cmd1.Parameters.Add(new SQLiteParameter("@userpoint", userpoint)); cmd1.Parameters.Add(new SQLiteParameter("@balance", yue)); cmd1.ExecuteNonQuery(); } } } } } ts.Commit(); } } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } } while (false); do { List<object> cardwaitsavelist = new List<object>(); lock (m_saveCardObjList) { if (m_saveCardObjList.Count > 0) { cardwaitsavelist = new List<object>(m_saveCardObjList); m_saveObjList.Clear(); } } if (cardwaitsavelist.Count > 0) { int begintick = System.Environment.TickCount; using (SQLiteTransaction ts = m_cardconn.BeginTransaction()) { for (int i = 0; i < cardwaitsavelist.Count; ++i) { var tuple = cardwaitsavelist[i] as Tuple<CardWorker, string, string, string, string, string>; string uid = tuple.Item2; string pwd = tuple.Item3; string status = tuple.Item4; string cardid = tuple.Item5; string cardname = tuple.Item6; using (SQLiteCommand cmd = new SQLiteCommand(m_cardconn)) { cmd.CommandText = "UPDATE " + card_uidtable + " SET " + card_column_status + " = @status , " + card_column_password + " = @pwd, " + card_column_cardname + " = @name, " + card_column_cardid + " = @carid" + " WHERE " + column_uid + " = @uid "; cmd.Parameters.Add(new SQLiteParameter("@status", status)); cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd.Parameters.Add(new SQLiteParameter("@pwd", pwd)); cmd.Parameters.Add(new SQLiteParameter("@name", cardname)); cmd.Parameters.Add(new SQLiteParameter("@carid", cardid)); cmd.ExecuteNonQuery(); } } ts.Commit(); } m_logger.Debug("update pwc count:" + cardwaitsavelist.Count + " time:" + (System.Environment.TickCount - begintick) + "ms"); } } while (false); do { List<object> regwaitsavelist = new List<object>(); lock(m_saveRegObjList) { if (m_saveRegObjList.Count > 0) { for (int i = 0; i < m_saveRegObjList.Count; ++i) { regwaitsavelist.Add(m_saveRegObjList[i]); } m_saveRegObjList.Clear(); } } if (regwaitsavelist.Count > 0) { int begintick = System.Environment.TickCount; using (SQLiteTransaction ts = m_regconn.BeginTransaction()) { for (int i = 0; i < regwaitsavelist.Count; ++i) { var tuple = regwaitsavelist[i] as Tuple<string, string, string, string, string>; string uid = tuple.Item1; string pwd = tuple.Item2; string status = tuple.Item3; string cardid = tuple.Item4; string cardname = tuple.Item5; using (SQLiteCommand cmd = new SQLiteCommand(m_regconn)) { cmd.CommandText = "UPDATE reg_uid SET password=@pwd,status=@status,cardname=@name,cardid=@carid where uid=@uid"; cmd.Parameters.Add(new SQLiteParameter("@status", status)); cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd.Parameters.Add(new SQLiteParameter("@pwd", pwd)); cmd.Parameters.Add(new SQLiteParameter("@name", cardname)); cmd.Parameters.Add(new SQLiteParameter("@carid", cardid)); int effectrows = cmd.ExecuteNonQuery(); if (effectrows == 0) { cmd.CommandText = "INSERT INTO reg_uid (uid,password,status,cardname,cardid) VALUES(@uid,@pwd,@status,@name,@carid)"; cmd.Parameters.Add(new SQLiteParameter("@status", status)); cmd.Parameters.Add(new SQLiteParameter("@uid", uid)); cmd.Parameters.Add(new SQLiteParameter("@pwd", pwd)); cmd.Parameters.Add(new SQLiteParameter("@name", cardname)); cmd.Parameters.Add(new SQLiteParameter("@carid", cardid)); cmd.ExecuteNonQuery(); } } } ts.Commit(); } m_logger.Debug("update reg count:" + regwaitsavelist.Count + " time:" + (System.Environment.TickCount - begintick) + "ms"); } } while (false); Thread.Sleep(1000); } } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var arg = e.Result as Tuple<CpWorker, string, string, string>; CpWorker cpwoker = arg.Item1; string uid = arg.Item2; string pwd = arg.Item3; string result = arg.Item4; Dispatcher.BeginInvoke(new Action(() => { if (cbSpecial.IsChecked == false) { DataRow targetrow = m_pwcdataset.Tables[0].Rows[m_uid2idx[uid]]; targetrow[column_password] = pwd; targetrow[column_status] = result; if (result == "IP被封") { if (cpwoker.IpToken == m_IpToken) { if (File.Exists("RebootRoutine.exe")) { m_logger.Debug("启动RebootRoutine.exe..."); Process pro = Process.Start("RebootRoutine.exe"); pro.WaitForExit(); m_logger.Debug("RebootRoutine 退出!!"); } m_IpToken++; } } } try { if (CpWorker.KeepRunTime != 0 && btnStop.IsEnabled) { if (System.Environment.TickCount - CpWorker.StartRunTime > CpWorker.KeepRunTime) { btnStop.IsEnabled = false; MessageBox.Show("试用时间到了!!"); } } if (btnStop.IsEnabled == true) { if (cbSpecial.IsChecked == true) { string nextuid = "youxi0087"; string nextpwd = "youxi0087"; string nextnewpwd = "youxi0087"; if (cbSpecial.IsChecked == true) { cpwoker.CaptureMod = true; } cpwoker.BeginTaskChangePwd(nextuid.ToLower().Trim(), nextpwd.Trim(), nextnewpwd, m_IpToken); } else { DataRow nextuidrow = IteratorNextRow(m_pwcdataset.Tables[0], column_status, ref m_walkiterator); if (nextuidrow != null) { string nextuid = (string)nextuidrow[column_uid]; string nextpwd = (string)nextuidrow[column_password]; string nextnewpwd = this.GetNewPassword(); cpwoker.BeginTaskChangePwd(nextuid.ToLower().Trim(), nextpwd.Trim(), nextnewpwd, m_IpToken); nextuidrow[column_status] = status_ready; } else { cpwoker.IsWorking = false; CheckCpWorkerStatus(); } } } else { cpwoker.IsWorking = false; CheckCpWorkerStatus(); } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } })); } void CheckCpWorkerStatus() { foreach (CpWorker w in m_cpworkers) { if (w.IsWorking == true) { return; } } btnStart.IsEnabled = true; btnStop.IsEnabled = true; tbxWorkerNumber.IsEnabled = true; RandomPwdTextbox.IsEnabled = true; FixPwdTextbox.IsEnabled = true; tbxPwdNum.IsEnabled = true; } void load_captcha_xml(string xmlfile,Dictionary<string, string> dic) { XmlDocument doc = new XmlDocument(); doc.Load(xmlfile); XmlNode root = doc.SelectSingleNode("Data"); for (XmlNode item = root.FirstChild; item != null; item = item.NextSibling) { if (item.Attributes["name"] != null && item.Attributes["value"] != null) { dic.Add(item.Attributes["name"].Value, item.Attributes["value"].Value); } } } void load_captcha_from_safetxt(string safe_str, string key, Dictionary<string, string> dic) { if (!String.IsNullOrEmpty(safe_str)) { string src_txt = MyDes.Decode(safe_str, key); string[] split = src_txt.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (split.Length > 0) { foreach (string s in split) { string pattern = @"(\w+)=(\w+)"; Match mt = Regex.Match(s, pattern); if (mt.Groups.Count == 3) { dic.Add(mt.Groups[1].ToString(), mt.Groups[2].ToString()); } } } } } void save_captcha_db_from_dic(Dictionary<string, string> dic,string dbpwd,string tablename) { if (!File.Exists(captchadb)) { System.Data.SQLite.SQLiteConnection.CreateFile(captchadb); } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = captchadb; SQLiteConnection captcha_dbconn = new SQLiteConnection(); captcha_dbconn.ConnectionString = connstr.ToString(); captcha_dbconn.SetPassword(dbpwd); captcha_dbconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(captcha_dbconn)) { cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = '" + tablename + "'"; Int64 result = (Int64)cmd.ExecuteScalar(); if (result == 0) { cmd.CommandText = "CREATE TABLE " + tablename + "(name varchar(50) primary key,value varchar(20))"; cmd.ExecuteNonQuery(); } } using (SQLiteTransaction ts = captcha_dbconn.BeginTransaction()) { using (SQLiteCommand cmd = new SQLiteCommand(captcha_dbconn)) { foreach (string name in dic.Keys) { string value = dic[name]; cmd.CommandText = "INSERT INTO " + tablename + " (name , value) VALUES(@name,@value)"; cmd.Parameters.Clear(); cmd.Parameters.Add(new SQLiteParameter("@name", name)); cmd.Parameters.Add(new SQLiteParameter("@value", value)); cmd.ExecuteNonQuery(); } } ts.Commit(); } captcha_dbconn.Close(); } void load_captcha_from_db(Dictionary<string, string> dic,string dbpwd,string tablename) { if (!File.Exists(captchadb)) { return; } SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder(); connstr.DataSource = captchadb; SQLiteConnection captcha_dbconn = new SQLiteConnection(); captcha_dbconn.ConnectionString = connstr.ToString(); captcha_dbconn.SetPassword(dbpwd); captcha_dbconn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(captcha_dbconn)) { cmd.CommandText = "SELECT name,value FROM " + tablename; cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); DataSet tmpdataset = new DataSet(); da.Fill(tmpdataset); if (tmpdataset.Tables[0].Rows.Count > 0) { dic.Clear(); foreach (DataRow row in tmpdataset.Tables[0].Rows) { dic.Add(row["name"].ToString(), row["value"].ToString()); } } } captcha_dbconn.Close(); } void load_uidtxt(string uidtxt) { try { if (File.Exists(uidtxt)) { using (SQLiteCommand cmd = new SQLiteCommand(m_pwcconn)) { m_uid2idx.Clear(); m_pwcdataset.Tables[0].Clear(); cmd.CommandText = "DELETE FROM " + pwcuidtable; cmd.ExecuteNonQuery(); string[] lines = File.ReadAllLines(uidtxt, Encoding.GetEncoding("GB2312")); string pattern = @"[0-9]*[^a-zA-z0-9]*(\w+)[^a-zA-z0-9]*(\w+)"; foreach (string line in lines) { Match mt = Regex.Match(line, pattern); if (mt.Groups.Count == 3) { string uid = mt.Groups[1].ToString(); string pw = mt.Groups[2].ToString(); DataRow newRow = m_pwcdataset.Tables[0].Rows.Add(); newRow[column_uid] = uid; newRow[column_password] = pw; if (m_uid2idx.ContainsKey(uid.ToLower())) { m_uid2idx.Clear(); m_pwcdataset.Tables[0].Clear(); MessageBox.Show("导入的数据中包含了相同的账号:" + uid,"Warming",MessageBoxButton.OK,MessageBoxImage.Warning); } m_uid2idx.Add(uid.ToLower(), m_pwcdataset.Tables[0].Rows.IndexOf(newRow)); } } int begintick = System.Environment.TickCount; cmd.CommandText = "SELECT * FROM " + pwcuidtable; SQLiteDataAdapter dataadapter = new SQLiteDataAdapter(cmd); SQLiteCommandBuilder cmdbuilder = new SQLiteCommandBuilder(dataadapter); dataadapter.InsertCommand = cmdbuilder.GetInsertCommand(); using (SQLiteTransaction ts = m_pwcconn.BeginTransaction()) { dataadapter.Update(m_pwcdataset); ts.Commit(); } m_logger.Debug("数据库更新:" + (System.Environment.TickCount - begintick) + "ms"); } m_walkiterator = 0; } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } finally { } } void load_cseuidtxt(string uidtxt) { try { if (File.Exists(uidtxt)) { using (SQLiteCommand cmd = new SQLiteCommand(m_cseconn)) { m_csedataset.Tables[0].Clear(); cmd.CommandText = "DELETE FROM " + cse_uidtable; cmd.ExecuteNonQuery(); string[] lines = File.ReadAllLines(uidtxt, Encoding.GetEncoding("GB2312")); string pattern = @"[0-9]*[^a-zA-z0-9]*(\w+)[^a-zA-z0-9]*(\w+)"; foreach (string line in lines) { Match mt = Regex.Match(line, pattern); if (mt.Groups.Count == 3) { string uid = mt.Groups[1].ToString(); string pw = mt.Groups[2].ToString(); DataRow newRow = m_csedataset.Tables[0].Rows.Add(); newRow[cse_column_uid] = uid; newRow[cse_column_password] = pw; } } int begintick = System.Environment.TickCount; cmd.CommandText = "SELECT * FROM " + cse_uidtable; SQLiteDataAdapter dataadapter = new SQLiteDataAdapter(cmd); SQLiteCommandBuilder cmdbuilder = new SQLiteCommandBuilder(dataadapter); dataadapter.InsertCommand = cmdbuilder.GetInsertCommand(); using (SQLiteTransaction ts = m_cseconn.BeginTransaction()) { dataadapter.Update(m_csedataset); ts.Commit(); } m_logger.Debug("cse数据库更新:" + (System.Environment.TickCount - begintick) + "ms"); } m_csewalkiterator = 0; } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } finally { } } void load_carduidtxt(string uidtxt) { if (File.Exists(uidtxt)) { using (SQLiteCommand cmd = new SQLiteCommand(m_cardconn)) { m_carddataset.Tables[0].Clear(); cmd.CommandText = "DELETE FROM " + card_uidtable; cmd.ExecuteNonQuery(); string[] lines = File.ReadAllLines(uidtxt, Encoding.GetEncoding("GB2312")); string pattern = @"[0-9]*[^a-zA-z0-9]*(\w+)[^a-zA-z0-9]*(\w+)"; foreach (string line in lines) { Match mt = Regex.Match(line, pattern); if (mt.Groups.Count == 3) { string uid = mt.Groups[1].ToString(); string pw = mt.Groups[2].ToString(); DataRow newRow = m_carddataset.Tables[0].Rows.Add(); newRow[card_column_uid] = uid; newRow[card_column_password] = pw; } } int begintick = System.Environment.TickCount; cmd.CommandText = "SELECT * FROM " + card_uidtable; SQLiteDataAdapter dataadapter = new SQLiteDataAdapter(cmd); SQLiteCommandBuilder cmdbuilder = new SQLiteCommandBuilder(dataadapter); dataadapter.InsertCommand = cmdbuilder.GetInsertCommand(); using (SQLiteTransaction ts = m_cardconn.BeginTransaction()) { dataadapter.Update(m_carddataset); ts.Commit(); } m_logger.Debug("card数据库更新:" + (System.Environment.TickCount - begintick) + "ms"); } m_cardwalkiterator = 0; } } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { try { m_boshutdwon = true; m_uidbacker.BackUp(); Thread.Sleep(3000); m_pwcconn.Close(); CLogger.StopAllLoggers(); m_saveThread.Join(3000); } catch (System.Exception) { } base.OnClosing(e); } private void button2_Click(object sender, RoutedEventArgs e) { try { btnStop.IsEnabled = false; CheckCpWorkerStatus(); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } } private void statusGrid_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.Link; //WinForm中为e.Effect = DragDropEffects.Link else e.Effects = DragDropEffects.None; } private void statusGrid_Drop(object sender, DragEventArgs e) { string fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); load_uidtxt(fileName); } public void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = e.Row.GetIndex() + 1; } private void btnExportCpResult_Click(object sender, RoutedEventArgs e) { if (cbSpecial.IsChecked == true) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "保存类型 |*.xml"; dlg.FilterIndex = 1; if (dlg.ShowDialog() == true) { if (Directory.Exists("cap")) { string[] files = Directory.GetFiles("cap"); XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null); XmlElement root = doc.CreateElement("Data"); doc.AppendChild(root); foreach (string file in files) { Match mt = Regex.Match(file, "(\\w+)----([0-9]+).bmp"); if (mt.Groups.Count == 3) { XmlElement item = doc.CreateElement("captcha"); item.SetAttribute("name", mt.Groups[1].ToString()); item.SetAttribute("value", mt.Groups[2].ToString()); root.AppendChild(item); } } doc.Save(dlg.FileName); } } } else { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "保存类型 |*.txt"; dlg.FilterIndex = 1; if (dlg.ShowDialog() == true) { using (FileStream fs = new FileStream(dlg.FileName, FileMode.Create)) { using (StreamWriter writer = new StreamWriter(fs)) { for (int i = 0; i < m_pwcdataset.Tables[0].Rows.Count; ++i) { string uid = m_pwcdataset.Tables[0].Rows[i][column_uid].ToString(); string pwd = m_pwcdataset.Tables[0].Rows[i][column_password].ToString(); string status = m_pwcdataset.Tables[0].Rows[i][column_status].ToString(); writer.WriteLine(uid + "----" + pwd + "----" + status); } } } } } } private void Window_Loaded(object sender, RoutedEventArgs e) { cbSpecial.Visibility = Visibility.Hidden; if (File.Exists("sig")) { byte[] sig = File.ReadAllBytes("sig"); if (sig.Length > 0) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] strbytes = sig; byte[] md5_bytes = md5.ComputeHash(strbytes, 0, strbytes.Length); string md5_str = BitConverter.ToString(md5_bytes).Replace("-", ""); if (md5_str == "F47815543AB6B6278F857644B3AC0745") { cbSpecial.Visibility = Visibility.Visible; } } } UidGrid.DragEnter += new DragEventHandler(statusGrid_DragEnter); UidGrid.Drop += new DragEventHandler(statusGrid_Drop); CheckUidSafeGrid.DragEnter += new DragEventHandler(CheckUidSafeGrid_DragEnter); CheckUidSafeGrid.Drop += new DragEventHandler(CheckUidSafeGrid_Drop); CardUidGrid.DragEnter += new DragEventHandler(CardUidGrid_DragEnter); CardUidGrid.Drop += new DragEventHandler(CardUidGrid_Drop); int workerThreads = 0; int completePortsThreads = 0; ThreadPool.GetMaxThreads(out workerThreads, out completePortsThreads); ThreadPool.SetMaxThreads(workerThreads*10, completePortsThreads*10); if (m_userlvl < 0) { tabItem1.Visibility = Visibility.Collapsed; tabItem2.Visibility = Visibility.Collapsed; tabItem3.Visibility = Visibility.Collapsed; tabItem5.IsSelected = true; } if (m_userlvl == 0) { tabItem3.Visibility = Visibility.Collapsed; } } void CardUidGrid_Drop(object sender, DragEventArgs e) { string fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); load_carduidtxt(fileName); } void CardUidGrid_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.Link; else e.Effects = DragDropEffects.None; } void CheckUidSafeGrid_Drop(object sender, DragEventArgs e) { string fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); load_cseuidtxt(fileName); } void CheckUidSafeGrid_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.Link; else e.Effects = DragDropEffects.None; } void firstStart() { CpWorker.DBpwd = MyDes.Decode(m_safedbpwd, m_safekey); SeWorker.DBpwd = CpWorker.DBpwd; GuessWorker.DBpwd = CpWorker.DBpwd; CardWorker.DBpwd = CpWorker.DBpwd; if (!String.IsNullOrEmpty(m_safelg) && !String.IsNullOrEmpty(m_safepw)) { load_captcha_from_safetxt(m_safelg, m_constkey, m_lgcaptcha); load_captcha_from_safetxt(m_safepw, m_constkey, m_pwcaptcha); save_captcha_db_from_dic(m_lgcaptcha, CpWorker.DBpwd, "lg"); save_captcha_db_from_dic(m_pwcaptcha, CpWorker.DBpwd, "pwc"); } else { load_captcha_from_db(m_lgcaptcha, CpWorker.DBpwd, "lg"); load_captcha_from_db(m_pwcaptcha, CpWorker.DBpwd, "pwc"); } CpWorker.StartRunTime = System.Environment.TickCount; SeWorker.StartRunTime = CpWorker.StartRunTime; GuessWorker.StartRunTime = CpWorker.StartRunTime; } private void btnStartCheckSafe_Click(object sender, RoutedEventArgs e) { if (!File.Exists(md5js)) { MessageBox.Show(lgxml + "文件不存在", "", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (m_bofirststart) { firstStart(); m_bofirststart = false; } if (SeWorker.KeepRunTime != 0) { if (System.Environment.TickCount - SeWorker.StartRunTime > SeWorker.KeepRunTime) { if (File.Exists(captchadb)) { File.Delete(captchadb); } m_lgcaptcha.Clear(); m_pwcaptcha.Clear(); for (int i = 0; i < m_cpworkers.Count; ++i) { m_seworkers[i].m_lgcaptcha.Clear(); m_seworkers[i].m_pwcaptcha.Clear(); } MessageBox.Show("试用到期了!!"); return; } } int num = int.Parse(tbxSeWorkerNumber.Text); for (int i = 0; i < num; ++i) { if (m_seworkers.Count <= i) { SeWorker worker = new SeWorker(m_lgcaptcha, m_pwcaptcha, m_safekey); if (m_userlvl >= 2) { worker.QuerySafePoint = true; } worker.FinishTask += new Action<SeWorker, string, string, string, int, int, int>(seworker_FinishTask); m_seworkers.Add(worker); } DataRow nextuidrow = IteratorNextRow(m_csedataset.Tables[0], cse_column_status, ref m_csewalkiterator); if (nextuidrow != null) { string uid = (string)nextuidrow[cse_column_uid]; string pwd = (string)nextuidrow[cse_column_password]; m_seworkers[i].BeginTask(uid.ToLower().Trim(), pwd.Trim(), nextuidrow, m_IpToken); nextuidrow[cse_column_status] = status_ready; //m_logger.Debug("begin uid:" + uid + " pwd:" + pwd + " newpwd:" + newpwd); } else { m_seworkers[i].IsWorking = false; } } btnStartCheckSafe.IsEnabled = false; tbxSeWorkerNumber.IsEnabled = false; CheckSeWorkerStatus(); } void seworker_FinishTask(SeWorker seworker, string uid, string pwd, string status, int has_idcard, int yue, int safepoint) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(seworker_OnTaskFinish); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(seworker_RunWorkerCompleted); worker.RunWorkerAsync(new Tuple<SeWorker, string, string, string, int, int, int>(seworker, uid, pwd, status, has_idcard, yue, safepoint)); } void seworker_OnTaskFinish(object sender, DoWorkEventArgs e) { try { lock (m_saveSeObjList) { m_saveSeObjList.Add(e.Argument); } e.Result = e.Argument; } catch (System.Exception ex) { m_logger.Error(ex.ToString()); } } void seworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var arg = e.Result as Tuple<SeWorker, string, string, string, int, int, int>; SeWorker seworker = arg.Item1; string uid = arg.Item2; string pwd = arg.Item3; string status = arg.Item4; int has_idcard = arg.Item5; int yue = arg.Item6; int safepoint = arg.Item7; Dispatcher.BeginInvoke(new Action(() => { if (status == "IP被封") { if (seworker.IpToken == m_IpToken) { m_logger.Debug("启动RebootRoutine.exe..."); if (File.Exists("RebootRoutine.exe")) { Process pro = Process.Start("RebootRoutine.exe"); pro.WaitForExit(); } m_logger.Debug("RebootRoutine 退出!!"); m_IpToken++; } } DataRow targetrow = seworker.workArgument as DataRow; targetrow[cse_column_status] = status; if (status == "查询成功") { targetrow[cse_column_se_idcard] = queryResult[has_idcard]; targetrow[cse_column_se_safepoint] = safepoint; targetrow[cse_column_se_balance] = yue; m_uidbacker.PushUid(uid, pwd, pwd, "se"); } try { if (SeWorker.KeepRunTime != 0 && btnStartCheckSafe.IsEnabled) { if (System.Environment.TickCount - SeWorker.StartRunTime > SeWorker.KeepRunTime) { btnStop.IsEnabled = false; MessageBox.Show("试用时间到了!!"); } } if (btnStopCheckSafe.IsEnabled == true) { DataRow nextuidrow = IteratorNextRow(m_csedataset.Tables[0], cse_column_status, ref m_csewalkiterator); if (nextuidrow != null) { string nextuid = (string)nextuidrow[cse_column_uid]; string nextpwd = (string)nextuidrow[cse_column_password]; seworker.BeginTask(nextuid.ToLower().Trim(), nextpwd.Trim(), nextuidrow, m_IpToken); nextuidrow[cse_column_status] = status_ready; } else { seworker.IsWorking = false; CheckSeWorkerStatus(); } } else { seworker.IsWorking = false; CheckSeWorkerStatus(); } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } })); } void CheckSeWorkerStatus() { foreach (SeWorker w in m_seworkers) { if (w.IsWorking == true) { return; } } btnStartCheckSafe.IsEnabled = true; btnStopCheckSafe.IsEnabled = true; tbxSeWorkerNumber.IsEnabled = true; } private void btnStopCheckSafe_Click(object sender, RoutedEventArgs e) { try { btnStopCheckSafe.IsEnabled = false; CheckSeWorkerStatus(); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnExportCheckSafe_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "保存类型 |*.txt"; dlg.FilterIndex = 1; if (dlg.ShowDialog() == true) { using (FileStream fs = new FileStream(dlg.FileName, FileMode.Create)) { using (StreamWriter writer = new StreamWriter(fs)) { for (int i = 0; i < m_csedataset.Tables[0].Rows.Count; ++i) { string uid = m_csedataset.Tables[0].Rows[i][cse_column_uid].ToString(); string pwd = m_csedataset.Tables[0].Rows[i][cse_column_password].ToString(); string status = m_csedataset.Tables[0].Rows[i][cse_column_status].ToString(); string idcard = m_csedataset.Tables[0].Rows[i][cse_column_se_idcard].ToString(); string safepoint = m_csedataset.Tables[0].Rows[i][cse_column_se_safepoint].ToString(); string yue = m_csedataset.Tables[0].Rows[i][cse_column_se_balance].ToString(); writer.WriteLine(uid + "----" + pwd + "----" + status + "----" + idcard + "----" + safepoint + "----" + yue); } } } } } string GuessNextAccount(int saohaoset) { if (cbEnableLua.IsChecked == true) { } else { return m_GuessAccountPrefix + string.Format("{0:D" + m_numberOfDigit + "}", m_GuessBeginValue++); } return ""; } void GuessNextAccount1(ref string account, ref string password) { account = ""; password = ""; if (cbEnableLua.IsChecked == true) { m_jsVM.Run("getNewAccount()"); account = (string)m_jsVM.GetParameter("Account"); password = (string)m_jsVM.GetParameter("Password"); } else { account = m_GuessAccountPrefix + string.Format("{0:D" + m_numberOfDigit + "}", m_GuessBeginValue++); if (rdbNumberSame.IsChecked == true) { password = account.Substring(account.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' })); } else if (rdbFixpwd.IsChecked == true) { password = tbxFixpwd.Text; } else { password = account; } } } private void btnStartSaohao_Click(object sender, RoutedEventArgs e) { if (m_bofirststart) { firstStart(); m_bofirststart = false; } if (GuessWorker.KeepRunTime != 0) { if (System.Environment.TickCount - GuessWorker.StartRunTime > GuessWorker.KeepRunTime) { if (File.Exists(captchadb)) { File.Delete(captchadb); } m_lgcaptcha.Clear(); m_pwcaptcha.Clear(); for (int i = 0; i < m_cpworkers.Count; ++i) { m_guessWorkers[i].m_lgcaptcha.Clear(); m_guessWorkers[i].m_pwcaptcha.Clear(); } MessageBox.Show("试用到期了!!"); return; } } if (String.IsNullOrEmpty(tbxPrefixAccount.Text) || String.IsNullOrEmpty(tbxBeginValue.Text)) { MessageBox.Show("请先填写账号前缀,起始值!", "提示", MessageBoxButton.OK , MessageBoxImage.Information); return; } Regex re = new Regex("[a-z0-9]+"); if (!re.IsMatch(tbxPrefixAccount.Text) || !re.IsMatch(tbxBeginValue.Text)) { MessageBox.Show("账号前缀或者起始值格式错误!", "提示", MessageBoxButton.OK , MessageBoxImage.Information); return; } m_GuessSet = 10; m_GuessBeginValue = Convert.ToInt32(tbxBeginValue.Text); m_GuessAccountPrefix = tbxPrefixAccount.Text; m_numberOfDigit = tbxBeginValue.Text.Length; try { int numOfWorkers = Convert.ToInt32(tbxGuessWorkerNum.Text); if (numOfWorkers > m_maxGuessWorker) { tbxGuessWorkerNum.Text = m_maxGuessWorker.ToString(); numOfWorkers = m_maxGuessWorker; } for (int i = 0; i < numOfWorkers; ++i) { if (numOfWorkers >= m_guessWorkers.Count) { GuessWorker worker = new GuessWorker(m_lgcaptcha, m_pwcaptcha, m_safekey); worker.FinishTask += new Action<GuessWorker, string, string, string, int, int, int>(guessworker_FinishTask); m_guessWorkers.Add(worker); } string newAccount = ""; string newPassword = ""; GuessNextAccount1(ref newAccount, ref newPassword); m_guessWorkers[i].BeginTask(newAccount.ToLower().Trim(), newPassword, null, m_IpToken); //string nextguess = GuessNextAccount(m_GuessSet); ////m_guessWorkers[i].BeginTask(nextguess.Trim(), nextguess.Trim(), null, m_IpToken); //if (rdbNumberSame.IsChecked == true) //{ // string nextpwd = nextguess.Substring(nextguess.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' })); // m_guessWorkers[i].BeginTask(nextguess.ToLower().Trim(), nextpwd, null, m_IpToken); //} //else if (rdbFixpwd.IsChecked == true) //{ // m_guessWorkers[i].BeginTask(nextguess.ToLower().Trim(), tbxFixpwd.Text, null, m_IpToken); //} //else //{ // m_guessWorkers[i].BeginTask(nextguess.ToLower().Trim(), nextguess.Trim(), null, m_IpToken); //} } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } btnStartSaohao.IsEnabled = false; tbxPrefixAccount.IsEnabled = false; tbxBeginValue.IsEnabled = false; tbxGuessWorkerNum.IsEnabled = false; CheckGuessWorkerStatus(); } void guessworker_FinishTask(GuessWorker seworker, string uid, string pwd, string status, int has_idcard, int yue, int userpoint) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(guessworker_OnTaskFinish); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(guessworker_RunWorkerCompleted); worker.RunWorkerAsync(new Tuple<GuessWorker, string, string, string, int, int, int>(seworker, uid, pwd, status, has_idcard, yue, userpoint)); } void guessworker_OnTaskFinish(object sender, DoWorkEventArgs e) { try { e.Result = e.Argument; } catch (System.Exception ex) { m_logger.Error(ex.ToString()); } } void guessworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var arg = e.Result as Tuple<GuessWorker, string, string, string, int, int, int>; GuessWorker guessworker = arg.Item1; string uid = arg.Item2; string pwd = arg.Item3; string status = arg.Item4; int has_idcard = arg.Item5; int yue = arg.Item6; int userpoint = arg.Item7; Dispatcher.BeginInvoke(new Action(() => { if (status == "IP被封") { if (guessworker.IpToken == m_IpToken) { if (File.Exists("RebootRoutine.exe")) { m_logger.Debug("启动RebootRoutine.exe..."); Process pro = Process.Start("RebootRoutine.exe"); pro.WaitForExit(); m_logger.Debug("RebootRoutine 退出!!"); } m_IpToken++; } } if (status == "查询成功") { m_countOfGuessOk++; DataRow row = m_guessdataset.Tables[0].NewRow(); row[guess_column_uid] = uid; row[guess_column_password] = pwd; row[guess_column_status] = status; row[guess_column_se_idcard] = queryResult[has_idcard]; row[guess_column_se_jifen] = userpoint; row[guess_column_se_balance] = yue; m_guessdataset.Tables[0].Rows.Add(row); lock (m_saveGuessObjList) { m_saveGuessObjList.Add(arg); } m_uidbacker.PushUid(uid, pwd, "", "guess"); } m_countOfGuess++; tbStatus.Text = string.Format("{0} {1} | 累积成功:{2}/{3} | ", uid, status, m_countOfGuessOk, m_countOfGuess); tbxBeginValue.Text = string.Format("{0:D" + m_numberOfDigit + "}", m_GuessBeginValue); try { if (GuessWorker.KeepRunTime != 0 && btnStartCheckSafe.IsEnabled) { if (System.Environment.TickCount - GuessWorker.StartRunTime > GuessWorker.KeepRunTime) { btnStopSaohao.IsEnabled = false; MessageBox.Show("试用时间到了!!"); } } if (btnStopSaohao.IsEnabled == true) { string newAccount = ""; string newPassword = ""; GuessNextAccount1(ref newAccount, ref newPassword); if (!string.IsNullOrEmpty(newAccount)) { guessworker.BeginTask(newAccount.ToLower().Trim(), newPassword, null, m_IpToken); } else { guessworker.IsWorking = false; CheckGuessWorkerStatus(); } } else { guessworker.IsWorking = false; CheckGuessWorkerStatus(); } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } })); } void cardworker_FinishTask(CardWorker worker, string uid, string pwd, string status, string cardid, string cardname) { BackgroundWorker backworker = new BackgroundWorker(); backworker.DoWork += new DoWorkEventHandler(cardworker_OnTaskFinish); backworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(cardworker_RunWorkerCompleted); backworker.RunWorkerAsync(new Tuple<CardWorker, string, string, string, string, string>(worker, uid, pwd, status, cardid, cardname)); } void cardworker_OnTaskFinish(object sender, DoWorkEventArgs e) { e.Result = e.Argument; lock (m_saveCardObjList) { m_saveCardObjList.Add(e.Result); } } void cardworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var arg = e.Result as Tuple<CardWorker, string, string, string, string, string>; CardWorker cardworker = arg.Item1; string uid = arg.Item2; string pwd = arg.Item3; string status = arg.Item4; string cardid = arg.Item5; string cardname = arg.Item6; Dispatcher.BeginInvoke(new Action(() => { if (status == "IP被封") { if (cardworker.IpToken == m_IpToken) { if (File.Exists("RebootRoutine.exe")) { m_logger.Debug("启动RebootRoutine.exe..."); Process pro = Process.Start("RebootRoutine.exe"); pro.WaitForExit(); m_logger.Debug("RebootRoutine 退出!!"); } m_IpToken++; } } DataRow targetrow = cardworker.workArgument as DataRow; targetrow[cse_column_status] = status; targetrow[card_column_cardid] = cardid; targetrow[card_column_cardname] = cardname; if (status == "上证成功") { m_uidbacker.PushUid(uid, pwd, "", "card"); } try { if (CardWorker.KeepRunTime != 0 && btnStartCardSubmit.IsEnabled) { if (System.Environment.TickCount - GuessWorker.StartRunTime > CardWorker.KeepRunTime) { btnStopCardSubmit.IsEnabled = false; MessageBox.Show("试用时间到了!!"); } } if (btnStopCardSubmit.IsEnabled == true) { DataRow nextuidrow = IteratorNextRow(m_carddataset.Tables[0], card_column_status, ref m_cardwalkiterator); if (nextuidrow != null) { string nextuid = (string)nextuidrow[cse_column_uid]; string nextpwd = (string)nextuidrow[cse_column_password]; cardworker.BeginTask(nextuid.ToLower().Trim(), nextpwd.Trim(), nextuidrow, m_IpToken); nextuidrow[cse_column_status] = status_ready; } else { cardworker.IsWorking = false; CheckCardWorkerStatus(); } //string next = GuessNextAccount(m_GuessSet); //if (!string.IsNullOrEmpty(next)) //{ // cardworker.BeginTask(next.ToLower().Trim(), next.Trim(), null, m_IpToken); //} //else //{ // cardworker.IsWorking = false; // CheckCardWorkerStatus(); //} } else { cardworker.IsWorking = false; CheckCardWorkerStatus(); } } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } })); } void CheckCardWorkerStatus() { foreach (CardWorker w in m_cardwokers) { if (w.IsWorking == true) { return; } } btnStartCardSubmit.IsEnabled = true; btnStopCardSubmit.IsEnabled = true; tbxCardWorkerNum.IsEnabled = true; } void CheckGuessWorkerStatus() { foreach (GuessWorker w in m_guessWorkers) { if (w.IsWorking == true) { return; } } btnStartSaohao.IsEnabled = true; btnStopSaohao.IsEnabled = true; tbxPrefixAccount.IsEnabled = true; tbxBeginValue.IsEnabled = true; tbxGuessWorkerNum.IsEnabled = true; } void CheckRegWorkerStatus() { foreach (RegWorker w in m_regworkers) { if (w.IsWorking == true) { return; } } btnStartReg.IsEnabled = true; btnStopReg.IsEnabled = true; } private void btnStopSaohao_Click(object sender, RoutedEventArgs e) { btnStopSaohao.IsEnabled = false; CheckGuessWorkerStatus(); } private void btnExportSaohao_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Filter = "保存类型 |*.txt"; dlg.FilterIndex = 1; if (dlg.ShowDialog() == true) { using (FileStream fs = new FileStream(dlg.FileName, FileMode.Create)) { using (StreamWriter writer = new StreamWriter(fs)) { for (int i = 0; i < m_guessdataset.Tables[0].Rows.Count; ++i) { string uid = m_guessdataset.Tables[0].Rows[i][guess_column_uid].ToString(); string pwd = m_guessdataset.Tables[0].Rows[i][guess_column_password].ToString(); string status = m_guessdataset.Tables[0].Rows[i][guess_column_status].ToString(); string idcard = m_guessdataset.Tables[0].Rows[i][guess_column_se_idcard].ToString(); string jifen = m_guessdataset.Tables[0].Rows[i][guess_column_se_jifen].ToString(); string yue = m_guessdataset.Tables[0].Rows[i][guess_column_se_balance].ToString(); writer.WriteLine(uid + "----" + pwd + "----" + status + "----" + idcard + "----" + jifen + "----" + yue); } } } } } private void PreviewTextInput_NumberAndEnglish(object sender, TextCompositionEventArgs e) { Regex re = new Regex("[^\u4e00-\u9fa5a-z0-9.-]+"); e.Handled = re.IsMatch(e.Text); } private void PreviewTextInput_Number(object sender, TextCompositionEventArgs e) { Regex re = new Regex("[^\u4e00-\u9fa50-9.-]+"); e.Handled = re.IsMatch(e.Text); } private void btnCleanRecord_Click(object sender, RoutedEventArgs e) { m_guessdataset.Tables[0].Rows.Clear(); using (SQLiteCommand cmd = new SQLiteCommand(m_guessconn)) { cmd.CommandText = "DELETE FROM " + guess_uidtable; int effectOfCount = cmd.ExecuteNonQuery(); m_logger.Debug("clean {0} guess items!", effectOfCount); } } private void btnStartCardSubmit_Click(object sender, RoutedEventArgs e) { if (!File.Exists(md5js)) { MessageBox.Show(lgxml + "文件不存在", "", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (m_bofirststart) { firstStart(); m_bofirststart = false; } if (CardWorker.KeepRunTime != 0) { if (System.Environment.TickCount - CardWorker.StartRunTime > CardWorker.KeepRunTime) { if (File.Exists(captchadb)) { File.Delete(captchadb); } m_lgcaptcha.Clear(); m_pwcaptcha.Clear(); for (int i = 0; i < m_cpworkers.Count; ++i) { m_cardwokers[i].m_lgcaptcha.Clear(); m_cardwokers[i].m_pwcaptcha.Clear(); } MessageBox.Show("试用到期了!!"); return; } } int num = int.Parse(tbxCardWorkerNum.Text); for (int i = 0; i < num; ++i) { if (m_cardwokers.Count <= i) { CardWorker worker = new CardWorker(m_lgcaptcha, m_pwcaptcha, m_safekey); worker.FinishTask += cardworker_FinishTask; m_cardwokers.Add(worker); } DataRow nextuidrow = IteratorNextRow(m_carddataset.Tables[0], card_column_status, ref m_cardwalkiterator); if (nextuidrow != null) { string uid = (string)nextuidrow[cse_column_uid]; string pwd = (string)nextuidrow[cse_column_password]; m_cardwokers[i].BeginTask(uid.ToLower().Trim(), pwd.Trim(), nextuidrow, m_IpToken); nextuidrow[cse_column_status] = status_ready; //m_logger.Debug("begin uid:" + uid + " pwd:" + pwd + " newpwd:" + newpwd); } else { m_cardwokers[i].IsWorking = false; } } btnStartCardSubmit.IsEnabled = false; tbxCardWorkerNum.IsEnabled = false; CheckCardWorkerStatus(); } private void btnStopCardSubmit_Click(object sender, RoutedEventArgs e) { btnStopCardSubmit.IsEnabled = false; CheckCardWorkerStatus(); } private void btnStartReg_Click(object sender, RoutedEventArgs e) { if (m_bofirststart) { firstStart(); m_bofirststart = false; } if (!File.Exists(md5js)) { MessageBox.Show(md5js + "文件不存在", "", MessageBoxButton.OK, MessageBoxImage.Error); return; } int num = int.Parse(tbxRegWorkerNum1.Text); for (int i = 0; i < num; ++i) { if (m_regworkers.Count <= i) { RegWorker worker = new RegWorker(m_lgcaptcha, m_pwcaptcha); worker.FinishTask += RegWorker_FinishTask; m_regworkers.Add(worker); } m_regworkers[i].Start(tbxRegNamePrefix.Text + RandomString.Next(Convert.ToInt32(tbxRegNameLenSuffix.Text) , tbxRegNameSuffix.Text) , RandomString.Next(4, "a-z") + RandomString.Next(4, "0-9") , CardIdGenerator.NewId() , CardIdGenerator.NewName()); } btnStartReg.IsEnabled = false; CheckRegWorkerStatus(); } void RegWorker_FinishTask(RegWorker regwoker, Tuple<string,string,string,string,string> ret) { lock (m_saveRegObjList) { m_saveRegObjList.Add(ret); } Dispatcher.BeginInvoke(new Action(() => { DataRow row = m_regdataset.Tables[0].NewRow(); row[reg_column_uid] = ret.Item1; row[reg_column_password] = ret.Item2; row[reg_column_status] = ret.Item3; row[reg_column_cardid] = ret.Item4; row[reg_column_cardname] = ret.Item5; m_regdataset.Tables[0].Rows.Add(row); regwoker.IsWorking = false; if (btnStopReg.IsEnabled) { if (ret.Item3 == "Error:1040" || ret.Item3 == "") { if (regwoker.IpToken == m_IpToken) { if (File.Exists("RebootRoutine.exe")) { m_logger.Debug("启动RebootRoutine.exe..."); Process pro = Process.Start("RebootRoutine.exe"); pro.WaitForExit(); m_logger.Debug("RebootRoutine 退出!!"); } m_IpToken++; } } regwoker.IpToken = m_IpToken; regwoker.Start(tbxRegNamePrefix.Text + RandomString.Next(Convert.ToInt32(tbxRegNameLenSuffix.Text) , tbxRegNameSuffix.Text) , RandomString.Next(4, "a-z") + RandomString.Next(4, "0-9") , CardIdGenerator.NewId() , CardIdGenerator.NewName()); } else { CheckRegWorkerStatus(); } })); } private void btnStopReg_Click(object sender, RoutedEventArgs e) { btnStopReg.IsEnabled = false; } private void btnClearReg_Click(object sender, RoutedEventArgs e) { m_regdataset.Tables[0].Rows.Clear(); using (SQLiteCommand cmd = new SQLiteCommand(m_regconn)) { cmd.CommandText = "DELETE FROM " + reg_uidtable; cmd.ExecuteNonQuery(); } } private void Button_Click_PickJsPath(object sender, RoutedEventArgs e) { try { OpenFileDialog dlg = new OpenFileDialog(); dlg.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + "脚本\\"; dlg.Filter = "js|*.js"; dlg.ShowDialog(); tbxLuaPath.Text = dlg.FileName; m_jsVM.Run(File.ReadAllText(tbxLuaPath.Text)); m_jsModifyTime = File.GetLastWriteTime(tbxLuaPath.Text); } catch(JavascriptException ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch(Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } private void Button_Click_TestScript(object sender, RoutedEventArgs e) { try { if (m_jsModifyTime != File.GetLastWriteTime(tbxLuaPath.Text)) { m_jsVM.Run(File.ReadAllText(tbxLuaPath.Text)); m_jsModifyTime = File.GetLastWriteTime(tbxLuaPath.Text); } string account; string password; string tempFile = System.IO.Path.GetTempFileName(); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 10000; ++i) { m_jsVM.Run("getNewAccount()"); account = (string)m_jsVM.GetParameter("Account"); password = (string)m_jsVM.GetParameter("Password"); sb.Append(account + "----" + password + "\r\n"); } File.WriteAllText(tempFile, sb.ToString()); Process.Start("notepad", tempFile); //File.Delete(tempFile); } catch (JavascriptException ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } private void cbEnableLua_Checked(object sender, RoutedEventArgs e) { try { if (cbEnableLua.IsChecked == true) { if (m_jsModifyTime != File.GetLastWriteTime(tbxLuaPath.Text)) { m_jsVM.Run(File.ReadAllText(tbxLuaPath.Text)); m_jsModifyTime = File.GetLastWriteTime(tbxLuaPath.Text); } } } catch (JavascriptException ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch(Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; #nullable disable namespace HROADS_WebApi.Domains { public partial class Personagen { public Personagen() { Usuarios = new HashSet<Usuario>(); } public int IdPersonagem { get; set; } public int? IdClasse { get; set; } [Required(ErrorMessage = "O nome do personagem é obrigatorio!")] public string Nome { get; set; } [Required(ErrorMessage = "Informe a quantidade de Vida do seu personagem")] public int Vida { get; set; } [Required(ErrorMessage = "Informe a quantidade de Mana do seu personagem")] public int Mana { get; set; } [DataType(DataType.Date)] public DateTime DataDeAtualizacao { get; set; } [DataType(DataType.Date)] public DateTime DataDeCriacao { get; set; } public virtual Class IdClasseNavigation { get; set; } public virtual ICollection<Usuario> Usuarios { get; set; } } }
using Microsoft.AspNetCore.Identity; namespace ApiTemplate.Core.Entities.Users { public class AppUser :IdentityUser<long> { public string Name { get; set; } public string LastName { get; set; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; [RequireComponent(typeof(Image))] public class Pip : MonoBehaviour { public void Populate(Spell spell) { GetComponent<Image>().color = spell.pipColor; } }
using System; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.CompilerServices; namespace DanialProject.Models.Database { public class OpenDates { public DanialProject.Models.Database.Buildings Buildings { get; set; } [ForeignKey("Buildings")] public int? BuildingsID { get; set; } public DateTime Date { get; set; } public int ID { get; set; } public DateTime Time1 { get; set; } public DateTime Time2 { get; set; } public DateTime Time3 { get; set; } public OpenDates() { } } }
using ManageDomain; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ManageWeb.Controllers { [AllowAnonymous] public class ManagerController : ManageBaseController { // // GET: /Manager/ ManageDomain.BLL.ManagerBll managerbll = new ManageDomain.BLL.ManagerBll(); public ActionResult Index(int pno = 1, string keywords = "") { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Manager_Show); const int pagesize = 20; var model = managerbll.GetManagerPage(pno, pagesize, keywords); return View(model); } [HttpGet] public ActionResult Edit(int managerid = 0) { ViewBag.alltags = managerbll.GetAllManagerTag(); if (managerid > 0) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Manager_Show); var model = managerbll.GetManagerDetail(managerid); return View(model); } else { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Manager_Add); return View(); } } [HttpPost] public ActionResult Edit(ManageDomain.Models.Manager model, int[] tag, string AllowLogin = "") { try { ViewBag.alltags = managerbll.GetAllManagerTag(); if (model == null) { throw new Exception("无效参数!"); } model.AllowLogin = (AllowLogin ?? "").ToLower() == "on" ? 1 : 0; if (model.ManagerId > 0) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Manager_Update); managerbll.UpdateManager(model, tag); ManageDomain.PermissionProvider.RemoveManagerKeys(model.ManagerId); ViewBag.msg = "修改成功"; } else { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Manager_Add); model = managerbll.AddManager(model, tag); ViewBag.msg = "新增成功"; } model = managerbll.GetManagerDetail(model.ManagerId); return View(model); } catch (Exception ex) { ViewBag.msg = ex.Message; return View(model); } } public JsonResult ResetPwd(int managerid) { if (managerbll.ResetPwd(managerid)) { return Json(new JsonEntity() { code = 1, msg = "重置成功" }); } else { return Json(new JsonEntity() { code = 1, msg = "重置失败" }); } } public ActionResult Tag() { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.UserTag_Show); ViewBag.alltags = managerbll.GetAllManagerTag(); return View(); } public JsonResult AddUserTag(string tag, string remark) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.UserTag_Add); var result = managerbll.AddUserTag(tag, remark); return JsonE("添加成功!"); } public JsonResult DeleteUserTag(int usertagid) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.UseTag_Delete); var result = managerbll.DeleteUserTag(usertagid); return JsonE("删除成功!"); } public ActionResult TagPermission(int usertagid) { ManageDomain.BLL.PermissionBll pbll = new ManageDomain.BLL.PermissionBll(); var result = pbll.GetTagPermission(usertagid); ViewBag.tagpermissions = result; return PartialView(); } public JsonResult SaveTagPermission(int usertagid, string[] keys) { if (keys == null) keys = new string[0]; var newkeys = keys.Distinct().ToList(); ManageDomain.BLL.PermissionBll pbll = new ManageDomain.BLL.PermissionBll(); var result = pbll.SaveTagPermission(usertagid, newkeys); ManageDomain.PermissionProvider.ClearCache(); return JsonE("OK"); } [HttpPost] public JsonResult DeleteManager(int managerid) { //权限 ManageDomain.PermissionProvider.CheckExist(SystemPermissionKey.Manager_Delete); bool deleteok = managerbll.DeleteManager(managerid); if (deleteok) return JsonE("OK"); else { return Json(new JsonEntity() { code = -1, msg = "删除失败" }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FOREACH_LISTA { class Funcionarios { string nome; int idade; string cargo; int salario; public string Nome { get { return nome; } set { nome = value; } } public int Idade { get { return idade; } set { idade = value; } } public string Cargo { get { return cargo; } set { cargo = value; } } public int Salario { get { return salario; } set { salario = value; } } public Funcionarios(string nom, int ida, string carg, int salar){ this.Nome = nom; this.Idade = ida; this.Cargo = carg; this.Salario = salar; } } }
using System; using System.Diagnostics; public class Timing { //TimeSpan startingTime; //TimeSpan duration; static Stopwatch timer = new Stopwatch(); public Timing() { //startingTime = new TimeSpan(0); //duration = new TimeSpan(0); } public void stopTime() { timer.Stop(); //Stop timer //duration = Process.GetCurrentProcess().UserProcessorTime.CurrentThread.Subtract(startingTime); //duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime); } public void startTime() { GC.Collect(); GC.WaitForPendingFinalizers(); timer.Reset(); //reset timer to 0 timer.Start(); //start timer //startingTime = Process.GetCurrentProcess().CurrentThread.UserProcessorTime; //startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime; } public TimeSpan Result() { //get time elapsed in seconds return TimeSpan.FromSeconds(timer.Elapsed.TotalSeconds); //return duration; } } class chapter1 { static void Main() { int[] nums = new int[100000]; BuildArray(nums); Timing tObj = new Timing(); tObj.startTime(); DisplayNums(nums); tObj.stopTime(); Console.WriteLine("time (.NET): " + tObj.Result()); Console.WriteLine("IsHighResolution = " + Stopwatch.IsHighResolution); } static void BuildArray(int[] arr) { for(int i = 0; i <= arr.GetUpperBound(0); i++) arr[i] = i; } static void DisplayNums(int[] arr) { for(int i = 0; i <= arr.GetUpperBound(0); i++) Console.Write(arr[i] + " "); } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Runtime.InteropServices; namespace identity { public class Chapter2 { public Game1 game; private Texture2D background, Cop1; private Rectangle Leftside = new Rectangle(797, 37, 0, 481); private Rectangle Downside = new Rectangle(509, 550, 0, 164); private Rectangle a = new Rectangle(353, 380, 0, 154); private Rectangle b = new Rectangle(0, 19, 750, 0); private Rectangle c = new Rectangle(353, 518, 156, 0); private Rectangle d = new Rectangle(664, 536, 1150, 0); private Rectangle d2 = new Rectangle(664, 525, 1150, 0); private Rectangle e = new Rectangle(26, 22, 0, 500); private Rectangle f = new Rectangle(35, 358, 300, 0); private Rectangle g = new Rectangle(507, 682, 644, 0); private Rectangle h = new Rectangle(355, 38, 0, 132); private Rectangle i = new Rectangle(26, 168, 327, 0); private Rectangle Rightside = new Rectangle(207, 363, 150, 0); private Rectangle Talk = new Rectangle(19, 461, 307, 56); float chapter2; int moveright; int moveup; private Vector2 backpos = new Vector2(0, 0); private KeyboardState newState; float opacity = 1; public Chapter2(Game1 game) { this.game = game; background = game.Content.Load<Texture2D>("images/Chapter 2"); Cop1 = game.Content.Load<Texture2D>("images/Cop Back Sprite Brown Hair"); } public void Update(GameTime Gametime) { KeyboardState keyboardState = Keyboard.GetState(); newState = keyboardState; //Chapter 2 splash screen and opacity of cell hallway chapter2 += 0.0166666f; if (chapter2 <= 3) { opacity -= 0.006f; } if (chapter2 >= 3 && chapter2 <= 10) { background = game.Content.Load<Texture2D>("images/cell hallway"); if (opacity <= 1) { opacity += 0.01f; Gameplay.KurtPos = new Vector2(238, 269); Gameplay.KurtOpaque = 1; } } if (chapter2 >= 10 && Text.textinitiate != 3 && chapter2 <= 22) { chapter2 -= 0.0166666f; } if (background == game.Content.Load<Texture2D>("images/cell hallway")) { if (Gameplay.KurtPos.Y <= 18) Gameplay.KurtPos.Y = 18; if (Gameplay.KurtPos.Y >= 415) Gameplay.KurtPos.Y = 415; if (Gameplay.KurtPos.X <= 18) Gameplay.KurtPos.X = 18; if (Gameplay.KurtPos.X >= 241) Gameplay.KurtPos.X = 241; } if (Gameplay.KurtRect.Intersects(Talk)) { Text.textinitiate = 3; Text.textpause = 1; } else { Text.textinitiate = 0; Text.textpause = 0; } if (Text.event1 == 1) { if (backpos.X == -20) moveright = 1; if (moveright == 1) backpos.X += 10; if (backpos.X == 20) moveright = 0; if (moveright == 0) backpos.X -= 10; if (backpos.Y == -30) moveup = 1; if (moveup == 1) backpos.Y += 10; if (backpos.Y == 30) moveup = 0; if (moveup == 0) backpos.Y -= 10; } if (chapter2 >= 22 && chapter2 <= 27) { Talk = new Rectangle(0, 0, 0, 0); Text.textkey = 0; if (opacity >= 0) { opacity -= 0.01f; Gameplay.KurtOpaque -= 0.01f; } } if (chapter2 >= 30) { Text.event1 = 0; backpos = new Vector2(0, 0); if (opacity <= 1) { opacity += 0.01f; Gameplay.KurtOpaque += 0.01f; } background = game.Content.Load<Texture2D>("images/brooken cell"); } //private Rectangle Leftside = new Rectangle(797, 37, 0, 481); //private Rectangle Downside = new Rectangle(509, 520, 0, 164); //private Rectangle a = new Rectangle(353, 364, 0, 154); //private Rectangle b = new Rectangle(147, 19, 649, 0); //private Rectangle c = new Rectangle(353, 518, 156, 0); //private Rectangle d = new Rectangle(664, 536, 1150, 0); //private Rectangle e = new Rectangle(353, 364, 0, 154); //private Rectangle f = new Rectangle(35, 358, 300, 0); //private Rectangle g = new Rectangle(507, 682, 644, 0); //private Rectangle Rightside = new Rectangle(207, 363, 150, 0); //private Rectangle h = new Rectangle(355, 38, 0, 132); //private Rectangle i = new Rectangle(26, 168, 327, 0); if (background == game.Content.Load<Texture2D>("images/brooken cell")) { if (Gameplay.KurtRect.Intersects(Leftside)) { Gameplay.KurtPos.X = Leftside.X - 84; } if (Gameplay.KurtRect.Intersects(Downside)) { Gameplay.KurtPos.X = Downside.X; } if (Gameplay.KurtRect.Intersects(a)) { Gameplay.KurtPos.X = a.X; } if (Gameplay.KurtRect.Intersects(b)) { Gameplay.KurtPos.Y = b.Y; } if (Gameplay.KurtRect.Intersects(c)) { Gameplay.KurtPos.Y = c.Y - 104; } if (Gameplay.KurtRect.Intersects(d)) { Gameplay.KurtPos.Y = d.Y; } if (Gameplay.KurtRect.Intersects(d2)) { Gameplay.KurtPos.Y = d2.Y - 104; } if (Gameplay.KurtRect.Intersects(e)) { Gameplay.KurtPos.X = e.X; } if (Gameplay.KurtRect.Intersects(f)) { Gameplay.KurtPos.Y = f.Y - 104; } if (Gameplay.KurtRect.Intersects(g)) { Gameplay.KurtPos.Y = g.Y - 104; } if (Gameplay.KurtRect.Intersects(h)) { Gameplay.KurtPos.X = h.X; } if (Gameplay.KurtRect.Intersects(i)) { Gameplay.KurtPos.Y = i.Y; } } if (Gameplay.KurtPos.X >= 1100) { Gameplay.KurtPos.X = 0; Gameplay.KurtPos.Y = 290; game.level1 = 3; } } public void Draw(SpriteBatch spritebatch) { spritebatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); if (background == game.Content.Load<Texture2D>("images/cell hallway")) { spritebatch.Draw(Cop1, new Vector2(84, 538), null, Color.White * opacity, 0, Vector2.Zero, 1, SpriteEffects.None, 1); } spritebatch.Draw(background, backpos, null, Color.White * opacity, 0, Vector2.Zero, game.scale, SpriteEffects.None, 1); spritebatch.End(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Diagnostics; namespace Editor { [DescriptionAttribute("RigidBody"), CategoryAttribute("Components")] public class RigidBodyComponent : Component { #region accessors [CategoryAttribute("RigidBody")] public float Mass { get { return (float)GetField("Mass").value; } set { GetField("Mass").value = value; } } [CategoryAttribute("RigidBody")] public float Drag { get { return (float)GetField("Drag").value; } set { GetField("Drag").value = value; } } [CategoryAttribute("RigidBody")] public float AngularDrag { get { return (float)GetField("AngularDrag").value; } set { GetField("AngularDrag").value = value; } } [CategoryAttribute("RigidBody")] public bool UseGravity { get { return (bool)GetField("UseGravity").value; } set { GetField("UseGravity").value = value; } } [CategoryAttribute("RigidBody")] public bool IsKinematic { get { return (bool)GetField("IsKinematic").value; } set { GetField("IsKinematic").value = value; } } #endregion accessors public RigidBodyComponent() { base.DisplayName = "RigidBody"; base.Name = "RigidBodyComponent"; base.Description = "RigidBody Component"; } } }
/* * Created by SharpDevelop. * User: dell * Date: 05/05/2019 * Time: 05:50 a.m. * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Collections; namespace proyeto_poo { /// <summary> /// Description of Person. /// </summary> public class Person : Functions { string _name = null; long _phone = 0000000000; string _email = null; bool _paymethodwithcard = false; int ReservedRooms = 0, UnreservedRooms = 10, SimpleReserved = 0, SimpleUnreserved = 5, DoubleReserved = 0, DoubleUnreserved = 3, LuxorReserved = 0, LuxorUnreserved = 2; ArrayList PayDataVar = new ArrayList(); public Person( string name, long phone, string email, bool paymethodwithcard, ref Simple Room101, ref Simple Room102, ref Simple Room103, ref Simple Room104, ref Simple Room105, ref Double Room106, ref Double Room107, ref Double Room108, ref Luxor Room109, ref Luxor Room110 ) { this.name = name; this.phone = phone; this.email = email; this.paymethodwithcard = paymethodwithcard; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); } public string name{ get{return _name;} set{_name = value;}} public long phone{ get{return _phone;} set{_phone = value;}} public string email{ get{return _email;} set{_email = value;}} public bool paymethodwithcard{ get{return _paymethodwithcard;} set{_paymethodwithcard = value;}} double _FinalTotalFinalized = 0.0; public double FinalTotalFinalized{get { return _FinalTotalFinalized; }set { _FinalTotalFinalized = value; }} public long PaymentCardNumber {get;set;} string _MM_YY_Of_Card = "nothing"; public string MM_YY_Of_Card {get{return _MM_YY_Of_Card;}set{_MM_YY_Of_Card = value;}} public int CVC_Of_Card {get;set;} string[] _CardType = { "credito", "debito" }; public string[] CardType {get{return _CardType;}} public string print(){ string str = null; string temp = null; str = "Nombre: " + name + "\n"; str += "Telefono: " + phone + "\n"; str += "Email: " + email + "\n"; if (_paymethodwithcard){ temp = "Si"; }else{ temp = "No"; } str += "Pago con tarjeta: " + temp + "\n"; return str; } public ArrayList PayData(bool paymenthodwithcard){ if(paymenthodwithcard){ do{ WindowLogged("HOTEL HOLIDAY INN - RESERVACION: PAGO", 23); Write("REGISTRO DEL METODO DE PAGO", 5, 7); Write("Tipo de tarjeta (credito / debito): ", 5, 9); PayDataVar.Insert(0, MoveRead(41,9)); if (PayDataVar[0].ToString() != "credito" && PayDataVar[0].ToString() != "debito") { PopUp("Error: entrada incorrecta\nIngrese de nuevo","ERROR"); } }while (PayDataVar[0].ToString() != "credito" && PayDataVar[0].ToString() != "debito"); while (PaymentCardNumber.ToString().Length != 16) { try { WindowLogged("HOTEL HOLIDAY INN - RESERVACION: PAGO", 23); Write("REGISTRO DEL METODO DE PAGO", 5, 7); Write("Tipo de tarjeta (credito / debito): ", 5, 9); Write(PayDataVar[0].ToString(), 41,9); Write("Numero de tarjeta: ", 5, 10); PaymentCardNumber = Convert.ToInt64(MoveRead(24,10)); if (PaymentCardNumber.ToString().Length != 16) { PopUp("Error: ingrese un numero valido\nIngrese de nuevo","ERROR"); } } catch (Exception e) { PopUp("Error: " + e.Message + "\nIngrese de nuevo","ERROR"); } } while (MM_YY_Of_Card.Length != 5) { WindowLogged("HOTEL HOLIDAY INN - RESERVACION: PAGO", 23); Write("REGISTRO DEL METODO DE PAGO", 5, 7); Write("Tipo de tarjeta (credito / debito): ", 5, 9); Write(PayDataVar[0].ToString(), 41,9); Write("Numero de tarjeta: ", 5, 10); Write(PaymentCardNumber.ToString(),24, 10); Write("MM - YY de la tarjeta (MM/YY): ", 5, 11); MM_YY_Of_Card = MoveRead(36,11); if (MM_YY_Of_Card.Length != 5) { PopUp("Error: ingrese un numero valido\nIngrese de nuevo","ERROR"); } } while (CVC_Of_Card.ToString().Length != 3) { try { WindowLogged("HOTEL HOLIDAY INN - RESERVACION: PAGO", 23); Write("REGISTRO DEL METODO DE PAGO", 5, 7); Write("Tipo de tarjeta (credito / debito): ", 5, 9); Write(PayDataVar[0].ToString(), 41,9); Write("Numero de tarjeta: ", 5, 10); Write(PaymentCardNumber.ToString(),24, 10); Write("MM - YY de la tarjeta (MM/YY): ", 5, 11); Write(MM_YY_Of_Card, 36, 11); Write("CVC: ", 5, 12); CVC_Of_Card = Convert.ToInt32(MoveRead(11,12)); if (CVC_Of_Card.ToString().Length != 3) { PopUp("Error: ingrese un numero valido\nIngrese de nuevo","ERROR"); } } catch (Exception e) { PopUp("Error: " + e.Message + "\nIngrese de nuevo","ERROR"); } } } return PayDataVar; } public void Pay(ref Simple Room101, ref Simple Room102, ref Simple Room103, ref Simple Room104, ref Simple Room105, ref Double Room106, ref Double Room107, ref Double Room108, ref Luxor Room109, ref Luxor Room110){ string input = null; string input2 = null; do{ WindowLogged("HOTEL HOLIDAY INN - RESERVACION: HABITACION", 23); Write("Elija tipo de habitacion disponible", 5, 7); Write("Opcion elegida: ", 5, 9); Write("1. Habitaciones simples ocupadas: " + SimpleReserved, 5, 10); Write("2. Habitaciones dobles ocupadas: " + DoubleReserved, 5, 11); Write("3. Habitaciones luxor ocupadas: " + LuxorReserved, 5, 12); Write("*. Cancelar reservacion en curso: " + LuxorReserved, 5, 13); input = MoveRead(22, 9); switch (input) { case "1": WindowLogged("HOTEL HOLIDAY INN - RESERVACION: HABITACION", 23); Write("Elija habitacion disponible", 5, 7); Write("Opcion elegida: ", 5, 9); Write("1. 101 Ocupada: " + Room101.ReservationStatus, 5, 10); Write("2. 102 Ocupada: " + Room102.ReservationStatus, 5, 11); Write("3. 103 Ocupada: " + Room103.ReservationStatus, 5, 12); Write("5. 104 Ocupada: " + Room104.ReservationStatus, 5, 13); Write("5. 105 Ocupada: " + Room105.ReservationStatus, 5, 14); input2 = MoveRead(22, 9); switch (input2) { case "1": Room101.ReservationStatus = false; Room102.ReservationStatus = false; Room103.ReservationStatus = false; Room104.ReservationStatus = false; Room105.ReservationStatus = false; Room106.ReservationStatus = false; Room107.ReservationStatus = false; Room108.ReservationStatus = false; Room109.ReservationStatus = false; Room110.ReservationStatus = false; Write("Habitacion reservada", 30, 16); Room101.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "2": Room101.ReservationStatus = false; Room102.ReservationStatus = false; Room103.ReservationStatus = false; Room104.ReservationStatus = false; Room105.ReservationStatus = false; Room106.ReservationStatus = false; Room107.ReservationStatus = false; Room108.ReservationStatus = false; Room109.ReservationStatus = false; Room110.ReservationStatus = false; Write("Habitacion reservada", 30, 16); Room102.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "3": Room101.ReservationStatus = false; Room102.ReservationStatus = false; Room103.ReservationStatus = false; Room104.ReservationStatus = false; Room105.ReservationStatus = false; Room106.ReservationStatus = false; Room107.ReservationStatus = false; Room108.ReservationStatus = false; Room109.ReservationStatus = false; Room110.ReservationStatus = false; Write("Habitacion reservada", 30, 16); Room103.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "4": Room101.ReservationStatus = false; Room102.ReservationStatus = false; Room103.ReservationStatus = false; Room104.ReservationStatus = false; Room105.ReservationStatus = false; Room106.ReservationStatus = false; Room107.ReservationStatus = false; Room108.ReservationStatus = false; Room109.ReservationStatus = false; Room110.ReservationStatus = false; Write("Habitacion reservada", 30, 16); Room104.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "5": Room101.ReservationStatus = false; Room102.ReservationStatus = false; Room103.ReservationStatus = false; Room104.ReservationStatus = false; Room105.ReservationStatus = false; Room106.ReservationStatus = false; Room107.ReservationStatus = false; Room108.ReservationStatus = false; Room109.ReservationStatus = false; Room110.ReservationStatus = false; Write("Habitacion reservada", 30, 16); Room105.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; default: PopUp("Elija una opcion valida","ERROR"); break; } break; case "2": WindowLogged("HOTEL HOLIDAY INN - RESERVACION: HABITACION", 23); Write("Elija habitacion disponible", 5, 7); Write("Opcion elegida: ", 5, 9); Write("1. 106 Ocupada: " + Room106.ReservationStatus, 5, 10); Write("2. 107 Ocupada: " + Room107.ReservationStatus, 5, 11); Write("3. 108 Ocupada: " + Room108.ReservationStatus, 5, 12); input2 = MoveRead(22, 9); switch (input2) { case "1": Write("Habitacion reservada", 30, 16); Room106.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "2": Write("Habitacion reservada", 30, 16); Room107.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "3": Write("Habitacion reservada", 30, 16); Room108.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; default: PopUp("Elija una opcion valida","ERROR"); break; } break; case "3": WindowLogged("HOTEL HOLIDAY INN - RESERVACION: HABITACION", 23); Write("Elija habitacion disponible", 5, 7); Write("Opcion elegida: ", 5, 9); Write("1. 109 Ocupada: " + Room106.ReservationStatus, 5, 10); Write("2. 110 Ocupada: " + Room107.ReservationStatus, 5, 11); input2 = MoveRead(22, 9); switch (input2) { case "1": Write("Habitacion reservada", 30, 16); Room109.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; case "2": Write("Habitacion reservada", 30, 16); Room110.ReservationStatus = true; ReservedRoomsCount( ref Room101, ref Room102, ref Room103, ref Room104, ref Room105, ref Room106, ref Room107, ref Room108, ref Room109, ref Room110 ); break; default: PopUp("Elija una opcion valida","ERROR"); break; } break; case "*": break; default: PopUp("Elija una opcion valida","ERROR"); break; } }while(input != "*" && input != "1" && input != "2" && input != "3"); } public void ReservedRoomsCount( ref Simple Room101, ref Simple Room102, ref Simple Room103, ref Simple Room104, ref Simple Room105, ref Double Room106, ref Double Room107, ref Double Room108, ref Luxor Room109, ref Luxor Room110 ){ if (Room101.ReservationStatus) { ReservedRooms++; UnreservedRooms--; SimpleReserved++; SimpleUnreserved--; } if (Room102.ReservationStatus) { ReservedRooms++; UnreservedRooms--; SimpleReserved++; SimpleUnreserved--; } if (Room103.ReservationStatus) { ReservedRooms++; UnreservedRooms--; SimpleReserved++; SimpleUnreserved--; } if (Room104.ReservationStatus) { ReservedRooms++; UnreservedRooms--; SimpleReserved++; SimpleUnreserved--; } if (Room105.ReservationStatus) { ReservedRooms++; UnreservedRooms--; SimpleReserved++; SimpleUnreserved--; } if (Room106.ReservationStatus) { ReservedRooms++; UnreservedRooms--; DoubleReserved++; DoubleUnreserved--; } if (Room107.ReservationStatus) { ReservedRooms++; UnreservedRooms--; DoubleReserved++; DoubleUnreserved--; } if (Room108.ReservationStatus) { ReservedRooms++; UnreservedRooms--; DoubleReserved++; DoubleUnreserved--; } if (Room109.ReservationStatus) { ReservedRooms++; UnreservedRooms--; LuxorReserved++; LuxorUnreserved--; } if (Room110.ReservationStatus) { ReservedRooms++; UnreservedRooms--; LuxorReserved++; LuxorUnreserved--; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName="Zomz/AI/Action/Patrol",fileName="Action_Patrol_New")] public class PatrolAction : Action { public override void Act(AIStateController pController) { Patrol (pController); } private void Patrol(AIStateController pController) { if (pController.IsAlive) { if (pController.navMeshAgent.isActiveAndEnabled) { pController.navMeshAgent.destination = pController.wayPoints[pController.NextWayPoint].position; pController.navMeshAgent.isStopped = false; if (pController.navMeshAgent.remainingDistance <= 1f) { pController.NextWayPoint = Random.Range(0, pController.wayPoints.Count); } } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2017 { public class Problem12 : AdventOfCodeBase { private Dictionary<int, HashSet<int>> _hash; public override string ProblemName { get { return "Advent of Code 2017: 12"; } } public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { BuildHash(input); return FindContaining(0).Count; } private int Answer2(List<string> input) { BuildHash(input); return FindGroups(); } private int FindGroups() { int count = 0; var visited = new HashSet<int>(_hash.Keys); var group = FindContaining(0); do { foreach (var num in group) { visited.Remove(num); } if (visited.Count > 0) { group = FindContaining(visited.First()); } count++; } while (visited.Count > 0); return count; } private HashSet<int> FindContaining(int start) { var current = new List<int>() { start }; var seenBefore = new HashSet<int>(); do { var nextCurrent = new List<int>(); foreach (var num in current) { foreach (var next in _hash[num]) { if (!seenBefore.Contains(next)) { nextCurrent.Add(next); seenBefore.Add(next); } } } current = nextCurrent; } while (current.Count > 0); return seenBefore; } private void BuildHash(List<string> input) { _hash = new Dictionary<int, HashSet<int>>(); input.ForEach(line => { var split = line.Split(' '); var num1 = Convert.ToInt32(split[0]); for (int index = 2; index < split.Length; index++) { AddToHash(num1, Convert.ToInt32(split[index].Trim().Replace(",", ""))); } }); } private void AddToHash(int num1, int num2) { if (!_hash.ContainsKey(num1)) { _hash.Add(num1, new HashSet<int>()); } if (!_hash.ContainsKey(num2)) { _hash.Add(num2, new HashSet<int>()); } _hash[num1].Add(num2); _hash[num2].Add(num1); } } }
using System; using UnityEngine; using Unity.Mathematics; using static Unity.Mathematics.math; using Unity.Collections; namespace IzBone.IzBCollider.RawCollider { /** カプセル形状コライダ */ public unsafe struct Capsule : ICollider { public float3 pos; //!< 中央位置 public float r_s; //!< 横方向の半径 public float3 dir; //!< 縦方向の向き public float r_h; //!< 縦方向の長さ /** 指定の球がぶつかっていた場合、引き離しベクトルを得る */ public bool solve(Sphere* s, float3* oColN, float* oColDepth) { var d = s->pos - pos; // まずはバウンダリー球で衝突判定 var dSqLen = lengthsq(d); var sumR_s = r_s + s->r; var sumR_h = r_h + s->r; if (sumR_s*sumR_s < dSqLen && sumR_h*sumR_h < dSqLen) return false; // 縦方向の位置により距離を再計算 var len_h = dot(d, dir); // if (len_h < -sumR_h || sumR_h < len_h) return false; // バウンダリー球で判定する場合はこれはいらない if (len_h < -r_h+r_s) d += dir * (r_h-r_s); // 下側の球との衝突可能性がある場合 else if (len_h < r_h-r_s) d -= dir * len_h; // 中央との衝突可能性がある場合 else d += dir * (r_s-r_h); // 上側の球との衝突可能性がある場合 // 球vs球の衝突判定 dSqLen = lengthsq(d); if ( sumR_s*sumR_s < dSqLen ) return false; var dLen = sqrt(dSqLen); *oColN = d / (dLen + 0.0000001f); *oColDepth = sumR_s - dLen; return true; } } }
// Decompiled with JetBrains decompiler // Type: Tpi_Watcher.Program // Assembly: Tpi Watcher, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null // MVID: A91036F6-4ADD-407B-9987-2D811322E7F8 // Assembly location: C:\PixelPos\TPI Watcher\Tpi Watcher.exe using System; using System.Threading; using System.Windows.Forms; namespace Tpi_Watcher { internal static class Program { private static Mutex m_Mutex; [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool createdNew; Program.m_Mutex = new Mutex(true, "MyApplicationMutex", out createdNew); if (createdNew) { Application.Run((Form) new Form1()); } else { int num = (int) MessageBox.Show("TPI Watcher is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } }
using System; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Xamarin.Forms; namespace NSchedule { public static class Extensions { public static Page GetCurrentPage(this Shell s) { return (s?.CurrentItem?.CurrentItem as IShellSectionController)?.PresentedPage; } public static Color Random(this Color c) { var colors = typeof(Color).GetFields().ToList().Where(x => x.IsStatic && x.FieldType == typeof(Color)).ToList(); Random rng = new Random(); var n = rng.Next(0, colors.Count()); var col = colors[n]; return (Color)col.GetValue(null); } public static int GetIso8601WeekOfYear(this DateTime time) { // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll // be the same week# as whatever Thursday, Friday or Saturday are, // and we always get those right DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } // Return the week of our adjusted day return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; namespace _07.PrintAllMinionNames { class PrintAllMinionNames { static void Main() { string connStr = @"Server=.\SQLEXPRESS;database=MinionsDB;Trusted_Connection=true;"; List<string> minionsList = new List<string>(); using (SqlConnection connection = new SqlConnection(connStr)) { string sql = "Select m.Name from Minions as m"; SqlCommand minionNamesCmd = new SqlCommand(sql, connection); connection.Open(); using (SqlDataReader reader = minionNamesCmd.ExecuteReader()) { while (reader.Read()) { minionsList.Add(reader[0].ToString()); } } } if (minionsList.Count > 0) { PrintMinionNames(minionsList); } else { Console.WriteLine("Not any minions in database"); } } private static void PrintMinionNames(List<string> minionsList) { int oddName = 0; int lastName = minionsList.Count - 1; for (int i = 0; i < minionsList.Count; i++) { int curIndex; if (i % 2 == 0) { curIndex = oddName; oddName++; } else { curIndex = lastName; lastName--; } Console.WriteLine(minionsList[curIndex]); } } } }
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.Util; using Android.Views; using Android.Widget; namespace UberClone.Fragments { public class MakePaymentFragment : Android.Support.V4.App.DialogFragment { double mfares; TextView TotalFaresText; Button makePaymentButton; public EventHandler PaymentComplete; public MakePaymentFragment(double fares) { mfares = fares; } public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your fragment here } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.makepayment, container, false); TotalFaresText = view.FindViewById<TextView>(Resource.Id.totalfaresText); makePaymentButton = view.FindViewById<Button>(Resource.Id.makePaymentButton); TotalFaresText.Text = "$" + mfares.ToString(); makePaymentButton.Click += MakePaymentButton_Click; return view; } private void MakePaymentButton_Click(object sender, EventArgs e) { PaymentComplete.Invoke(this, new EventArgs()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace goPlayApi.Models { public class Gamification { public int GamificationId { get; set; } public int Points { get; set; } public int UserId { get; set; } public User User { get; set; } } }
namespace FichaTecnica.Repositorio.EF.Migrations { using System; using System.Data.Entity.Migrations; public partial class FirstMigration : DbMigration { public override void Up() { CreateTable( "dbo.Cargo", c => new { Id = c.Int(nullable: false, identity: true), Descricao = c.String(nullable: false, maxLength: 500), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Comentario", c => new { Id = c.Int(nullable: false, identity: true), Assunto = c.String(nullable: false, maxLength: 500), Texto = c.String(nullable: false, maxLength: 1000), Tipo = c.Int(nullable: false), DataCriacao = c.DateTime(nullable: false), IdProjeto = c.Int(nullable: false), IdUsuario = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Projeto", t => t.IdProjeto, cascadeDelete: false) .ForeignKey("dbo.Usuario", t => t.IdUsuario, cascadeDelete: false) .Index(t => t.IdProjeto) .Index(t => t.IdUsuario); CreateTable( "dbo.Projeto", c => new { Id = c.Int(nullable: false, identity: true), Nome = c.String(nullable: false, maxLength: 500), DataInicio = c.DateTime(nullable: false), Descricao = c.String(nullable: false), IdUsuario = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Usuario", t => t.IdUsuario, cascadeDelete: false) .Index(t => t.IdUsuario); CreateTable( "dbo.Membro", c => new { Id = c.Int(nullable: false, identity: true), Nome = c.String(nullable: false, maxLength: 500), Email = c.String(nullable: false, maxLength: 500), DataDeNascimento = c.DateTime(nullable: false), DataCriacao = c.DateTime(nullable: false), Telefone = c.String(maxLength: 18), Foto = c.String(maxLength: 500), IdCargo = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Cargo", t => t.IdCargo, cascadeDelete: false) .Index(t => t.IdCargo); CreateTable( "dbo.Usuario", c => new { Id = c.Int(nullable: false, identity: true), Senha = c.String(nullable: false, maxLength: 200), Email = c.String(nullable: false, maxLength: 255), Nome = c.String(nullable: false, maxLength: 120), IdPermissao = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Permissao", t => t.IdPermissao, cascadeDelete: false) .Index(t => t.IdPermissao); CreateTable( "dbo.Permissao", c => new { Id = c.Int(nullable: false, identity: true), Descricao = c.String(nullable: false, maxLength: 120), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.LinkFork", c => new { Id = c.Int(nullable: false, identity: true), IdProjeto = c.Int(nullable: false), IdMembro = c.Int(nullable: false), URL = c.String(nullable: false, maxLength: 500), }) .PrimaryKey(t => t.IdProjeto); CreateTable( "dbo.Membro_Projeto", c => new { IdMembro = c.Int(nullable: false), IdProjeto = c.Int(nullable: false), }) .PrimaryKey(t => new { t.IdMembro, t.IdProjeto }) .ForeignKey("dbo.Membro", t => t.IdMembro, cascadeDelete: false) .ForeignKey("dbo.Projeto", t => t.IdProjeto, cascadeDelete: false) .Index(t => t.IdMembro) .Index(t => t.IdProjeto); } public override void Down() { DropForeignKey("dbo.Comentario", "IdUsuario", "dbo.Usuario"); DropForeignKey("dbo.Comentario", "IdProjeto", "dbo.Projeto"); DropForeignKey("dbo.Projeto", "IdUsuario", "dbo.Usuario"); DropForeignKey("dbo.Usuario", "IdPermissao", "dbo.Permissao"); DropForeignKey("dbo.Membro_Projeto", "IdProjeto", "dbo.Projeto"); DropForeignKey("dbo.Membro_Projeto", "IdMembro", "dbo.Membro"); DropForeignKey("dbo.Membro", "IdCargo", "dbo.Cargo"); DropIndex("dbo.Membro_Projeto", new[] { "IdProjeto" }); DropIndex("dbo.Membro_Projeto", new[] { "IdMembro" }); DropIndex("dbo.Usuario", new[] { "IdPermissao" }); DropIndex("dbo.Membro", new[] { "IdCargo" }); DropIndex("dbo.Projeto", new[] { "IdUsuario" }); DropIndex("dbo.Comentario", new[] { "IdUsuario" }); DropIndex("dbo.Comentario", new[] { "IdProjeto" }); DropTable("dbo.Membro_Projeto"); DropTable("dbo.LinkFork"); DropTable("dbo.Permissao"); DropTable("dbo.Usuario"); DropTable("dbo.Membro"); DropTable("dbo.Projeto"); DropTable("dbo.Comentario"); DropTable("dbo.Cargo"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class New_problem : System.Web.UI.Page { TaskManager ts = new TaskManager(); protected void Page_Load(object sender, EventArgs e) { Label2.Visible = false; if (!IsPostBack) loadCats(); } protected void loadCats() { List<string> cats = ts.getCats(); if(cats.Count==0) { CheckBox1.Checked=true; return; } DropDownList1.Items.Clear(); foreach (string tc in cats) { DropDownList1.Items.Add(tc); } } protected void CheckBox1_CheckedChanged(object sender, EventArgs e) { if(CheckBox1.Checked) { TextBox1.Enabled = true; DropDownList1.Enabled = false; } else { TextBox1.Enabled = false; DropDownList1.Enabled = true; } } protected void Button1_Click(object sender, EventArgs e) { string cat=string.Empty; if (CheckBox1.Checked) cat = TextBox1.Text; else cat = DropDownList1.SelectedItem.ToString(); if(cat.TrimEnd().Length<1) { Label2.Text = "Please Enter/Select The Category."; Label2.Visible = true; return; } string problem = TextBox2.Text; if (problem.TrimEnd().Length < 1) { Label2.Text = "Please Enter The Problem."; Label2.Visible = true; return; } if(CheckBox1.Checked && DropDownList1.Items.ToString().Contains(TextBox1.Text)) { Label2.Text = "Category Exist, Please Choose From The List."; Label2.Visible = true; return; } if(CheckBox1.Checked) { if(!ts.newCat(cat)) { Label2.Text = "Failed To Insert To Database."; Label2.Visible = true; return; } } if(!ts.newProblem(cat,problem)) { if (!ts.newCat(cat)) { Label2.Text = "Failed To Insert To Database."; Label2.Visible = true; return; } } int problemId = ts.getProblemId(problem); if(problemId==0) { Label2.Text = "Sorry Something Went Wrong, Please Try Again."; Label2.Visible = true; return; } Session["PID"] = problemId; Response.Redirect("First_Question"); } }
using UnityEngine; using System.Collections; /* The SkinSwitcher class allows the user to change skins and customize the virus tracker. */ public class SkinSwitcher : MonoBehaviour { public Texture[] texture; //array of skins public GameObject[] obj; //array of GameObject objects to be retextured int textureIndex = 0; //location in texture /* The setIndex function is called by the SwitchImage script to choose the new skin. */ public void setIndex(int currentIndex) { textureIndex = currentIndex; } /* The getIndex function returns the index of the current skin. */ public int getIndex() { return textureIndex; } /* The OnLevelWasLoaded function retextures the Player when a new level is loaded. */ void OnLevelWasLoaded(int level) { for (int i = 0; i < obj.Length; i++) { obj[i].GetComponent<Renderer>().material.mainTexture = texture[textureIndex]; } } }
namespace P08MilitaryElite.Interfaces { using System.Collections.Generic; public interface ILeutenantGeneral : IPrivate { IEnumerable<IPrivate> Privates { get; } } }
using UnityEngine; #if UNITY_ANDROID || UNITY_IPHONE using UnityEngine.Advertisements; #endif using System; using Mio.TileMaster; namespace Mio.Utils { #pragma warning disable 414 public class UnityAdsHelper : MonoBehaviour { public bool isEnabled = false; public string rewardVideoID = "rewardedVideo"; public string interstitialZoneID = "video"; private string rewardIDPostponeAds = "rewardVideoPostponeAds"; public string iosID = "1073252"; public string androidID = "1073253"; private int diamondsReward = 10; private static UnityAdsHelper instance; public Action OnViewedAds; public static UnityAdsHelper Instance { get { if (instance == null) { Debug.LogError("UnityAdhelper instance is null, is this an error?"); } return instance; } } // Use this for initialization void Start () { if (instance == null) { instance = this; //print("here"); DontDestroyOnLoad(this.gameObject); } else { if (this != instance) { Destroy(this); return; } } } public void Initialize () { if (!isEnabled) return; if (GameManager.Instance.GameConfigs.videoAdsReward != 0) diamondsReward = GameManager.Instance.GameConfigs.videoAdsReward; string id = androidID; #if UNITY_IOS id = iosID; Advertisement.Initialize(id); #endif } public void ShowRewardedAd () { if (!isEnabled) return; #if UNITY_ANDROID || UNITY_IPHONE //if (Advertisement.IsReady(rewardVideoID)) { // Advertisement.Show(rewardVideoID, new ShowOptions { // resultCallback = HandleShowResultRewardDiamond // }); //} #endif } public void ShowRewardVideoPostponeAds () { if (!isEnabled) return; #if UNITY_ANDROID || UNITY_IPHONE //if (Advertisement.IsReady(rewardIDPostponeAds)) { // Advertisement.Show(rewardIDPostponeAds, new ShowOptions { // resultCallback = HandleShowResultPostponeAds // }); //} #endif } public void ShowInterstitialAds (bool callMopubIfAdNotAvailable = true) { if (!isEnabled) return; #if UNITY_ANDROID || UNITY_IPHONE //if (Advertisement.IsReady(interstitialZoneID)) { // Advertisement.Show(interstitialZoneID); // //AdHelper.Instance.ResetTimeStamp(); //} //else { // if (callMopubIfAdNotAvailable) { // AdHelper.Instance.DisplayInterstitialAds(); // } //} #endif } #if UNITY_ANDROID || UNITY_IPHONE private void HandleShowResultRewardDiamond (ShowResult result) { // switch (result) { // case ShowResult.Finished: // //Debug.Log("The ad was successfully shown."); // RewardDiamond(); // AchievementHelper.Instance.LogAchievement("watchVideoAds"); // break; // case ShowResult.Skipped: // Debug.Log("The ad was skipped before reaching the end."); // break; // case ShowResult.Failed: // Debug.LogError("The ad failed to be shown."); // break; // } } private void HandleShowResultPostponeAds (ShowResult result) { switch (result) { case ShowResult.Finished: //Debug.Log("The ad was successfully shown."); PostponeAds(); AchievementHelper.Instance.LogAchievement("watchVideoAds"); break; case ShowResult.Skipped: Debug.Log("The ad was skipped before reaching the end."); break; case ShowResult.Failed: Debug.LogError("The ad failed to be shown."); break; } } #endif private void PostponeAds () { ProfileHelper.Instance.TimeToResumeAds = DateTime.Now.AddMinutes(10).ToEpochTime(); } private void RewardDiamond () { ProfileHelper.Instance.CurrentDiamond += diamondsReward; if (OnViewedAds != null) OnViewedAds(); } } }
using MySql.Data.MySqlClient; using System; using System.Data; using System.Text; using System.Windows.Forms; namespace GYOMU_CHECK { public partial class MS0010 : Form { private User user; CommonUtil comU = new CommonUtil(); MySqlCommand command = new MySqlCommand(); MySqlTransaction transaction = null; string programId = "MS0010"; private int passNumber = 3; public MS0010(User user) { InitializeComponent(); this.user = user; txtOldPass.PasswordChar = '●'; txtNewPass.PasswordChar = '●'; txtNewPass2.PasswordChar = '●'; } private void btnInsert_Click(object sender, EventArgs e) { if (!CheckUpdate()) { return; } Update(); } private void Update() { DialogResult result = MessageBox.Show("変更を行います。よろしいでしょうか。?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { if (!comU.CConnect(ref transaction, ref command)) { return; } if (!UpdatePasswordMst(transaction)) { MessageBox.Show("パスワードマスタの更新に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } transaction.Commit(); MessageBox.Show("変更が完了しました。", ""); this.Close(); } } private bool UpdatePasswordMst(MySqlTransaction transaction) { StringBuilder sql = new StringBuilder(); sql.Append(" INSERT INTO mst_shainpw "); sql.Append(" (MST_SHAINPW_CODE "); sql.Append(" ,MST_SHAINPW_GENERAITON "); sql.Append(" ,MST_SHAINPW_PASSWORD "); sql.Append(" ,MST_SHAINPW_INS_DT "); sql.Append(" ,MST_SHAINPW_INS_USER "); sql.Append(" ,MST_SHAINPW_INS_PGM "); sql.Append(" ,MST_SHAINPW_UPD_DT "); sql.Append(" ,MST_SHAINPW_UPD_USER "); sql.Append(" ,MST_SHAINPW_UPD_PGM) "); sql.Append(" SELECT "); sql.Append($" {user.Id} "); sql.Append(" ,MAX(MST_SHAINPW_GENERAITON) + 1 "); sql.Append($" ,{comU.GetHashedPassword(txtNewPass.Text)})"); sql.Append(" ,now() "); sql.Append($" ,{user.Id} "); sql.Append($" ,{comU.CAddQuotation(programId)} "); sql.Append(" ,now() "); sql.Append($" ,{user.Id} "); sql.Append($" ,{comU.CAddQuotation(programId)} "); sql.Append("FROM mst_shainpw"); if (!comU.CExecute(ref transaction, ref command, sql.ToString())) { return false; } return true; } private bool CheckUpdate() { if(string.IsNullOrEmpty(txtOldPass.Text.ToString())|| string.IsNullOrEmpty(txtNewPass.Text.ToString())|| string.IsNullOrEmpty(txtNewPass2.Text.ToString())) { MessageBox.Show("すべて入力してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtNewPass.Text.Length < 10 || txtNewPass2.Text.Length < 10 || txtOldPass.Text.Length < 10) { MessageBox.Show("パスワードは10文字以上で入力してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (!txtNewPass.Text.Equals(txtNewPass2.Text)) { MessageBox.Show("新パスワードと確認パスワードが一致していません", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); txtNewPass2.Focus(); return false; } StringBuilder sql = new StringBuilder(); sql.Append(" SELECT "); sql.Append(" MST_SHAINPW_PASSWORD"); sql.Append(" FROM mst_shain"); sql.Append(" LEFT JOIN mst_shainpw"); sql.Append(" ON MST_SHAIN_CODE = MST_SHAINPW_CODE"); sql.Append($" WHERE MST_SHAIN_CODE = {user.Id}"); sql.Append($" AND MST_SHAINPW_GENERAITON = (select MAX(MST_SHAINPW_GENERAITON) from mst_shainpw WHERE MST_SHAINPW_CODE = {user.Id})"); DataSet ds = new DataSet(); if (!comU.CSerch(sql.ToString(), ref ds)) { return false; } if (ds.Tables["Table1"].Rows.Count == 0) { MessageBox.Show("旧パスワードが間違っています。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); txtOldPass.Focus(); return false; } for (int i = 0; i < ds.Tables["Table1"].Rows.Count; i++) { if (ds.Tables["Table1"].Rows[i]["MST_SHAINPW_PASSWORD"].ToString().Equals(comU.GetHashedPassword(txtOldPass.Text))) { //過去に登録されたパスワードかチェック return CheckTorokuPass(); } } MessageBox.Show("旧パスワードが間違っています。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); txtOldPass.Focus(); return false; } private bool CheckTorokuPass() { //過去3回使用されていないか StringBuilder sqlPass = new StringBuilder(); sqlPass.Append(" SELECT "); sqlPass.Append(" MST_SHAINPW_PASSWORD"); sqlPass.Append(" FROM mst_shain"); sqlPass.Append(" LEFT JOIN mst_shainpw"); sqlPass.Append(" ON MST_SHAIN_CODE = MST_SHAINPW_CODE"); sqlPass.Append($" WHERE MST_SHAIN_CODE = {user.Id}"); sqlPass.Append($" AND MST_SHAINPW_GENERAITON > (select MAX(MST_SHAINPW_GENERAITON) from mst_shainpw WHERE MST_SHAINPW_CODE = {user.Id}) -{passNumber}"); DataSet dsPass = new DataSet(); if (!comU.CSerch(sqlPass.ToString(), ref dsPass)) { return false; } for (int i = 0; i < dsPass.Tables["Table1"].Rows.Count; i++) { if (dsPass.Tables["Table1"].Rows[i]["MST_SHAINPW_PASSWORD"].ToString().Equals(comU.GetHashedPassword(txtNewPass.Text))) { MessageBox.Show("過去に使用されたパスワードです。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } return true; } private void btnReturn_Click_1(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using VideoStream.Models; using VideoStream.ViewModels; using Xamarin.Forms; namespace VideoStream.Views { public partial class FirstPage : ContentView { public FirstPage() { InitializeComponent(); BackgroundColor = Color.White; } private async void HandleTapped(object sender,EventArgs e) { var gestureRecognizer = (sender as StackLayout).GestureRecognizers[0] as TapGestureRecognizer; var video = gestureRecognizer.CommandParameter as Video; var mainVm = BindingContext as MainPageViewModel; mainVm.PlayVideoCommand.Execute(video); } } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SafetySharp.CaseStudies.SmallModels.DeadReckoning { using System; using System.Collections.Generic; using Analysis; using Bayesian; using ISSE.SafetyChecking; using ISSE.SafetyChecking.MinimalCriticalSetAnalysis; using ModelChecking; using NUnit.Framework; public class BayesianAnalysis { [Test] public void TestScoreBasedLearning() { var model = new DeadReckoningModel(); Func<bool> hazard = () => model.Component.Hazard; Func<bool> state = () => model.Component.NoDataAvailable || model.Component.CalculationError; var states = new Dictionary<string, Func<bool>> { /*["State"] = state*/ }; var config = BayesianLearningConfiguration.Default; var bayesianCreator = new BayesianNetworkCreator(model, 10, config); var result = bayesianCreator.LearnScoreBasedBayesianNetwork(@"C:\SafetySharpSimulation\", 100000, hazard, states); } [Test] public void TestConstraintBasedLearning() { var model = new DeadReckoningModel(); Func<bool> hazard = () => model.Component.Hazard; Func<bool> state = () => true; var states = new Dictionary<string, Func<bool>> { /*["State"] = state*/ }; var config = BayesianLearningConfiguration.Default; var bayesianNetworkCreator = new BayesianNetworkCreator(model, 10, config); var result = bayesianNetworkCreator.LearnConstraintBasedBayesianNetwork(hazard, states, new[] { model.Component.FF, model.Component.FS, model.Component.FC }); } [Test] public void SerializeAndDeserializeBayesianNetwork() { const string filePath = "network.json"; var model = new DeadReckoningModel(); Func<bool> hazard = () => model.Component.Hazard; var config = BayesianLearningConfiguration.Default; config.BayesianNetworkSerializationPath = filePath; var bayesianNetworkCreator = new BayesianNetworkCreator(model, 10, config); var result = bayesianNetworkCreator.LearnConstraintBasedBayesianNetwork(hazard, null, new[] { model.Component.FF, model.Component.FS, model.Component.FC }); bayesianNetworkCreator = new BayesianNetworkCreator(model, 10); var network = bayesianNetworkCreator.FromJson(filePath, hazard); } [Test] public void CalculateBayesianNetworkProbabilities() { const string filePath = "network.json"; var model = new DeadReckoningModel(); Func<bool> hazard = () => model.Component.Hazard; var bayesianNetworkCreator = new BayesianNetworkCreator(model, 10); var network = bayesianNetworkCreator.FromJson(filePath, hazard); var calculator = new BayesianNetworkProbabilityDistributionCalculator(network, 0.0000000001); var result = calculator.CalculateConditionalProbabilityDistribution(new[] { "FS" }, new[] { "FC", "FF" }); Console.Out.WriteLine(string.Join("\n", result)); } [Test] public void CalculateHazardProbability() { var tc = SafetySharpModelChecker.TraversalConfiguration; tc.WriteGraphvizModels = true; tc.EnableStaticPruningOptimization = false; SafetySharpModelChecker.TraversalConfiguration = tc; var model = new DeadReckoningModel(); var result = SafetySharpModelChecker.CalculateProbabilityToReachStateBounded(model, model.Component.Hazard, 10); Console.WriteLine($"Probability of hazard in model: {result}"); } [Test] public void CalculateFaultProbabilities() { var tc = SafetySharpModelChecker.TraversalConfiguration; tc.WriteGraphvizModels = true; tc.EnableStaticPruningOptimization = false; SafetySharpModelChecker.TraversalConfiguration = tc; var model = new DeadReckoningModel(); var isFlActivated = SafetySharpModelChecker.CalculateProbabilityToReachStateBounded(model, model.Component.FF.IsActivated, 20); var isFvActivated = SafetySharpModelChecker.CalculateProbabilityToReachStateBounded(model, model.Component.FC.IsActivated, 20); var isFsActivated = SafetySharpModelChecker.CalculateProbabilityToReachStateBounded(model, model.Component.FS.IsActivated, 20); Console.WriteLine($"Probability that Fault1 is activated: {isFlActivated}"); Console.WriteLine($"Probability that Fault2 is activated: {isFvActivated}"); Console.WriteLine($"Probability that Fault2 is activated: {isFsActivated}"); } [Test] public void CalculateDcca() { var model = new DeadReckoningModel(); var analysis = new SafetySharpSafetyAnalysis { Backend = SafetyAnalysisBackend.FaultOptimizedOnTheFly, Heuristics = { new MaximalSafeSetHeuristic(model.Faults) } }; var result = analysis.ComputeMinimalCriticalSets(model, model.Component.Hazard); var orderResult = SafetySharpOrderAnalysis.ComputeOrderRelationships(result); Console.WriteLine(orderResult); } [Test] public void CalculateRangeHazardLtmdp() { var model = new DeadReckoningModel(); model.Component.FF.ProbabilityOfOccurrence = null; SafetySharpModelChecker.TraversalConfiguration.EnableStaticPruningOptimization = true; SafetySharpModelChecker.TraversalConfiguration.LtmdpModelChecker = LtmdpModelChecker.BuildInMdpWithNewStates; var result = SafetySharpModelChecker.CalculateProbabilityRangeToReachStateBounded(model, model.Component.Hazard, 10); Console.Write($"Probability of hazard: {result}"); } [Test] public void CalculateRangeHazardLtmdpWithoutStaticPruning() { var model = new DeadReckoningModel(); model.Component.FF.ProbabilityOfOccurrence = null; SafetySharpModelChecker.TraversalConfiguration.EnableStaticPruningOptimization = false; SafetySharpModelChecker.TraversalConfiguration.LtmdpModelChecker = LtmdpModelChecker.BuildInMdpWithNewStates; var result = SafetySharpModelChecker.CalculateProbabilityRangeToReachStateBounded(model, model.Component.Hazard, 10); SafetySharpModelChecker.TraversalConfiguration.EnableStaticPruningOptimization = true; Console.Write($"Probability of hazard: {result}"); } } }
using UnityEngine; using System.Collections.Generic; public class Or : BasicMove { private Move[] moves; public Or(params Move[] variableMoves) { moves = variableMoves; } public override Move Clone() { List<Move> clonedMoves = new List<Move> (); foreach(Move m in moves) { clonedMoves.Add (m.Clone ()); } return new Or (clonedMoves.ToArray ()).AddConstraint(manualAddedConstraints.ToArray()); } protected override List<Vector3> CalcEndPoints (Vector3 start, Board[] boards) { List<Vector3> outDots = new List<Vector3> (); foreach (Move move in moves) { outDots.AddRange (move.GetMovesFrom (start, boards)); } return outDots; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thingy.WebServerLite.Api; namespace Thingy.WebServerLite { public class UserFactory : IUserFactory { public IUser CreateFailedUser() { return new User("Failed"); } public IUser CreateGuestUser() { return new User("Guest"); } public IUser CreateUserFromKnownUser(IKnownUser knownUser) { return new User(knownUser.UserId, knownUser.Roles); } } }
using MyForum.Domain; using MyForum.Infrastructure.Exceptions; using MyForum.Persistence; using MyForum.Services.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyForum.Services { public class ThreadsService : IThreadsService { private readonly MyForumDbContext db; private readonly IUsersService usersService; private readonly ICategoriesService categoriesService; public ThreadsService(MyForumDbContext db, IUsersService usersService, ICategoriesService categoriesService) { this.db = db; this.usersService = usersService; this.categoriesService = categoriesService; } public IQueryable<Thread> All() { var allTreads = this.db.Threads; return allTreads; } public async Task Create(string title, string content, string authorId, string categoryId) { var errorMessage = ""; try { var thread = new Thread { Id = Guid.NewGuid().ToString(), Title = title, Content = content, CreatedOn = DateTime.UtcNow, ThreadCreatorId = authorId, CategoryId = categoryId }; this.db.Threads.Add(thread); await this.db.SaveChangesAsync(); } catch (Exception ex) { errorMessage = ex.Message; throw new CreateThreadException(); } } public async Task Delete(string threadId) { var thread = this.db.Threads.FirstOrDefault(t => t.Id == threadId); this.db.Threads.Remove(thread); await this.db.SaveChangesAsync(); } public async Task<string> Edit(string threadId, string title, string content, DateTime modifiedOn) { var threadFromDb = this.db.Threads.FirstOrDefault(t => t.Id == threadId); threadFromDb.ModifiedOn = modifiedOn; threadFromDb.Title = title; threadFromDb.Content = content; this.db.Threads.Update(threadFromDb); await this.db.SaveChangesAsync(); return threadFromDb.CategoryId; } public async Task<Thread> GetThreadById(string id) { var thread = this.db.Threads.Where(t => t.Id == id).FirstOrDefault(); return thread; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EpisodeGrabber.Library.DAO; using EpisodeGrabber.Library.Entities; namespace EpisodeGrabber.Library.Services { public interface IFetchService { BusinessObject<List<EntityBase>> FetchMetadataByName(string name); BusinessObject<EntityBase> FetchMetadataByID(int id); } }
using UnityEngine; using System.Collections; public class RightEdge : MonoBehaviour { public Main parent; private void OnCollisionEnter(Collision col) { parent.UpdateRightScore(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Interfaz { public partial class Paciente : Form { public Paciente() { InitializeComponent(); } private void groupBox1_Enter(object sender, EventArgs e) { } //Validacioneees private bool valid() { bool error = true; if (txtCiPaciente.Text == "") { error = false; error1.SetError(txtCiPaciente, "Ingresa la cédula del paciente"); } if (txtNombre.Text == "") { error = false; error2.SetError(txtNombre, "Nombre del paciente."); } if (txtSexo.Text == "") { error = false; error3.SetError(txtSexo, "Asigna un género"); } if (txtEdad.Text == "") { error = false; error4.SetError(txtEdad, "Ingresa la edad del paciente."); } if (txtTelefono.Text == "") { error = false; error5.SetError(txtTelefono, "Agrega un número teléfonico"); } if (dateTimePickerFUR.Text == "") { error = false; error6.SetError(dateTimePickerFUR, "Fecha de hoy"); } if (txtNroHab.Text == "") { error = false; error7.SetError(txtNroHab, "El número de habitación"); } if (txtIdMedico.Text == "") { error = false; error8.SetError(txtIdMedico, "Agrega el ID del médico"); } return error; } //Eliminación de los errores private void SinErrores() { error1.SetError(txtCiPaciente, ""); error2.SetError(txtNombre, ""); error3.SetError(txtSexo, ""); error4.SetError(txtEdad,""); error5.SetError(txtTelefono,""); error6.SetError(dateTimePickerFUR,""); error7.SetError(txtNroHab,""); error8.SetError(txtIdMedico,""); } private void btnGuardar_Click(object sender, EventArgs e) { SinErrores(); if (valid()) { MessageBox.Show("¡Paciente guardado satisfactoriamente!", "Almacenado...", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } } }
public interface IObserver<T> { void Notify(T subject); } public interface IObserver<T1,T2> { void Notify(T1 subject1, T2 subject2); } public interface IObserver<T1,T2, T3> { void Notify(T1 subject1, T2 subject2, T3 subject3); }
using NUnit.Framework; namespace CaveDwellersTest { [TestFixture] public abstract class AAATest { protected abstract void Arrange(); protected abstract void Act(); [TestFixtureSetUp] public void ArrangeAct() { Arrange(); Act(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { [SerializeField] Rigidbody2D rb2d; [SerializeField] Vector2 direction;//移動する方向 public float speed; public int ItemNum;//アイテムとしての番号 // Start is called before the first frame update void Start() { rb2d = this.GetComponent<Rigidbody2D>(); Move();//移動する力を一度だけ与える } // Update is called once per frame void Update() { } void Move() {//真下に落ちていく direction = new Vector2(0,-1.0f); rb2d.velocity = direction * speed; } }
 using Newtonsoft.Json; namespace SecureNetRestApiSDK.Api.Models { public class UserDefinedField { #region Properties [JsonProperty("udfName")] public string UdfName { get; set; } [JsonProperty("udfValue")] public string UdfValue { get; set; } #endregion } }
namespace Projekt_PPR { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Oddane")] public partial class Oddane { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID_operacji { get; set; } [StringLength(50)] public string rasa { get; set; } [Column(TypeName = "date")] public DateTime data { get; set; } public void nowa_historia(int ID_operacji, string rasa, DateTime data) { this.ID_operacji = ID_operacji; this.rasa = rasa; this.data = data; } } }
using UnityEngine; public class BaseMove : MonoBehaviour { /// <summary> /// 同步时间 /// </summary> public float lastSendSyncTime = 0; /// <summary> /// 同步帧率 /// </summary> public static float syncInterval = 0.02f; // Use this for initialization private void Start() { } // Update is called once per frame private void Update() { } }
using System; using System.Collections.Generic; using System.Text; using Breeze.AssetTypes; using Breeze.AssetTypes.StaticTemplates; using Breeze.Screens; namespace Breeze.Helpers { public static class StateHelper { public static ButtonVisualDescriptor GetState(this StaticTemplate template, ButtonState state, bool enabled) { if (!enabled) return template.Disabled; switch (state) { case ButtonState.Normal: { return template.Normal; } case ButtonState.Hover: { return template.Hover; } case ButtonState.Pressing: { return template.Pressing; } } throw new Exception("Who added a new state?"); } } }
using System.Windows.Input; using Inventory.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 namespace Inventory.Views { public sealed partial class OrderDishChoiceGrid : UserControl { public OrderDishChoiceGrid() { InitializeComponent(); } #region ViewModel public DishListViewModel ViewModel { get { return (DishListViewModel)GetValue(ViewModelProperty); } set { SetValue(ViewModelProperty, value); } } public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(DishListViewModel), typeof(OrderDishChoiceGrid), new PropertyMetadata(null)); #endregion #region NewCommand public ICommand NewCommand { get { return (ICommand)GetValue(NewCommandProperty); } set { SetValue(NewCommandProperty, value); } } public static readonly DependencyProperty NewCommandProperty = DependencyProperty.Register("NewCommand", typeof(ICommand), typeof(OrderDishChoiceGrid), new PropertyMetadata(null)); #endregion } }
using System; using System.Linq; using System.Xml; using System.Xml.Serialization; using Breeze.AssetTypes.DataBoundTypes; using Breeze.AssetTypes.XMLClass; using Breeze.FontSystem; using Breeze.Helpers; using Breeze.Screens; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Breeze.AssetTypes { public class ButtonAsset : InteractiveAsset { public ButtonAsset() { } public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null) { if (this.Children.Value == null || this.Children.Value.Count == 0) { return; } foreach (DataboundAsset databoundAsset in this.Children.Value) { databoundAsset.IsHidden.Value = true; } DataboundAsset select = this.Children.Value.First(); if (this.State.Value == ButtonState.Hover && this.Children.Value.Count > 1) select = this.Children.Value[1]; if (this.State.Value == ButtonState.Pressing && this.Children.Value.Count > 2) select = this.Children.Value[2]; select.IsHidden.Value = false; SetChildrenOriginToMyOrigin(); if (this.ActualSize == Vector2.Zero) { this.ActualSize = this.Children.Value.First().ActualSize; } } } }
using Sales.ViewModels; using MahApps.Metro.Controls; using Sales.SplashScreen; using System.Threading; using System.ServiceProcess; using Sales.Models; using Sales.Services; using System.Linq; using System.Data.Entity; namespace Sales.Views.MainViews { public partial class MainWindow : MetroWindow { CategoryServices catServ = new CategoryServices(); SalesDB db = new SalesDB(); public MainWindow() { InitializeComponent(); ServiceController service = new ServiceController("MSSQL$SQLEXPRESS"); if (service.Status != ServiceControllerStatus.Running) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } //var categories = db.Categories; //foreach (var item in categories) //{ // var salesSum = db.SalesCategories.Where(w => w.CategoryID == item.ID).Sum(s => s.Qty); // if (salesSum == null) // salesSum = 0; // var suppliesSum = db.SuppliesCategories.Where(w => w.CategoryID == item.ID).Sum(s => s.Qty); // if (suppliesSum == null) // suppliesSum = 0; // item.Qty = item.QtyStart + suppliesSum - salesSum; // db.Entry(item).State = EntityState.Modified; //} //db.SaveChanges(); Hide(); Splasher.Splash = new SplashScreenWindow(); Splasher.ShowSplash(); for (int i = 0; i < 100; i++) { if (i % 10 == 0) MessageListener.Instance.ReceiveMessage(string.Format("Loading " + "{0}" + " %", i)); Thread.Sleep(40); } Splasher.CloseSplash(); Show(); Closing += (s, e) => ViewModelLocator.Cleanup("Main"); } } }
using System.Collections.Generic; using iSukces.Code.Interfaces; namespace iSukces.Code.Irony { public abstract partial class RuleBuilder { public sealed class SequenceRule : RuleBuilder, IMap12 { public SequenceRule(IReadOnlyList<SequenceItem> expressions, IReadOnlyList<MapInfo> map) { Expressions = expressions; Map = map; } public IEnumerable<EnumerateTuple> Enumerate() { if (Map is null || Map.Count == 0) for (var index = 0; index < Expressions.Count; index++) { var i = Expressions[index]; yield return new EnumerateTuple(index, null, i.Expression); } else foreach (var map in Map) { var i = Expressions[map.RuleItemIndex]; yield return new EnumerateTuple(map.AstIndex, map, i.Expression); } } public override string GetCode(ITypeNameResolver resolver) { var tmp = GetCode(resolver, " + ", GetRuleExpressions()); return tmp; } private IEnumerable<ICsExpression> GetRuleExpressions() { foreach (var i in Expressions) foreach (var j in i.GetAll()) yield return j; } public IReadOnlyList<SequenceItem> Expressions { get; } public IReadOnlyList<MapInfo> Map { get; } public struct EnumerateTuple { public EnumerateTuple(int astIndex, MapInfo map, ICsExpression expression) { AstIndex = astIndex; Map = map; Expression = expression; } public int AstIndex { get; } public MapInfo Map { get; } public ICsExpression Expression { get; } } public sealed class SequenceItem { public SequenceItem(ICsExpression expression, IReadOnlyList<ICsExpression> hints) { if (hints != null && hints.Count == 0) hints = null; Expression = expression; Hints = hints; } public IReadOnlyList<ICsExpression> GetAll() { if (Hints is null) return new[] {Expression}; var l = new List<ICsExpression>(1 + Hints.Count); l.AddRange(Hints); l.Add(Expression); return l; } public ICsExpression Expression { get; } public IReadOnlyList<ICsExpression> Hints { get; } } } } }
using Newtonsoft.Json; namespace json_converter { public class PlcVar { public int id { get; set; } public string type { get; set; } public string name { get; set; } public object value { get; set; } [JsonIgnore] public object valueref { get; set; } } }
using System; namespace Juicy.WindowsService.UnitTest { class MockSchedTask : ScheduledTask { public MockSchedTask() { } protected override void Execute(DateTime scheduledDate) { Executed = true; } public bool Executed = false; } class MockPeriodTask : PeriodicalTask { public MockPeriodTask() { } public override void Execute() { Executed = true; } public bool Executed = false; } class NamedMockSchedTask : ScheduledTask { public NamedMockSchedTask(string name) : base(name) { } protected override void Execute(DateTime scheduledDate) { Executed = true; } public bool Executed = false; } class NamedMockPeriodTask : PeriodicalTask { public NamedMockPeriodTask(string name) : base(name) { } public override void Execute() { Executed = true; } public bool Executed = false; } }
using System.Collections; using System.Collections.Generic; namespace Quark { public class DynamicTags : IEnumerable<object> { private readonly Dictionary<string, int> _tagc; private readonly Dictionary<string, object> _tags; public DynamicTags() { _tagc = new Dictionary<string, int>(); _tags = new Dictionary<string, object>(); } public IEnumerator<object> GetEnumerator() { return _tags.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _tags.Values.GetEnumerator(); } public void Add(string key) { Add(key, true); } public void Add(string key, object value) { if (!Has(key)) _tagc.Add(key, 0); _tagc[key]++; _tags.Add(key, value); } public bool Has(string key) { return _tagc.ContainsKey(key) && _tagc[key] > 0; } public object Get(string key) { return _tags[key]; } public void Delete(string key) { if (!Has(key)) return; _tagc[key]--; if (_tagc[key] < 1) { _tags.Remove(key); _tagc.Remove(key); } } public bool this[string key] { get { return Has(key); } } public static DynamicTags operator +(DynamicTags collection, string tag) { collection.Add(tag); return collection; } public static DynamicTags operator -(DynamicTags collection, string tag) { collection.Delete(tag); return collection; } } public class StaticTags : IEnumerable<string> { private readonly Dictionary<string, int> _tags; public StaticTags() { _tags = new Dictionary<string, int>(); } public IEnumerator<string> GetEnumerator() { return _tags.Keys.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _tags.Keys.GetEnumerator(); } public void Add(string key) { _tags.Add(key, 1); } public bool Has(string key) { return _tags.ContainsKey(key); } public object Get(string key) { return _tags[key]; } public bool this[string key] { get { return Has(key); } } } public interface ITaggable : ITagged { DynamicTags Tags { get; } void Tag(string tag); void Tag(string tag, object value); void Untag(string tag); object GetTag(string tag); } public interface ITagged { bool IsTagged(string tag); } }
using System.Threading.Tasks; using DFC.ServiceTaxonomy.CustomFields.Fields; using DFC.ServiceTaxonomy.CustomFields.ViewModels; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.ContentTypes.Editors; using OrchardCore.DisplayManagement.Views; namespace DFC.ServiceTaxonomy.CustomFields.Settings { public class AccordionFieldSettingsDriver : ContentPartFieldDefinitionDisplayDriver<AccordionField> { public override IDisplayResult Edit(ContentPartFieldDefinition partFieldDefinition) { return Initialize<EditAccordionFieldSettingsViewModel>("AccordionFieldSettings_Edit", model => {}) .Location("Content"); } public override async Task<IDisplayResult> UpdateAsync(ContentPartFieldDefinition partFieldDefinition, UpdatePartFieldEditorContext context) { var model = new EditAccordionFieldSettingsViewModel(); if (await context.Updater.TryUpdateModelAsync(model, Prefix)) { context.Builder.WithSettings(new AccordionFieldSettings()); } return Edit(partFieldDefinition); } } }
using System; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core.Interops { public sealed partial class VlcManager { /// <summary> /// Set if, and how, the video title will be shown when media is played. /// </summary> /// <param name="mediaPlayerInstance">The media player instance</param> /// <param name="position">position at which to display the title, or libvlc_position_disable to prevent the title from being displayed</param> /// <param name="timeout">title display timeout in milliseconds (ignored if libvlc_position_disable)</param> public void SetVideoTitleDisplay(IntPtr mediaPlayerInstance, Position position, int timeout) { if (mediaPlayerInstance == IntPtr.Zero) throw new ArgumentException("Media player instance is not initialized."); myLibraryLoader.GetInteropDelegate<SetVideoTitleDisplay>().Invoke(mediaPlayerInstance, position, timeout); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Animation2D : MonoBehaviour { #region transform objcect protected GameObject m_cachedObject; public GameObject thisObject { get { if (m_cachedObject == null) m_cachedObject = gameObject; return m_cachedObject; } } protected Transform m_cachedTransform; public Transform thisTransform { get { if (m_cachedTransform == null) m_cachedTransform = transform; return m_cachedTransform; } } #endregion protected Actor m_owner; public Animator m_animator; public void Initialize() { m_owner = thisObject.GetComponent<Character>(); } //public void PlayAnimation(GameType.AnimationState state) //{ // m_animator.Play() //} #region 애니메이션 실행함수 public void OnMove(bool bMove) { m_animator.SetBool(GameType.AnimationState.Move.ToString(), bMove); } /// <summary> /// 공격 /// </summary> /// <param name="state"></param> public void OnAttack() { m_animator.SetTrigger("Attack"); } /// <summary> /// 점프 /// </summary> public void OnJump() { m_animator.SetTrigger(GameType.AnimationState.Jump.ToString()); } public void OnDamage() { m_animator.SetTrigger(GameType.AnimationState.Damage.ToString()); } /// <summary> /// 죽었을때 /// </summary> public void OnDead() { m_animator.SetBool(GameType.AnimationState.Dead.ToString(), true); } #endregion #region 애니메이션 확인함수 #endregion }
/** * Copyright (C) 2005-2014 by Rivello Multimedia Consulting (RMC). * code [at] RivelloMultimediaConsulting [dot] com * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and#or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // Marks the right margin of code ******************************************************************* //-------------------------------------- // Imports //-------------------------------------- using UnityEngine; using com.rmc.exceptions; using System.Collections; using com.rmc.projects.animation_monitor; //-------------------------------------- // Namespace //-------------------------------------- using com.rmc.projects.paddle_soccer.mvcs.model.data; using com.rmc.utilities; using com.rmc.projects.paddle_soccer.mvcs.view.ui; using com.rmc.projects.paddle_soccer.mvcs; namespace com.rmc.projects.paddle_soccer.components { //-------------------------------------- // Namespace Properties //-------------------------------------- public enum AnimationType { WALK, ATTACK, TAKE_HIT, DIE, IDLE, JUMP } //-------------------------------------- // Class Attributes //-------------------------------------- //-------------------------------------- // Class //-------------------------------------- public class PaddleComponent : MonoBehaviour { //-------------------------------------- // Properties //-------------------------------------- // GETTER / SETTER /// <summary> /// The _target y_float. /// </summary> public float targetY { get{ return _yPosition_lerptarget.targetValue; } set { _yPosition_lerptarget.targetValue = value; } } // PUBLIC /// <summary> /// When the type of the _animation. /// </summary> public AnimationType animationType; // PUBLIC STATIC // PRIVATE /// <summary> /// When the turret spinning_lerptarget. /// </summary> private LerpTarget _yPosition_lerptarget; /// <summary> /// When the animation. /// </summary> new private Animation animation; /// <summary> /// When the _animation binder. /// /// NOTE: Notifies when an animation is complete /// /// </summary> public AnimationMonitor animationMonitor; /// <summary> /// When the ANIMATION NAMES /// </summary> public const string ANIMATION_NAME_IDLE = "idle"; public const string ANIMATION_NAME_JUMP = "jump"; public const string ANIMATION_NAME_WALK = "walk"; public const string ANIMATION_NAME_ATTACK_1 = "attack1"; public const string ANIMATION_NAME_ATTACK_2 = "attack2"; public const string ANIMATION_NAME_HIT_1 = "hit1"; public const string ANIMATION_NAME_HIT_2 = "hit2"; public const string ANIMATION_NAME_DEATH_1 = "death1"; public const string ANIMATION_NAME_DEATH_2 = "death2"; /// <summary> /// When the _move speed_float. /// </summary> private float _moveSpeed_float; /// <summary> /// The _velocity_vector2. /// /// </summary> private Vector2 _velocity_vector2; /// <summary> /// The _last position_vector3. /// </summary> private Vector3 _lastPosition_vector3; // PRIVATE STATIC //-------------------------------------- // Methods //-------------------------------------- ///<summary> /// Use this for initialization ///</summary> public void Start () { animation = GetComponentInChildren<Animation>(); animationMonitor = GetComponentInChildren<AnimationMonitor>(); _yPosition_lerptarget = new LerpTarget (0, 0, -5, 5, 0.5f); } ///<summary> /// Called once per frame ///</summary> void Update () { //ROTATE THE BARREL IF FIRING if (true) { _yPosition_lerptarget.lerpCurrentToTarget (Time.deltaTime); _doMoveToTarget(); } } // PUBLIC /// <summary> /// Do play animation. /// </summary> /// <param name="aAnimationType">A animation type.</param> /// <param name="aDelayBeforeAnimation_float">A delay before animation_float.</param> /// <param name="aDelayAfterAnimation_float">A delay after animation_float.</param> public void doPlayAnimation (AnimationType aAnimationType, float aDelayBeforeAnimation_float, float aDelayAfterAnimation_float) { // animationType = aAnimationType; doStopAnimation(); // switch (animationType) { case AnimationType.JUMP: animationMonitor.playRequest ( new AnimationMonitorRequestVO (ANIMATION_NAME_JUMP, WrapMode.Default)); break; case AnimationType.WALK: animationMonitor.playRequest ( new AnimationMonitorRequestVO (ANIMATION_NAME_WALK, WrapMode.Loop)); break; default: #pragma warning disable 0162 throw new SwitchStatementException(); break; #pragma warning restore 0162 } } /// <summary> /// Do stop animation. /// </summary> public void doStopAnimation() { animation.Stop(); } /// <summary> /// Do tween to fall from sky. /// </summary> public void doTweenToFallFromSky () { // // Hashtable moveTo_hashtable = new Hashtable(); moveTo_hashtable.Add(iT.MoveTo.y, 0); moveTo_hashtable.Add(iT.MoveTo.delay, 0); moveTo_hashtable.Add(iT.MoveTo.time, 1); moveTo_hashtable.Add(iT.MoveTo.easetype, iTween.EaseType.linear); iTween.MoveTo (gameObject, moveTo_hashtable); } // PUBLIC STATIC // PRIVATE /// <summary> /// Do move to target. /// </summary> private void _doMoveToTarget () { // transform.position = new Vector3 ( transform.position.x, _getNewYPositionOnscreen(), transform.position.z); //STORE FOR VELOCITY CHECK _velocity_vector2 = transform.position - _lastPosition_vector3; _lastPosition_vector3 = transform.position; } /// <summary> /// _gets the new Y position onscreen. /// </summary> private float _getNewYPositionOnscreen () { float newYPosition_float = _yPosition_lerptarget.current; if (newYPosition_float < Constants.PADDLE_Y_MINIMUM) { newYPosition_float = Constants.PADDLE_Y_MINIMUM; _yPosition_lerptarget.targetValue = _yPosition_lerptarget.current; } else if (newYPosition_float > Constants.PADDLE_Y_MAXIMUM) { newYPosition_float = Constants.PADDLE_Y_MAXIMUM; _yPosition_lerptarget.targetValue = _yPosition_lerptarget.current; } return newYPosition_float; } // PRIVATE STATIC // PRIVATE COROUTINE // PRIVATE INVOKE //-------------------------------------- // Events // (This is a loose term for -- handling incoming messaging) // //-------------------------------------- /// <summary> /// Raises the collision enter2 d event. /// /// NOTE: This just detects soccer ball /// /// </summary> /// <param name="aCollision2D">A collision2 d.</param> public void OnCollisionEnter2D (Collision2D aCollision2D) { //Debug.Log (aCollision2D.collider.gameObject.tag); // if (aCollision2D.collider.gameObject.tag == SoccerBallUI.TAG) { // SoccerBallUI soccerBallUI = aCollision2D.collider.gameObject.GetComponent<SoccerBallUI>(); // soccerBallUI.doGiveEnglishFromPaddleVelocity (_velocity_vector2); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GangOfFourDesignPatterns.Behavioral.Observer { /// <summary> /// Subject contains a collection of observers that will /// receive notification when a Stock price change /// </summary> public abstract class ObservableStock { //objects following up changes ArrayList _observers; public ObservableStock() { _observers = new ArrayList(); } /// <summary> /// adds an observer interested in follow up /// subject / stock changes /// </summary> /// <param name="observer"></param> public void Add(IObserver observer) { _observers.Add(observer); } /// <summary> /// removes an observer /// </summary> /// <param name="observer"></param> public void Remove(IObserver observer) { _observers.Remove(observer); } public void Notifiy() { foreach (IObserver o in _observers) { o.Update(); } } } }
namespace iSukces.Code { public sealed class CsConditionsPair { public CsConditionsPair(string condition, string inversed = null) { Condition = condition; if (inversed is null) inversed = $"!({condition})"; Inversed = inversed; } public static CsConditionsPair FromInversed(string inversed) { return new CsConditionsPair($"!({inversed})", inversed); } public bool IsAlwaysTrue { get { return Condition == "true"; } } public bool IsAlwaysFalse { get { return Condition == "false"; } } public static CsConditionsPair FromIsNull(string variable) { return new CsConditionsPair($"{variable} is null"); } public static implicit operator CsConditionsPair(bool x) { return x ? new CsConditionsPair("true", "false") : new CsConditionsPair("false", "true"); } public override string ToString() { return $"Condition={Condition}, Inversed={Inversed}"; } public string Condition { get; } public string Inversed { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(UpdatableSettings), true)] public class UpdatableDataEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); UpdatableSettings data = (UpdatableSettings)target; if(CustomEditorGUI.Buttons.AddButton("Update data")) { data.NotifyUpdatedValues(); EditorUtility.SetDirty(target); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de SessionUser /// </summary> public class SessionUser { public SessionUser() { } }
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 Oracle.DataAccess.Client; using Oracle.DataAccess.Types; namespace ProjectDB2 { public partial class Send_Mail : MaterialSkin.Controls.MaterialForm { string constr = "Data source= orcl; User Id=scott;Password=tiger;"; OracleConnection conn; public static string mail_to; // public static string mail_from; public static int flag = 0; public static string msg; public Send_Mail() { InitializeComponent(); } private void Send_Mail_Load(object sender, EventArgs e) { conn = new OracleConnection(constr); conn.Open(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void panel1_Paint(object sender, PaintEventArgs e) { } private void materialFlatButton1_Click(object sender, EventArgs e) { int maxid, newid; OracleCommand cmd2 = new OracleCommand(); cmd2.Connection = conn; cmd2.CommandText = "GET_MAILINGID"; cmd2.CommandType = CommandType.StoredProcedure; cmd2.Parameters.Add("id", OracleDbType.Int32, ParameterDirection.Output); cmd2.ExecuteNonQuery(); try { maxid = Convert.ToInt32(cmd2.Parameters["id"].Value.ToString()); newid = maxid + 1; } catch { newid = 1; } OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandText = "INSERT_MAIL_INFO"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("id", newid); cmd.Parameters.Add("to", txt_to.Text); mail_to = txt_to.Text; cmd.Parameters.Add("from", Sign_In.mail_to); cmd.Parameters.Add("sub", txt_sub.Text); cmd.Parameters.Add("id", Sign_In.idd); cmd.Parameters.Add("msg", txt_msg.Text); mail_to = txt_to.Text; //mail_from = txt_from.Text; cmd.ExecuteNonQuery(); MessageBox.Show("Successfully Sending"); conn.Close(); this.Close(); } private void materialFlatButton2_Click(object sender, EventArgs e) { OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandText = "insert into draft values (:id,:drafted_mail,:mailTo,:subject)"; cmd.Parameters.Add("id", Sign_In.idd); cmd.Parameters.Add("drafted_mail", txt_msg.Text); cmd.Parameters.Add("mailTo", txt_to.Text); cmd.Parameters.Add("subject", txt_sub.Text); int n = cmd.ExecuteNonQuery(); if (n != -1) { MessageBox.Show("added to draft"); this.Close(); } } private void fileToolStripMenuItem_Click(object sender, EventArgs e) { } private void Send_Mail_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void newToolStripMenuItem_Click(object sender, EventArgs e) { } private void fileToolStripMenuItem_Click_1(object sender, EventArgs e) { } private void newToolStripMenuItem_Click_1(object sender, EventArgs e) { txt_msg.Clear(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void undoToolStripMenuItem_Click(object sender, EventArgs e) { txt_msg.Undo(); } private void redoToolStripMenuItem_Click(object sender, EventArgs e) { txt_msg.Redo(); } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { txt_msg.Cut(); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { txt_msg.Copy(); } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { txt_msg.Paste(); } private void selectAllToolStripMenuItem_Click(object sender, EventArgs e) { txt_msg.SelectAll(); } private void button1_Click(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Report re = new Report(); re.Show(); } } }
using BugTracker.DataAccessLayer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugTracker.BusinessLayer { class CompraService { CompraDao oCaompraDao; CompraService() { oCaompraDao = new CompraDao(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerCharacter : MonoBehaviour { public float moveSpeed; public float jumpSpeed; bool canJump = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey("left")){ Move("left"); } if (Input.GetKey("right")){ Move("right"); } if (Input.GetKey("up") && canJump){ Jump(); } } public void Move(string direction){ if(direction == "right"){ rigidbody2D.velocity = new Vector2(moveSpeed, rigidbody2D.velocity.y); } else if(direction == "left"){ rigidbody2D.velocity = new Vector2(moveSpeed * -1f, rigidbody2D.velocity.y); } } void OnCollisionEnter2D(Collision2D collision){ if(collision.gameObject.tag == "floor"){ canJump = true; } } void OnCollisionExit2D(Collision2D collision){ if(collision.gameObject.tag == "floor"){ canJump = false; } } void OnTriggerEnter2D(Collider2D collider){ if(collider.gameObject.tag == "poop"){ Jump(); collider.gameObject.SendMessage("Kill", ""); // kutsutaan kakan funktiota Kill //Destroy(collider.gameObject); } } public bool CanJump(){ return canJump; } public void Stop(){ rigidbody2D.velocity = new Vector2(0f, rigidbody2D.velocity.y); } public void Jump(){ rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, jumpSpeed); } }
using System.Threading.Tasks; using Airelax.Application.Houses; using Airelax.Application.Houses.Dtos.Request.ManageHouse; using Airelax.Application.ManageHouses.Request; using Airelax.Application.ManageHouses.Response; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Airelax.Controllers { [Route("[controller]")] [Authorize] public class ManageHouseController : Controller { private readonly IManageHouseService _manageHouseService; public ManageHouseController(IManageHouseService manageHouseService) { _manageHouseService = manageHouseService; } [HttpGet] [Route("all")] public IActionResult MyHousesDetail() { var myHousesViewModel = _manageHouseService.GetMyHouseViewModel(); return View(myHousesViewModel); } [HttpGet] [Route("{id}")] public async Task<IActionResult> IndexAsync(string id) { var manageInfo = await _manageHouseService.GetManageHouseInfo(id); if (manageInfo == null) return RedirectToAction("Index", "Error"); return View(manageInfo); } [HttpPut] [Route("{id}/Description")] public IActionResult UpdateDescription(string id, [FromBody] HouseDescriptionInput input) { var description = _manageHouseService.UpdateDescription(id, input); return Ok(description); } [HttpPut] [Route("{id}/Title")] public IActionResult UpdateTitle(string id, [FromBody] HouseTitleInput input) { var title = _manageHouseService.UpdateTitle(id, input); return Ok(title); } [HttpPut] [Route("{id}/CustomerNumber")] public IActionResult UpdateCustomerNumber(string id, [FromBody] CustomerNumberInput input) { var customerNumber = _manageHouseService.UpdateCustomerNumber(id, input); return Ok(customerNumber); } [HttpPut] [Route("{id}/Status")] public IActionResult UpdateStatus(string id, [FromBody] HouseStatusInput input) { var status = _manageHouseService.UpdateStatus(id, input); return Ok(status); } [HttpPut] [Route("{id}/Address")] public IActionResult UpdateAddress(string id, [FromBody] HouseAddressInput input) { var address = _manageHouseService.UpdateAddress(id, input); return Ok(address); } [HttpPut] [Route("{id}/Location")] public IActionResult UpdateLocation(string id, [FromBody] HouseLocationInupt input) { var location = _manageHouseService.UpdateLocation(id, input); return Ok(location); } [HttpPut] [Route("{id}/Category")] public IActionResult UpdateCategory(string id, [FromBody] HouseCategoryInput input) { var category = _manageHouseService.UpdateCategory(id, input); return Ok(category); } [HttpPut] [Route("{id}/Price")] public IActionResult UpdatePrice(string id, [FromBody] HousePriceInput input) { var price = _manageHouseService.UpdatePrice(id, input); return Ok(price); } [HttpPut] [Route("{id}/Cancel")] public IActionResult UpdateCancel(string id, [FromBody] CancelPolicyInput input) { var cancel = _manageHouseService.UpdateCancel(id, input); return Ok(cancel); } [HttpPut] [Route("{id}/RealTime")] public IActionResult UpdateRealTime(string id, [FromBody] RealTimeInput input) { var realTime = _manageHouseService.UpdateRealTime(id, input); return Ok(realTime); } [HttpPut] [Route("{id}/CheckTime")] public IActionResult UpdateCheckTime(string id, [FromBody] CheckTimeInput input) { var checkTime = _manageHouseService.UpdateCheckTime(id, input); return Ok(checkTime); } [HttpPut] [Route("{id}/Others")] public IActionResult UpdateOthers(string id, [FromBody] HouseOtherInput input) { var others = _manageHouseService.UpdateOthers(id, input); return Ok(others); } [HttpPut] [Route("{id}/Rules")] public IActionResult UpdateRules(string id, [FromBody] HouseRuleInput input) { var rules = _manageHouseService.UpdateRules(id, input); return Ok(rules); } [HttpPut] [Route("{id}/Facility")] public IActionResult UpdateFacility(string id, [FromBody] HouseFacilityInput input) { var facility = _manageHouseService.UpdateFacility(id, input); return Ok(facility); } [HttpPost] [Route("{id}/Space")] public IActionResult CreateSpace(string id, [FromBody] HouseSpaceInput input) { var space = _manageHouseService.CreateSpace(id, input); return Ok(space); } [HttpDelete] [Route("{id}/Space")] public IActionResult DeleteSpace(string id, [FromBody] HouseSpaceInput input) { var space = _manageHouseService.DeleteSpace(id, input); return Ok(space); } [HttpPost] [Route("{id}/BedroomDetail")] public IActionResult CreateBedroomDetail(string id, [FromBody] BedroomDetailInput input) { var bedroomDetail = _manageHouseService.CreateBedroomDetail(id, input); return Ok(bedroomDetail); } [HttpPut] [Route("{id}/BedroomDetail")] public IActionResult UpdateBedroomDetail(string id, [FromBody] BedroomDetailInput input) { var bedroomDetail = _manageHouseService.UpdateBedroomDetail(id, input); return Ok(bedroomDetail); } [HttpPost] [Route("{id}/pictures")] public async Task<UploadHouseImagesViewModel> UploadHouseImages(string id, [FromBody] UploadHouseImagesInput input) { return await _manageHouseService.UploadHouseImages(id, input); } } }
using RabbitMQ.Client.Service.Interfaces; using RabbitMQ.Client.Service.Options; using System; using System.Collections.Generic; using System.Text; namespace RabbitMQ.Client.Service.Implementations { public class Publisher : IPublisher { private readonly IAMQPChannelProvider _amqpChannelProvider; private readonly IModel _amqpChannel; public Publisher(IAMQPChannelProvider aMQPChannelProvider) { _amqpChannelProvider = aMQPChannelProvider; _amqpChannel = _amqpChannelProvider.GetAMQPChannel(); } public void PublishMessage(ExchangeOptions exchangeOptions, string message, Dictionary<string, object> messageAttributes = null, string timeToLive = "30000") { byte[] messageBodyBytes = Encoding.UTF8.GetBytes(message); _amqpChannel.ExchangeDeclare(exchangeOptions.Name, exchangeOptions.Type.ToString().ToLower(), exchangeOptions.Durable, exchangeOptions.AutoDelete); IBasicProperties basicProperties = _amqpChannel.CreateBasicProperties(); basicProperties.DeliveryMode = 2; basicProperties.Persistent = true; basicProperties.Expiration = timeToLive; basicProperties.ContentType = "application/json"; if (messageAttributes is not null) { basicProperties.Headers = messageAttributes; } _amqpChannel.BasicPublish(exchangeOptions.Name, exchangeOptions.RoutingKey, basicProperties, messageBodyBytes); } public void Dispose() { _amqpChannelProvider.Dispose(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Btn_level2_0 : BasePanel { Animator animator; private void Start() { animator = GetComponent<Animator>(); GetComponent<Button>().onClick.AddListener(BtnClick); } private void BtnClick() { EventCenter.GetInstance().EventTrigger<string>(EventDic.MainMenuLevelBtnClick, gameObject.name); //throw new NotImplementedException(); } public void Init() { Debug.Log("b"); animator.Play("Enter"); GetControl<Text>("Text_Level").text = this.gameObject.name; bool useAble = GameRoot.instance.playerModel.UnlockLevelList.Contains(this.gameObject.name); if (!useAble) { GetComponent<CanvasGroup>().alpha = 0.5f; GetComponent<Button>().interactable = false; } else { GetComponent<CanvasGroup>().alpha = 1f; GetComponent<Button>().interactable = true; } SetStart(); } public GameObject Stars; private void SetStart() { int tempInt = PlayerModelController.GetInstance().GetLevelStarDic(this.gameObject.name); for (int i = 0; i < tempInt; i++) { Stars.transform.GetChild(i).gameObject.SetActive(true); } } }
using UnityEngine; [System.Serializable] public struct LODInfo { [Range(0, MeshSettings.numSupportedLODs - 1)] public int lod; public float visibleDistanceThreshold; public float sqrVisibleDstTresh { get { return visibleDistanceThreshold * visibleDistanceThreshold; } } }
using System; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Breeze.FontSystem { public static class MDL2SymbolsExtension { public static string AsChar(this MDL2Symbols symb) { return ((char)symb).ToString(); } } public enum MDL2Symbols { MenuMore = '\uE26B', Caret = '\uE933', Tape = '\uE96A', TickBox = 61804 , Box = 61803, Finger = '\uf271', Lock = '\ue1F6', UnLock = '\ue1F7', Resize = '\uf0d8', BulletPoint = '\ue1F5', Accept = '\ue10b', Account = '\ue168', Add = '\ue109', AddFriend = '\ue1e2', Admin = '\ue1a7', AlignCenter = '\ue1a1', AlignLeft = '\ue1a2', AlignRight = '\ue1a0', AllApps = '\ue179', Attach = '\ue16c', AttachCamera = '\ue12d', Audio = '\ue189', Back = '\ue112', BackToWindow = '\ue1d8', BlockContact = '\ue1e0', Bold = '\ue19b', Bookmarks = '\ue12f', BrowsePhotos = '\ue155', Bullets = '\ue133', Calculator = '\ue1d0', Calendar = '\ue163', CalendarDay = '\ue161', CalendarReply = '\ue1db', CalendarWeek = '\ue162', Camera = '\ue114', Cancel = '\ue10a', Caption = '\ue15a', CellPhone = '\ue1c9', Character = '\ue164', Clear = '\ue106', ClearSelection = '\ue1c5', Clock = '\ue121', ClosedCaption = '\ue190', ClosePane = '\ue127', ClosePane2 = '\uef2c', ClosePaneMirrored = '\ueA49', Comment = '\ue134', Contact = '\ue13d', Contact2 = '\ue187', ContactInfo = '\ue136', ContactPresence = '\ue181', Copy = '\ue16f', Crop = '\ue123', Cut = '\ue16b', Delete = '\ue107', Directions = '\ue1d1', DisableUpdates = '\ue194', DisconnectDrive = '\ue17a', Dislike = '\ue19e', DockBottom = '\ue147', DockLeft = '\ue145', DockRight = '\ue146', Document = '\ue130', Download = '\ue118', Edit = '\ue104', Emoji = '\ue11d', Emoji2 = '\ue170', Favorite = '\ue113', Filter = '\ue16e', Find = '\ue11a', Flag = '\ue129', Folder = '\ue188', Font = '\ue185', FontColor = '\ue186', FontDecrease = '\ue1c6', FontIncrease = '\ue1c7', FontSize = '\ue1c8', Forward = '\ue111', FourBars = '\ue1e9', FullScreen = '\ue1d9', GlobalNavigationButton = '\ue700', Globe = '\ue12b', Go = '\ue143', GoToStart = '\ue1e4', GoToToday = '\ue184', HangUp = '\ue137', Help = '\ue11b', HideBcc = '\ue16a', Highlight = '\ue193', Home = '\ue10f', Import = '\ue150', ImportAll = '\ue151', Important = '\ue171', Italic = '\ue199', Keyboard = '\ue144', LeaveChat = '\ue11f', Library = '\ue1d3', Like = '\ue19f', LikeDislike = '\ue19d', Link = '\ue167', List = '\ue14c', Mail = '\ue119', MailFilled = '\ue135', MailForward = '\ue120', MailReply = '\ue172', MailReplyAll = '\ue165', Manage = '\ue178', Map = '\ue1c4', MapDrive = '\ue17b', MapPin = '\ue139', Memo = '\ue1d5', Message = '\ue15f', Microphone = '\ue1d6', More = '\ue10c', MousePointer = '\ue8b0', MoveToFolder = '\ue19c', MusicInfo = '\ue142', Mute = '\ue198', NewFolder = '\ue1da', NewWindow = '\ue17c', Next = '\ue101', OneBar = '\ue1e6', OpenFile = '\ue1a5', OpenLocal = '\ue197', OpenPane = '\ue126', OpenPaneMirrored = '\uea5B', OpenWith = '\ue17d', Orientation = '\ue14f', OtherUser = '\ue1a6', OutlineStar = '\ue1ce', Page = '\ue132', Page2 = '\ue160', Paste = '\ue16d', Pause = '\ue103', People = '\ue125', Permissions = '\ue192', Phone = '\ue13a', PhoneBook = '\ue1d4', Pictures = '\ue158', Pin = '\ue141', Placeholder = '\ue18a', Play = '\ue102', PostUpdate = '\ue1d7', Preview = '\ue295', PreviewLink = '\ue12a', Previous = '\ue100', Print = '\ue749', Priority = '\ue182', ProtectedDocument = '\ue131', Read = '\ue166', Redo = '\ue10d', Refresh = '\ue149', Remote = '\ue148', Relationship = '\uf003', Remove = '\ue108', Rename = '\ue13e', Repair = '\ue15e', RepeatAll = '\ue1cd', RepeatOne = '\ue1cc', ReportHacked = '\ue1de', ReShare = '\ue1ca', Rotate = '\ue14a', RotateCamera = '\ue124', Save = '\ue105', SaveLocal = '\ue159', Scan = '\ue294', SelectAll = '\ue14e', Send = '\ue122', SetLockScreen = '\ue18c', SetTile = '\ue18d', Setting = '\ue115', Share = '\ue72d', Shop = '\ue14d', ShowBcc = '\ue169', ShowResults = '\ue15c', Shuffle = '\ue14b', SlideShow = '\ue173', SolidStar = '\ue1cf', Sort = '\ue174', Stop = '\ue15b', StopSlideShow = '\ue191', Street = '\ue1c3', Switch = '\ue13c', SwitchApps = '\ue1e1', Sync = '\ue117', SyncFolder = '\ue1df', Tag = '\ue1cb', Target = '\ue1d2', ThreeBars = '\ue1e8', TouchPointer = '\ue1e3', Trim = '\ue12c', TwoBars = '\ue1e7', TwoPage = '\ue11e', Underline = '\ue19a', Undo = '\ue10e', UnFavorite = '\ue195', UnPin = '\ue196', UnSyncFolder = '\ue1dd', Up = '\ue110', Upload = '\ue11c', Video = '\ue116', VideoChat = '\ue138', View = '\ue18b', ViewAll = '\ue138', Volume = '\ue15d', WebCam = '\ue156', World = '\ue128', XboxOneConsole = '\ue990', ZeroBars = '\ue1e5', Zoom = '\ue1a3', ZoomIn = '\ue12e', ZoomOut = '\ue1a4' } }
using Unity.Entities; using UnityEngine; namespace ECS.Hybrid.Systems { public class PlayerFiringSystem : ComponentSystem { private struct Filter { public InputComponent InputComponent; } protected override void OnUpdate() { if (Input.GetMouseButtonDown(0)) { RaycastHit hit; var ray = Camera.main.ScreenPointToRay(Input.mousePosition); foreach (var entity in GetEntities<Filter>()) { if (entity.InputComponent.isFired == false && Physics.Raycast(ray, out hit)) { if (hit.transform.tag == "Player") { entity.InputComponent.isFired = true; entity.InputComponent.startFireTime = Time.time; Object.Instantiate(entity.InputComponent.BulletPrefab,hit.collider.attachedRigidbody.transform.position,hit.collider.attachedRigidbody.transform.rotation); } } } } } } }
using System; using Grasshopper.Kernel; using PterodactylRh; using PterodactylEngine; using System.Drawing; namespace Pterodactyl { public class ViewportGH : GH_Component { public ViewportGH() : base("Viewport", "Viewport", "Capture selected Rhino viewport and insert to report as image. THIS COMPONENT IS NOT SUPPORTED ON THE SHAPEDIVER PLATFORM", "Pterodactyl", "Parts") { } public override bool IsBakeCapable => false; protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddTextParameter("Title", "Title", "Title image", GH_ParamAccess.item, "Example"); pManager.AddTextParameter("Viewport Name", "Viewport Name", "Name of the viewport", GH_ParamAccess.item); //pManager.AddTextParameter("Path", "Path", "Directory where image of your viewport will be saved. Should end up with .png", // GH_ParamAccess.item); pManager.AddBooleanParameter("Draw Axes", "Draw Axes", "Boolean, true = draw axes", GH_ParamAccess.item, false); pManager.AddBooleanParameter("Draw Grid", "Draw Grid", "Boolean, true = draw grid", GH_ParamAccess.item, false); pManager.AddBooleanParameter("Draw Grid Axes", "Draw Grid Axes", "Boolean, true = draw grid axes", GH_ParamAccess.item, false); pManager.AddBooleanParameter("Transparent Background", "Transparent Background", "Boolean, true = transparent background", GH_ParamAccess.item, true); } protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddParameter(new PterodactylGrasshopperBitmapParam(), "Report Part", "Report Part", "Created part of the report (Markdown text with referenced Image)", GH_ParamAccess.item); } protected override void SolveInstance(IGH_DataAccess DA) { string title = string.Empty; string viewportName = string.Empty; bool drawAxes = false; bool drawGrid = false; bool drawGridAxes = false; bool transparentBackground = true; DA.GetData(0, ref title); DA.GetData(1, ref viewportName); DA.GetData(2, ref drawAxes); DA.GetData(3, ref drawGrid); DA.GetData(4, ref drawGridAxes); DA.GetData(5, ref transparentBackground); VieportRh reportDocument = new VieportRh(); PterodactylGrasshopperBitmapGoo GH_bmp = new PterodactylGrasshopperBitmapGoo(); PterodactylEngine.Image reportObject = new PterodactylEngine.Image(title, GH_bmp.ReferenceTag); using (System.Drawing.Bitmap b = reportDocument.CaptureToBitmap(viewportName, drawAxes, drawGrid, drawGridAxes, transparentBackground)) { GH_bmp.Value = b.Clone(new Rectangle(0, 0, b.Width, b.Height), b.PixelFormat); GH_bmp.ReportPart = reportObject.Create(); DA.SetData(0, GH_bmp); } } protected override System.Drawing.Bitmap Icon { get { return Properties.Resources.PterodactylViewport; } } public override GH_Exposure Exposure { get { return GH_Exposure.quarternary; } } public override Guid ComponentGuid { get { return new Guid("8b413c79-f96e-4fad-9cd9-80f7d9989f8a"); } } } }
using Alabo.Web.Mvc.Attributes; namespace Alabo.Cloud.Shop.Footprints.Domain.Enums { /// <summary> /// 足迹类型 /// </summary> [ClassProperty(Name = "足迹类型")] public enum FootprintType { /// <summary> /// 商品收藏 /// </summary> Product = 1, /// <summary> /// 店铺收藏 /// </summary> Store = 2, /// <summary> /// 用户收藏 /// </summary> User = 3, /// <summary> /// 文章收藏 /// </summary> Article = 4 } }
using System; using System.Windows.Forms; using MSProject = Microsoft.Office.Interop.MSProject; namespace Project_PERT_Add_in_2016 { public partial class frmCalcularPERT : Form { public frmCalcularPERT() { InitializeComponent(); if (Properties.Settings.Default.Language.ToString() == "English") { this.Text = "PERT Analysis"; lblGeral1.Text = "The PERT analysis uses the information contained in \"Dur. optimistic\", \"Dur. expected\"and \"Dur. pessimistic\". These values are stored in the Duration1, Duration2 and Duration3 respectively. Click \"Yes\" to recalculate the field \"Duration\" based on these three fields."; lblGeral2.Text = "Want to continue?"; btnSim.Text = "Yes"; btnNao.Text = "No"; } else if (Properties.Settings.Default.Language.ToString() == "Italian") { this.Text = "Analisi PERT"; lblGeral1.Text = "L' analisi PERT utilizza le informazioni contenute nei campi \"Dur. ottimistica\", \"Dur. prevista\", e \"Durata pessimistica\". Questi valori vengono memorizzati rispettivamente nei campi personalizzati \"Durata 1\", \"Durata 2\" e \"Durata 3\". Clicca \"Si\" per ricalcolare il campo \"Durata\", basandolo sui valori di questi tre campi."; lblGeral2.Text = "Continuare ?"; btnSim.Text = "Si"; btnNao.Text = "No"; } else if (Properties.Settings.Default.Language.ToString() == "Spanish") { this.Text = "Análisis PERT"; lblGeral1.Text = "El Análisis PERT utiliza la información contenida en los campos \"Dur. optimista\", \"Dur. esperada\" y \"Dur. pesimista\". Los valores se guardan en los campos Duración1, Duración2 y Duración3 respectivamente. Al hacer clic en Sí re recalcula el valor del campo Duración tomando base los de estos tres campos."; lblGeral2.Text = "¿Desea continuar?"; btnSim.Text = "Sí"; btnNao.Text = "No"; } else if (Properties.Settings.Default.Language.ToString() == "French") { this.Text = "Analyse PERT"; lblGeral1.Text = "L'analyse PERT utilise les informations contenues dans \"Dur. Optimiste\", \"Durée Prob.\" et \"Durée Pes.\". Ces valeurs sont stockées respectivement dans Durée1, Durée2 et Durée3. Cliquer sur \"Oui\" pour recalculer les champs \"Durée\" à partir de ces 3 champs."; lblGeral2.Text = "Voulez-vous continuer?"; btnSim.Text = "Oui"; btnNao.Text = "Non"; } else { this.Text = "Análise PERT"; lblGeral1.Text = "A análise PERT usa as informações contidas em \"Dur. otimista\", \"Dur. esperada\" e \"Dur. pessimista\". Esses valores são armazenados nos campos Duração1, Duração2 e Duração3 respectivamente. Clique em \"Sim\" para recalcular o campo \"Duração\" baseado nesses três campos."; lblGeral2.Text = "Deseja continuar?"; btnSim.Text = "Sim"; btnNao.Text = "Não"; } } private void btnSim_Click(object sender, EventArgs e) { MSProject.Project proj = Globals.ThisAddIn.Application.ActiveProject; try { double iOtimista = proj.ProjectSummaryTask.Number1; double iEsperada = proj.ProjectSummaryTask.Number2; double iPessimista = proj.ProjectSummaryTask.Number3; if (iOtimista + iEsperada + iPessimista != 6) { iOtimista = 1; iEsperada = 4; iPessimista = 1; } foreach (MSProject.Task tskT in proj.Tasks) { if ((tskT.PercentComplete == 0) & (tskT.PercentWorkComplete == 0) & (tskT.Duration1 + tskT.Duration2 + tskT.Duration3 != 0)) { tskT.Duration = ((((tskT.Duration1) * iOtimista) + ((tskT.Duration2) * iEsperada) + ((tskT.Duration3) * iPessimista)) / 6); } } } catch (System.Exception Ex) { MessageBox.Show(Ex.Message); } this.Close(); } private void btnNao_Click(object sender, EventArgs e) { this.Close(); } } }
using System.Windows.Controls; namespace WPF.NewClientl.UI.Dialogs { public partial class MeetingLoadingDialog : UserControl { public MeetingLoadingDialog() { InitializeComponent(); } } }
using System; using System.Linq; using System.Threading.Tasks; using LinqToSqlWrongDistinctClauseReproduction.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Logging; namespace LinqToSqlWrongDistinctClauseReproduction { public class Program { public static void Main(string[] args) { MainAsync().Wait(); } public static async Task MainAsync() { var itemsPerPage = 15; var page = 0; var dbContextFactory = new ApplicationDbContextFactory(); using (var context = dbContextFactory.Create(new DbContextFactoryOptions())) { var query = Filter(context.RunResults, "someUserId", null, null) .Select(x => x.Property) .Distinct() .OrderByDescending(x => x.CreationDate); var nbItems = await query.CountAsync(); var items = await query .Select(x => new PropertyRowViewModel { Id = x.Id, Source = x.Source, ForeignId = x.ForeignId, CreationDate = x.CreationDate, LastUpdate = x.LastUpdate, RemovalDate = x.RemovalDate, Details = x.Details, IsRemoved = x.IsRemoved }) .Skip(page * itemsPerPage) .Take(itemsPerPage) .ToListAsync(); Console.ReadLine(); } } public static IQueryable<QueryRunResult> Filter(IQueryable<QueryRunResult> input, string userId, Guid? queryDefinitionId, Guid? queryRunId) { // Always filter on UserId var query = input.Where(x => x.QueryRun.QueryDefinition.UserId == userId); if (queryDefinitionId.HasValue) { query = query.Where(x => x.QueryRun.QueryDefinitionId == queryDefinitionId.Value); } if (queryRunId.HasValue) { query = query.Where(x => x.QueryRunId == queryRunId.Value); } return query; } public class ApplicationDbContextFactory : IDbContextFactory<ApplicationDbContext> { public ApplicationDbContext Create(DbContextFactoryOptions options) { var connectionString = "Server=(localdb)\\mssqllocaldb;Database=LinqToSqlWrongDistinctClauseReproduction;Trusted_Connection=True;MultipleActiveResultSets=true"; var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug((origin, ll) => { return origin == "Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory"; }); var contextOptions = new DbContextOptionsBuilder<ApplicationDbContext>() .UseSqlServer(connectionString) .UseLoggerFactory(loggerFactory) .Options; return new ApplicationDbContext(contextOptions); } } } public class PropertyRowViewModel { public Guid Id { get; set; } public DataSource Source { get; set; } public string ForeignId { get; set; } public DateTime CreationDate { get; set; } public DateTime? LastUpdate { get; set; } public DateTime? RemovalDate { get; set; } public string Details { get; set; } public bool IsRemoved { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Unidade10.Fixacao { class IRPF { public static double Irpf(double salarioBruto,double reducao,double previdencia,double dependente,double INSS, double salario, double irpff) { INSS = 0.11; dependente = 150.69; previdencia = 0.10; salarioBruto = salario; salario = salario / INSS; salario = salario / dependente; salario = salario / previdencia; reducao = salario; salarioBruto -= salario; salarioBruto = irpff; return irpff; } static void Main231(string[] args) { double salarioBruto = 0; double reducao = 0; double previdencia = 0; double dependente = 0; double INSS = 0; double irpff = 0; Console.WriteLine("Salario: "); double salario = Convert.ToDouble(Console.ReadLine()); double result = Irpf(salarioBruto, reducao, previdencia, dependente, INSS, salario, irpff); Console.WriteLine(result); } } }
using Microsoft.EntityFrameworkCore; using Practise.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Practise.Infrastructure { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options): base(options) { } public DbSet<Employee> Employee { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } }
using System.ComponentModel.DataAnnotations; using Profiling2.Domain.Prf.Sources; namespace Profiling2.Web.Mvc.Areas.Hrdb.Controllers.ViewModels { public class JhroCaseViewModel { public int Id { get; set; } [Required(ErrorMessage = "The case code is required.")] public string CaseNumber { get; set; } public JhroCaseViewModel() { } public JhroCaseViewModel(JhroCase jhroCase) { if (jhroCase != null) { this.Id = jhroCase.Id; this.CaseNumber = jhroCase.CaseNumber; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Graph { class Graph { private const int NUM_VERTICES = 8; private Vertex[] vertices; private int[,] adjMatrix; int numVerts; public Graph() { vertices = new Vertex[NUM_VERTICES]; adjMatrix = new int[NUM_VERTICES, NUM_VERTICES]; numVerts = 0; for (int j = 0; j < NUM_VERTICES; j++) for (int k = 0; k < NUM_VERTICES ; k++) adjMatrix[j, k] = 0; } public void AddVertex(string label) { vertices[numVerts] = new Vertex(label); numVerts++; } public void AddEdge(string LabelOrigin, string LabelEnd) { int? indexOrigin = this.getIndex(LabelOrigin); int? indexEnd = this.getIndex(LabelEnd); if (indexOrigin.HasValue && indexEnd.HasValue) { AddEdge((int)indexOrigin,(int)indexEnd); } } public int? getIndex(string label) { for (int i = 0; i < this.vertices.Length; i++) { Vertex v= (Vertex)vertices[i]; if (v.label == label) return i; } return null; } public void AddEdge(int start, int eend) { adjMatrix[start, eend] = 1; adjMatrix[eend, start] = 1; } public void ShowVertex(int v) { Console.Write(vertices[v].label + " "); Console.WriteLine(""); Console.ReadKey(); } public int GetAdjUnvisitedVertex(int v) { for (int j = 0; j <= NUM_VERTICES - 1; j++) if ((adjMatrix[v, j] == 1) && (vertices[j].visited== false)) return j; return -1; } public void dsf() { Stack<int> stack = new Stack<int>(); Console.WriteLine("Pushing the starting vertex {0} to the stack", vertices[0].label); vertices[0].visited = true; ShowVertex(0); stack.Push(0); int v; while (stack.Count > 0) { int peek = stack.Peek(); Console.WriteLine("Peak is {0} ", vertices[peek].label); Console.ReadKey(); v = GetAdjUnvisitedVertex(peek); if (v == -1) { int p = stack.Pop(); Console.WriteLine("No adjacent unvisited vertices found, popping <--{0}",vertices[p]); } else { Console.WriteLine("Found {0} which is {1}", v, vertices[v].label); Console.ReadKey(); vertices[v].visited = true; ShowVertex(v); Console.WriteLine("Pushing {0} to the stack",vertices[v].label); stack.Push(v); } } } public void showMatrix() { string []a={"A","B","C","D","E","F","G","H"}; Console.WriteLine(""); Console.Write(" "); for (int i = 0; i < NUM_VERTICES; i++) { Console.Write("{0} ", a[i]); } Console.WriteLine(""); for (int i = 0; i < NUM_VERTICES; i++) { Console.Write("{0}",a[i]); for (int j = 0; j < NUM_VERTICES; j++) { Console.Write("[{0}] ",adjMatrix[i,j]); } Console.WriteLine(""); } } public void beathsearchfirst() { Queue<int> queue = new Queue<int>(); vertices[0].visited = true; ShowVertex(0); queue.Enqueue(0); while (queue.Count > 0) { int vert = queue.Dequeue(); int vert2 = GetAdjUnvisitedVertex(vert); while (vert2 != -1) { vertices[vert2].visited = true; ShowVertex(vert2); queue.Enqueue(vert2); vert2 = GetAdjUnvisitedVertex(vert); } } } } }
using System; namespace Week1b { class MainClass { public static void Main (string[] args) { int a = 1; int b = 5; int c = -30; a = a + 1; a += 1; Console.WriteLine (a); a -= 1; a *= 4; a /= 2; Console.WriteLine (a); a = 10; int remainder = a % 3; Console.WriteLine (remainder); int days = 700; int years = days / 365; int daysLeftover = days % 365; Console.WriteLine ("in " + days + " days there is " + years + " year/s and " + daysLeftover + " days remainder"); a = 4; b = 10; c = -3; // 40 // -8 // 77 // -26 int total = a * b; Console.WriteLine (total); total = a + a * c; Console.WriteLine (total); total = (b + b) * a + c; Console.WriteLine (total); total = a + a - a + c * b; Console.WriteLine (total); int data = 0; data++; // This is postfix, the increase happens at the end of use; Console.WriteLine (data); ++data; // This is prefix, the increase happens before use; Console.WriteLine (data); data++; ++data; Console.WriteLine (++data); Console.WriteLine (data++); Console.WriteLine (data); // 5 // 12 // 6 // 10 total = ++a; Console.WriteLine (total); total = a++ + ++a; Console.WriteLine (total); total = b + --c; Console.WriteLine (total); total = a + b++ - c + b; Console.WriteLine (total); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task3 { class Program { static void Main(string[] args) { Console.WriteLine("Task 3\n"); Dictionary<int, string> dict = new Dictionary<int, string>(); string input; // Get values for dictionary for (int i = 0; i < 10; i++) { Console.Write("Enter value: "); input = Console.ReadLine(); dict.Add(i, input); } // Copy to array and show string[] arr = new string[dict.Count]; dict.Values.CopyTo(arr, 0); Console.WriteLine("\nArray\n"); foreach(string s in arr) { Console.WriteLine($"Value: {s}"); } Console.WriteLine(); } } }
using System.Collections.Generic; //************************************************************************* //@header EventManager //@abstract Manage event. //@discussion Provide functions like PublishEvent, AddListener and RemoveListener . //@version v1.0.0 //@author Felix Zhang //@copyright Copyright (c) 2017 FFTAI Co.,Ltd.All rights reserved. //************************************************************************** namespace FZ.HiddenObjectGame { public class EventManager { EventManager() { _dicPool = new Dictionary<EventType, EventCallback>(); } #region Fields Dictionary<EventType, EventCallback> _dicPool; #endregion #region Instance static EventManager _instance; public static EventManager Instance { get { if (_instance == null) _instance = new EventManager(); return _instance; } } #endregion // Each AddListener also needs to be Removed by RemoveListener. Or it may cause unpreditable problems. public void AddListener(EventType eventType, EventCallback eventCallback) { if (_dicPool.ContainsKey(eventType)) { _dicPool[eventType] = _dicPool[eventType] == null ? eventCallback : _dicPool[eventType] + eventCallback; } else { _dicPool.Add(eventType, eventCallback); } } public void RemoveListener(EventType eventType, EventCallback eventCallback) { if (_dicPool.ContainsKey(eventType)) { _dicPool[eventType] = _dicPool[eventType] == null ? null : _dicPool[eventType] - eventCallback; if (_dicPool[eventType] == null) _dicPool.Remove(eventType); } } public void RemoveListener(EventType eventType) { if (_dicPool.ContainsKey(eventType)) { _dicPool[eventType] = null; _dicPool.Remove(eventType); } } public void PublishEvent(EventType eventType, EventData eventData) { if (_dicPool.ContainsKey(eventType)) { if (_dicPool[eventType] != null) _dicPool[eventType](eventData); } } } }
using System.Globalization; using CRMSecurityProvider.Sources.Attribute; using Microsoft.Xrm.Sdk; namespace AlphaSolutions.SitecoreCms.ExtendedCRMProvider.Sources.Repository.V5.Attribute { internal class CrmMoneyAttributeAdapter : CrmAttributeAdapter<Money>, ICrmDecimalAttribute, ICrmAttribute<decimal>, ICrmAttribute { public CrmMoneyAttributeAdapter(CrmAttributeCollectionAdapter crmAttributeCollection, Money internalAttribute) : base(crmAttributeCollection, internalAttribute) { } public override string GetStringifiedValue() { return this.Value.ToString(CultureInfo.InvariantCulture); } public override void SetValue(string value, params string[] data) { decimal num; if (decimal.TryParse(value, out num)) { base.Adaptee.Value = num; } } public decimal Value { get { return base.Adaptee.Value; } } } }
using System; using System.Collections.Generic; using System.Text; namespace Contracts { public interface IExploit { void Initialize(Threat threat); void Exploit(); } }
using System; using System.Collections.Generic; using System.Linq; using iSukces.Code.Interfaces; namespace iSukces.Code { public class CsAttribute : ClassMemberBase, ICsAttribute { public CsAttribute(string name) { Name = AttributableExt.CutAttributeSuffix(name); } public static CsAttribute Make<T>(ITypeNameResolver typeNameResolver) { return new CsAttribute(typeNameResolver.GetTypeName(typeof(T))); } public static implicit operator string(CsAttribute a) { return a.ToString(); } public static implicit operator CsAttribute(string name) { return new CsAttribute(name); } private static string Encode(object value) { switch (value) { case null: return "null"; case bool aBool: return aBool ? "true" : "false"; case int intValue: return intValue.ToCsString(); case uint uintValue: return uintValue.ToCsString() + "u"; case long longValue: return longValue.ToCsString() + "l"; case ulong ulongValue: return ulongValue.ToCsString() + "ul"; case byte byteValue: return "(byte)" + byteValue.ToCsString(); case sbyte sbyteValue: return "(sbyte)" + sbyteValue.ToCsString(); case double doubleValue: return doubleValue.ToCsString() + "d"; case decimal decimalValue: return decimalValue.ToCsString() + "m"; case float floatValue: return floatValue.ToCsString() + "f"; case Guid gValue: if (gValue.Equals(Guid.Empty)) return "System.Guid.Empty"; return "System.Guid.Parse(" + gValue.ToString("D").CsEncode() + ")"; case string aString: return aString.CsEncode(); case IDirectCode aDirectCode: return aDirectCode.Code; default: throw new NotSupportedException(value.GetType().ToString()); } } private static string KeyValuePairToString(KeyValuePair<string, string> x) { return string.IsNullOrEmpty(x.Key) ? x.Value : string.Format("{0} = {1}", x.Key, x.Value); } public override string ToString() { var values = _list.Select(KeyValuePairToString).ToArray(); var name = Name; if (name.EndsWith(AttributeSuffix, StringComparison.Ordinal)) if (!name.Contains('.')) name = name.Substring(0, name.Length - AttributeSuffixLength); if (values.Length == 0) return name; return string.Format("{0}({1})", name, string.Join(", ", values)); } public CsAttribute WithArgument(object value) { return WithArgument("", value); } public CsAttribute WithArgument(string name, object value) { var sValue = Encode(value); return WithArgumentCode(name, sValue); } public CsAttribute WithArgumentCode(string valueCode) { return WithArgumentCode("", valueCode); } public CsAttribute WithArgumentCode(string name, string valueCode) { name = (name ?? "").Trim(); _list.Add(new KeyValuePair<string, string>(name, valueCode)); return this; } public string Name { get; set; } public string Code { get { if (_list == null || _list.Count == 0) return Name; return string.Format("{0}({1})", Name, string.Join(",", _list.Select(KeyValuePairToString))); } } private static readonly int AttributeSuffixLength = AttributeSuffix.Length; private readonly List<KeyValuePair<string, string>> _list = new List<KeyValuePair<string, string>>(); private const string AttributeSuffix = "Attribute"; } }
/** * @author Looxidlabs * @version 1.0 */ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Looxid.Link { public class LooxidLinkManager : MonoBehaviour { #region Singleton private static LooxidLinkManager _instance; public static LooxidLinkManager Instance { get { if (_instance == null) { _instance = FindObjectOfType(typeof(LooxidLinkManager)) as LooxidLinkManager; if (_instance == null) { _instance = new GameObject("LooxidLinkManager").AddComponent<LooxidLinkManager>(); DontDestroyOnLoad(_instance.gameObject); } } return _instance; } } #endregion #region Variables private NetworkManager networkManager; private LinkCoreStatus linkCoreStatus = LinkCoreStatus.Disconnected; private LinkHubStatus linkHubStatus = LinkHubStatus.Disconnected; private bool isInitialized = false; [HideInInspector] public bool isLinkCoreConnected = false; [HideInInspector] public bool isLinkHubConnected = false; private bool isPrevLinkCoreConnected = false; private bool isPrevLinkHubConnected = false; public static System.Action OnLinkCoreConnected; public static System.Action OnLinkCoreDisconnected; public static System.Action OnLinkHubConnected; public static System.Action OnLinkHubDisconnected; // Colors public static Color32 linkColor = new Color32(124, 64, 254, 255); #endregion #region MonoBehavior Life Cycle void OnEnable() { if (isInitialized && linkCoreStatus == LinkCoreStatus.Disconnected) { StartCoroutine(AutoConnection()); } } void OnApplicationQuit() { isInitialized = false; } void Update() { if ( Input.GetKeyUp(KeyCode.X) ) { isInitialized = false; //networkManager.DisconnectMessage(); } if (networkManager == null) return; linkCoreStatus = networkManager.LinkCoreStatus; isLinkCoreConnected = (linkCoreStatus == LinkCoreStatus.Connected); linkHubStatus = networkManager.LinkHubStatus; isLinkHubConnected = (linkHubStatus == LinkHubStatus.Connected); if (isLinkCoreConnected != isPrevLinkCoreConnected) { if (isLinkCoreConnected) { if (OnLinkCoreConnected != null) OnLinkCoreConnected.Invoke(); } else { if (OnLinkCoreDisconnected != null) OnLinkCoreDisconnected.Invoke(); } } isPrevLinkCoreConnected = isLinkCoreConnected; if (isLinkHubConnected != isPrevLinkHubConnected) { if (isLinkHubConnected) { if (OnLinkHubConnected != null) OnLinkHubConnected.Invoke(); } else { if (OnLinkHubDisconnected != null) OnLinkHubDisconnected.Invoke(); } } isPrevLinkHubConnected = isLinkHubConnected; } #endregion #region Initialize public bool Initialize() { LXDebug.Log("Initialized!"); if (networkManager == null) { networkManager = gameObject.AddComponent<NetworkManager>(); } isInitialized = networkManager.Initialize(); StartCoroutine(AutoConnection()); return true; } #endregion #region Connect & Disconnect IEnumerator AutoConnection() { LXDebug.Log("Connect to LooxidLink..."); while (true) { if (isInitialized && linkCoreStatus == LinkCoreStatus.Disconnected) { networkManager.Connect(); } yield return new WaitForSeconds(1.0f); } } #endregion #region Debug Setting public void SetDebug(bool isDebug) { LXDebug.isDebug = isDebug; } #endregion } }
using Microsoft.EntityFrameworkCore; using RSS.Business.Interfaces; using RSS.Business.Models; using RSS.Data.Context; using System; using System.Threading.Tasks; namespace RSS.Data.Repository { public class AddressRepository : Repository<Address>, IAddressRepository { public AddressRepository(CompleteAppDbContext context) : base(context) { } public async Task<Address> GetAddressBySupplier(Guid supplierId) { return await _db.Addresses.AsNoTracking().FirstOrDefaultAsync(a => a.SupplierId == supplierId); } } }
using System; using System.Diagnostics; using System.IO; using System.Security.Claims; using ELearning.BAL; using ELearning.helper; using ELearning.Model; using ELearning.Models; using ELearning.Utility; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace ELearning.Controllers { public class HomeController : Controller { UserBAL bal; IConfiguration _config; public HomeController(IConfiguration config) { bal = new UserBAL(config); _config = config; } public IActionResult Index() { //var sss = HttpContext.Session.GetObject<UserModel>("SuperAdmin"); string ssss=Guid.NewGuid().ToString() + Path.GetExtension("ads.mp4"); string ss = "0dh5tL5IKPNe72j4pEoT6fjcvFxEYMdnp+/MiuP9Ozo=";//"!nd!@!ndore74"; string sss = ss.DecryptString(); return View(); } public IActionResult Logout() { HttpContext.SignOutAsync(); return RedirectToAction("Index", "Home"); } [HttpPost] public IActionResult Login(IFormCollection fc) { string password = fc["password"]; UserModel objUser = new UserModel() { Email = fc["email"], Password = fc["password"] }; objUser = bal.UserAuthentication(objUser); if (objUser.IsAuthenticated && objUser.Password.DecryptString() == password) { var claims = new[] { new Claim("name", objUser.Name), new Claim("email", objUser.Email), new Claim("role", objUser.RoleId.ToString()), new Claim("userid",objUser.UserId.ToString()) }; var identity = new ClaimsIdentity(claims, "FiverSecurityScheme"); HttpContext.SignInAsync("FiverSecurityScheme", new ClaimsPrincipal(identity)); if (Convert.ToInt16(RoleType.SuperAdmin) == objUser.RoleId) { return RedirectToAction("Index", "SuperAdmin"); } if (Convert.ToInt16(RoleType.InstituteAdmin) == objUser.RoleId) { return RedirectToAction("Index", "Institute"); } if (Convert.ToInt16(RoleType.Student) == objUser.RoleId) { return RedirectToAction("Index", "Student"); } } else { ViewBag.error = "Email or password is wrong"; return View("Index", "Home"); } return View("Index", "Home"); } [HttpPost] public IActionResult Register(IFormCollection fc) { bool isValid = true; UserModel objUser = new UserModel(); if (string.IsNullOrEmpty(fc["rname"])) isValid = false; else objUser.Name = fc["rname"]; if (string.IsNullOrEmpty(fc["remail"])) isValid = false; else objUser.Email = fc["remail"]; if (string.IsNullOrEmpty(fc["cemail"])) isValid = false; if (string.IsNullOrEmpty(fc["rpassword"])) isValid = false; else objUser.Password = fc["rpassword"].ToString().EncryptString(); if (string.IsNullOrEmpty(fc["cpassword"])) isValid = false; if (string.IsNullOrEmpty(fc["activationcode"])) isValid = false; else objUser.ActivationCode = fc["activationcode"]; if (isValid) { objUser = bal.RegisterStudent(objUser, out int result); if (objUser.IsAuthenticated) { var claims = new[] { new Claim("name", objUser.Name), new Claim("email", objUser.Email), new Claim("role", objUser.RoleId.ToString()), new Claim("userid",objUser.UserId.ToString()) }; var identity = new ClaimsIdentity(claims, "FiverSecurityScheme"); HttpContext.SignInAsync("FiverSecurityScheme", new ClaimsPrincipal(identity)); return RedirectToAction("Index", "Student"); } else { if (result == 1) ViewBag.rerror = "Activation code is wrong,Please verify."; if (result == 2) ViewBag.rerror = "Email address is already registered."; if (result == 3) ViewBag.rerror = "Technical issue, Please reach out to admin."; } } else { ViewBag.rerror = "You are not authorized."; } return View("Index", "Home"); } [HttpPost] public JsonResult Forgotpassword(string Email) { bool result; UserModel objModel = bal.Forgotpassword(Email, out result); objModel.Email = Email; objModel.Password = !string.IsNullOrEmpty(objModel.Password) ? objModel.Password.DecryptString() : ""; if (result) { new EmailHelper(_config).SendEmail(objModel); } return Json(result); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } [HttpPost] public JsonResult Contact(string Name,string Email,string Phone,string Message) { ContactModel objModel = new ContactModel(); objModel.Email = Email; objModel.Name = Name; objModel.Phone = Phone; objModel.Message = Message; new EmailHelper(_config).SendContactEmail(objModel); return Json(true); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SongDuration { class Program { static void Main(string[] args) { //Adding extra comments Console.WriteLine("Test the constructor by entering some invalid parameters"); SongDuration invalidDuration1 = new SongDuration(-5, 43); SongDuration invalidDuration2 = new SongDuration(1, 65); SongDuration invalidDuration3 = new SongDuration(20, 59); SongDuration song1 = new SongDuration(1, 59); Console.WriteLine(song1.ToString()); SongDuration song3 = new SongDuration(20, 0); Console.WriteLine(song3.ToString()); SongDuration song4 = new SongDuration(3, 30); Console.WriteLine(song4.ToString()); SongDuration song5 = new SongDuration(3, 30); Console.WriteLine(song5.ToString()); //Test the + and - operators SongDuration calculate = song1 + song4; Console.WriteLine(calculate.ToString()); calculate = song4 - song1; Console.WriteLine(calculate.ToString()); calculate = song1 - song4; Console.WriteLine(calculate.ToString()); //Test the == and != operators Console.WriteLine(song4 == song5); //true Console.WriteLine(song4 == song1); //false Console.WriteLine(song4 != song5); //false Console.WriteLine(song4 != song3); //true //Test the < and <= operators Console.WriteLine(song4 < song5); //false Console.WriteLine(song4 < song3); //true Console.WriteLine(song4 <= song5); //true Console.WriteLine(song4 <= song1); //false //Test the > and >= operators Console.WriteLine(song4 > song5); //false Console.WriteLine(song4 > song3); //false Console.WriteLine(song4 >= song5); //true Console.WriteLine(song4 >= song1); //true //Hold the screen Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rwd.Framework { public class User { public User() { FullName = string.Empty; UserName = string.Empty; IsAdmin = false; MachineName = string.Empty; Groups = new List<string>(); Title = string.Empty; } public string FullName { get; set; } public string UserName { get; set; } public string EmailAddress { get; set; } public bool IsAdmin { get; set; } public string MachineName { get; set; } public List<string> Groups { get; set; } public string Title { get; set; } public Exception UserException { get; set; } } }
using Ricky.Infrastructure.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VnStyle.Services.Business.Models; using VnStyle.Services.Data; using VnStyle.Services.Data.Domain; namespace VnStyle.Services.Business { public class ArtistsService : IArtistsService { private readonly IBaseRepository<Artist> _artistRepository; private readonly IBaseRepository<GalleryPhoto> _galleryPhoto; private readonly IMediaService _mediaService; public ArtistsService(IBaseRepository<Artist> artistRepository, IMediaService mediaService, IBaseRepository<GalleryPhoto> galleryPhoto) { _artistRepository = artistRepository; _mediaService = mediaService; _galleryPhoto = galleryPhoto; } public IList<ArtistListingModel> GetAllArtists() { var query = _artistRepository.Table.Where(p => p.ShowOnHompage == true).OrderBy(p => p.Seq); if (query == null) { return null; } var artists = query.Select(p => new ArtistListingModel { Id = p.Id, Name = p.Name, ImageId = p.ImageId }).ToList(); foreach (var artist in artists) { if (artist.ImageId.HasValue) artist.UrlImage = _mediaService.GetPictureUrl(artist.ImageId.Value); else artist.UrlImage = "~/Content/images/no-image.png"; } return artists; } public IEnumerable<ImagesByArtist> GetAllImage() { var queryJoin = (from g in _galleryPhoto.Table join a in _artistRepository.Table on g.ArtistId equals a.Id select new ImagesByArtist { Name = a.Name, ImageId = g.FileId }).ToList(); foreach (var image in queryJoin) { image.UrlImage = _mediaService.GetPictureUrl(image.ImageId); } return queryJoin; } public IEnumerable<ImagesByArtist> GetAllImageByArtist(int id) { var query = _galleryPhoto.Table.Where(p => p.ArtistId == id); var queryJoin = (from g in query join a in _artistRepository.Table on g.ArtistId equals a.Id select new ImagesByArtist { IdArtist = a.Id, Name = a.Name, ImageId = g.FileId }).ToList(); foreach (var image in queryJoin) { image.UrlImage = _mediaService.GetPictureUrl(image.ImageId); } return queryJoin; } public IList<ArtistListingModel> GetImage() { var query = _artistRepository.Table.Where(p => p.ShowOnHompage == true).OrderBy(p => p.Seq); if (query == null) { return null; } var artists = query.Select(p => new ArtistListingModel { Id = p.Id, Name = p.Name, ImageId = p.ImageId }).Take(3).ToList(); foreach (var artist in artists) { if (artist.ImageId.HasValue) artist.UrlImage = _mediaService.GetPictureUrl(artist.ImageId.Value); else artist.UrlImage = "~/Content/images/no-image.png"; } return artists; } } }
// *********************************************************************** // Assembly : Huawei.SCOM.ESightPlugin.WebServer // Author : suxiaobo // Created : 12-12-2017 // // Last Modified By : suxiaobo // Last Modified On : 12-12-2017 // *********************************************************************** // <copyright file="ESightHelper.cs" company="广州摩赛网络技术有限公司"> // Copyright © 2017 // </copyright> // <summary>The e sight helper.</summary> // *********************************************************************** namespace Huawei.SCOM.ESightPlugin.WebServer.Helper { using System; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using CommonUtil; using Huawei.SCOM.ESightPlugin.Const; using Huawei.SCOM.ESightPlugin.Models; using Huawei.SCOM.ESightPlugin.RESTeSightLib; using Huawei.SCOM.ESightPlugin.RESTeSightLib.Exceptions; using Huawei.SCOM.ESightPlugin.RESTeSightLib.Helper; using Huawei.SCOM.ESightPlugin.WebServer.Model; using LogUtil; /// <summary> /// The e sight helper. /// </summary> public class ESightHelper { /// <summary> /// Deletes the specified event data. /// </summary> /// <param name="eventData">The event data.</param> /// <returns>Huawei.SCOM.ESightPlugin.WebServer.Model.ApiResult.</returns> public static ApiResult Delete(object eventData) { var ret = new ApiResult(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR, string.Empty); try { var jsData = JsonUtil.SerializeObject(eventData); HWLogger.UI.Info("Deleting eSight, the param is [{0}]", jsData); var hostIps = eventData.ToString().TrimEnd(',').Split(','); foreach (var hostIp in hostIps) { try { // 取消订阅(不再修改eSight的订阅状态) var eSight = ESightDal.Instance.GetEntityByHostIp(hostIp); if (eSight == null) { throw new Exception("can not find eSight:" + hostIp); } UnSubscribeESight(hostIp, eSight.SystemID, true); // 从文件中删除 ESightDal.Instance.DeleteESightByHostIp(hostIp); // 告诉服务(删除scom中的服务器) Task.Run(() => { var message = new TcpMessage<string>(hostIp, TcpMessageType.DeleteESight, "delete a ESight"); NotifyClient.Instance.SendMsg(message); }); } catch (Exception ex) { HWLogger.UI.Error($"Deleting eSight({hostIp}) error !", ex); } } HWLogger.UI.Info("Deleting eSight successful!"); ret.Code = "0"; ret.Success = true; ret.Msg = "Deleting eSight successful!"; } catch (BaseException ex) { HWLogger.UI.Error("Deleting eSight failed: ", ex); ret.Code = $"{ex.ErrorModel}{ex.Code}"; ret.Success = false; ret.ExceptionMsg = ex.Message; } catch (Exception ex) { HWLogger.UI.Error("Deleting eSight failed: ", ex); ret.Code = ConstMgr.ErrorCode.SYS_UNKNOWN_ERR; ret.Success = false; ret.ExceptionMsg = ex.InnerException?.Message ?? ex.Message; } return ret; } /// <summary> /// 获取eSight列表数据 /// </summary> /// <param name="queryParam"> /// The query Param. /// </param> /// <returns> /// The <see> /// <cref>WebReturnLGResult</cref> /// </see> /// . /// </returns> public static WebReturnLGResult<HWESightHost> GetList(ParamPagingOfQueryESight queryParam) { var ret = new WebReturnLGResult<HWESightHost> { Code = CoreUtil.GetObjTranNull<int>( ConstMgr.ErrorCode.SYS_UNKNOWN_ERR), Description = string.Empty }; try { // 1. 处理参数 var jsData = JsonUtil.SerializeObject(queryParam); HWLogger.UI.Info("Querying eSight list, the param is [{0}]", jsData); var pageSize = queryParam.PageSize; var pageNo = queryParam.PageNo; var hostIp = queryParam.HostIp; // 2. 获取数据 var hwESightHostList = ESightDal.Instance.GetList(); var filterList = hwESightHostList.Where(x => x.HostIP.Contains(hostIp)).Skip((pageNo - 1) * pageSize) .Take(pageSize).ToList(); // 3. 返回数据 ret.Code = 0; ret.Data = filterList; ret.TotalNum = hwESightHostList.Count(); ret.Description = string.Empty; HWLogger.UI.Info("Querying eSight list successful, the ret is [{0}]", JsonUtil.SerializeObject(ret)); } catch (BaseException ex) { ret.Code = CoreUtil.GetObjTranNull<int>(ex.Code); ret.ErrorModel = ex.ErrorModel; ret.Description = ex.Message; ret.Data = null; ret.TotalNum = 0; HWLogger.UI.Error("Querying eSight list failed: ", ex); } catch (Exception ex) { HWLogger.UI.Error(ex); ret.Code = CoreUtil.GetObjTranNull<int>(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR); ret.Description = ex.InnerException?.Message ?? ex.Message; ret.Data = null; ret.TotalNum = 0; HWLogger.UI.Error("Querying eSight list failed: ", ex); } return ret; } /// <summary> /// Adds the specified event data. /// </summary> /// <param name="model">The new e sight.</param> /// <returns>Huawei.SCOM.ESightPlugin.WebServer.Model.ApiResult.</returns> public static ApiResult Add(HWESightHost model) { var ret = new ApiResult(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR, string.Empty); try { var oldeSight = ESightDal.Instance.GetEntityByHostIp(model.HostIP); // hostIp 已存在,则报错 if (oldeSight != null) { throw new BaseException("-90006", null, $"{model.HostIP} is already exsit"); } #region 赋值 model.CreateTime = DateTime.Now; model.LastModifyTime = DateTime.Now; model.OpenID = Guid.NewGuid().ToString("D"); model.SubscribeID = Guid.NewGuid().ToString("D"); model.SubKeepAliveStatus = 0; model.SubscriptionAlarmStatus = 0; model.SubscriptionNeDeviceStatus = 0; model.SubKeepAliveError = string.Empty; model.SubscripeAlarmError = string.Empty; model.SubscripeNeDeviceError = string.Empty; model.LatestStatus = ConstMgr.ESightConnectStatus.NONE; model.LatestConnectInfo = string.Empty; var encryptPwd = EncryptUtil.EncryptPwd(model.LoginPd); model.LoginPd = encryptPwd; #endregion var json = JsonUtil.SerializeObject(model); HWLogger.UI.Info("Add eSight, the param is [{0}]", HidePd(json)); ESightEngine.Instance.SaveSession(model); ESightDal.Instance.InsertEntity(model); // 告诉服务 Task.Run(() => { var message = new TcpMessage<string>(model.HostIP, TcpMessageType.SyncESight, "add new ESight"); NotifyClient.Instance.SendMsg(message); }); HWLogger.UI.Info("Add eSight successful!"); ret.Code = "0"; ret.Success = true; ret.Msg = "Add eSight successful!"; } catch (BaseException ex) { HWLogger.UI.Error("Add eSight failed: ", ex); ret.Code = $"{ex.ErrorModel}{ex.Code}"; ret.Success = false; ret.ExceptionMsg = ex.Message; } catch (Exception ex) { HWLogger.UI.Error("Add eSight failed: ", ex); ret.Code = ConstMgr.ErrorCode.SYS_UNKNOWN_ERR; ret.Success = false; ret.ExceptionMsg = ex.InnerException == null ? ex.Message : ex.InnerException.Message; } return ret; } /// <summary> /// Updates the specified new e sight. /// </summary> /// <param name="model">The new e sight.</param> /// <returns>Huawei.SCOM.ESightPlugin.WebServer.Model.ApiResult.</returns> public static ApiResult Update(HWESightHost model) { var ret = new ApiResult(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR, string.Empty); try { var json = JsonUtil.SerializeObject(model); HWLogger.UI.Info("Update eSight , the param is [{0}]", HidePd(json)); #region 赋值 var eSight = ESightDal.Instance.GetEntityByHostIp(model.HostIP); if (eSight == null) { ret.Code = "-81111"; ret.Success = false; ret.Msg = $"can not find eSight: hostip {model.HostIP}"; return ret; } eSight.AliasName = model.AliasName; eSight.HostPort = model.HostPort; eSight.LoginAccount = model.LoginAccount; eSight.LatestStatus = ConstMgr.ESightConnectStatus.NONE; eSight.LatestConnectInfo = string.Empty; eSight.LastModifyTime = DateTime.Now; var encryptPwd = EncryptUtil.EncryptPwd(model.LoginPd); eSight.LoginPd = encryptPwd; var oldSystemId = eSight.SystemID; var isChangeSystemId = oldSystemId != model.SystemID; if (isChangeSystemId) { eSight.SystemID = model.SystemID; eSight.SubscribeID = Guid.NewGuid().ToString(); eSight.SubscripeNeDeviceError = string.Empty; eSight.SubscripeAlarmError = string.Empty; eSight.SubKeepAliveError = string.Empty; eSight.SubscriptionNeDeviceStatus = 0; eSight.SubscriptionAlarmStatus = 0; eSight.SubKeepAliveStatus = 0; } #endregion ESightEngine.Instance.SaveSession(eSight); if (isChangeSystemId) { // 修改了systemId,在session保存成功后重新订阅 UnSubscribeESight(eSight.HostIP, oldSystemId); } // Update ESightDal.Instance.UpdateEntity(eSight); // 告诉服务 Task.Run(() => { var message = new TcpMessage<string>(eSight.HostIP, TcpMessageType.SyncESight, "Update ESight"); NotifyClient.Instance.SendMsg(message); }); HWLogger.UI.Info("Update eSight successful!"); ret.Code = "0"; ret.Success = true; ret.Msg = "Update eSight successful!"; } catch (BaseException ex) { HWLogger.UI.Error("Update eSight failed: ", ex); ret.Code = $"{ex.ErrorModel}{ex.Code}"; ret.Success = false; ret.ExceptionMsg = ex.Message; } catch (Exception ex) { HWLogger.UI.Error("Update eSight failed: ", ex); ret.Code = ConstMgr.ErrorCode.SYS_UNKNOWN_ERR; ret.Success = false; ret.ExceptionMsg = ex.InnerException == null ? ex.Message : ex.InnerException.Message; } return ret; } /// <summary> /// Updates the with out pass. /// </summary> /// <param name="model">The new e sight.</param> /// <returns>Huawei.SCOM.ESightPlugin.WebServer.Model.ApiResult.</returns> public static ApiResult UpdateWithOutPass(HWESightHost model) { var ret = new ApiResult(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR, string.Empty); try { var json = JsonUtil.SerializeObject(model); HWLogger.UI.Info("Update eSight , the param is [{0}]", HidePd(json)); #region 赋值 var eSight = ESightDal.Instance.GetEntityByHostIp(model.HostIP); if (eSight == null) { ret.Code = "-81111"; ret.Success = false; ret.Msg = $"can not find eSight: hostip {model.HostIP}"; return ret; } eSight.AliasName = model.AliasName; eSight.HostPort = model.HostPort; eSight.LastModifyTime = DateTime.Now; var oldSystemId = eSight.SystemID; var isChangeSystemId = oldSystemId != model.SystemID; if (isChangeSystemId) { // 修改了systemId,需要重新订阅 eSight.SystemID = model.SystemID; eSight.SubscribeID = Guid.NewGuid().ToString(); eSight.SubscripeNeDeviceError = string.Empty; eSight.SubscripeAlarmError = string.Empty; eSight.SubKeepAliveError = string.Empty; eSight.SubscriptionNeDeviceStatus = 0; eSight.SubscriptionAlarmStatus = 0; eSight.SubKeepAliveStatus = 0; } #endregion ESightEngine.Instance.SaveSession(eSight); if (isChangeSystemId) { // 修改了systemId,在session保存成功后重新订阅 UnSubscribeESight(eSight.HostIP, oldSystemId); } // UpdateWithOutPass ESightDal.Instance.UpdateEntity(eSight); // 告诉服务 Task.Run(() => { var message = new TcpMessage<string>(eSight.HostIP, TcpMessageType.SyncESight, "Update ESight WithOut Pass"); NotifyClient.Instance.SendMsg(message); }); HWLogger.UI.Info("Update eSight successful!"); ret.Code = "0"; ret.Success = true; ret.Msg = "Update eSight successful!"; } catch (BaseException ex) { HWLogger.UI.Error("Update eSight failed: ", ex); ret.Code = $"{ex.ErrorModel}{ex.Code}"; ret.Success = false; ret.ExceptionMsg = ex.Message; } catch (Exception ex) { HWLogger.UI.Error("Update eSight failed: ", ex); ret.Code = ConstMgr.ErrorCode.SYS_UNKNOWN_ERR; ret.Success = false; ret.ExceptionMsg = ex.InnerException == null ? ex.Message : ex.InnerException.Message; } return ret; } /// <summary> /// The test. /// </summary> /// <param name="eSight">The e sight.</param> /// <returns>The <see cref="ApiResult" />.</returns> public static ApiResult Test(HWESightHost eSight) { var ret = new ApiResult(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR, string.Empty); try { var json = JsonUtil.SerializeObject(eSight); HWLogger.UI.Info("Testing eSight connect..., the param is [{0}]", HidePd(json)); var LoginPd = eSight.LoginPd; eSight.LoginPd = EncryptUtil.EncryptPwd(LoginPd); var testResult = ESightEngine.Instance.TestEsSession(eSight); if (string.IsNullOrEmpty(testResult)) { HWLogger.UI.Info("Testing eSight connect successful!"); ret.Code = "0"; ret.Success = true; ret.Msg = "Testing eSight connect successful!"; } else { HWLogger.UI.Info("Testing eSight connect failed!"); ret.Code = testResult; ret.Success = false; ret.ExceptionMsg = "Testing eSight connect failed!"; } } catch (BaseException ex) { HWLogger.UI.Error("Testing eSight connect failed: ", ex); ret.Success = false; ret.Code = $"{ex.ErrorModel}{ex.Code}"; ret.ExceptionMsg = ex.Message; } catch (Exception ex) { HWLogger.UI.Error("Testing eSight connect failed: ", ex); ret.Code = ConstMgr.ErrorCode.SYS_UNKNOWN_ERR; ret.Success = false; ret.Msg = "Testing eSight connect failed!"; ret.ExceptionMsg = ex.InnerException?.Message ?? ex.Message; } return ret; } /// <summary> /// 隐藏Json字符串中的密码 /// </summary> /// <param name="jsonData"> /// The json data. /// </param> /// <returns> /// System.String. /// </returns> private static string HidePd(string jsonData) { var replacement = "\"${str}\":\"********\""; var pattern1 = "\"(?<str>([A-Za-z0-9_]*)loginPd)\":\"(.*?)\""; string newJsonData = Regex.Replace( jsonData, pattern1, replacement, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline); return newJsonData; } /// <summary> /// 取消订阅eSight.(需要用旧的systemId取消订阅) /// </summary> /// <param name="hostIp">The host ip.</param> /// <param name="oldSystemId">The system identifier.</param> /// <param name="isDeleteSession">The is delete session.</param> private static void UnSubscribeESight(string hostIp, string oldSystemId, bool isDeleteSession = false) { Task.Run(() => { try { // 取消订阅 var iEsSession = ESightEngine.Instance.FindEsSession(hostIp); var resut = iEsSession.UnSubscribeKeepAlive(oldSystemId); HWLogger.UI.Info($"UnSubscribeKeepAlive.eSight:{hostIp} result:{JsonUtil.SerializeObject(resut)}"); resut = iEsSession.UnSubscribeAlarm(oldSystemId); HWLogger.UI.Info($"UnSubscribeAlarm. eSight:{hostIp} result:{JsonUtil.SerializeObject(resut)}"); resut = iEsSession.UnSubscribeNeDevice(oldSystemId); HWLogger.UI.Info($"UnSubscribeNeDevice. eSight:{hostIp} result:{JsonUtil.SerializeObject(resut)}"); } catch (Exception ex) { HWLogger.UI.Error("UnSubscribeWhenUpdateSystemId Error", ex); } finally { if (isDeleteSession) { // 从缓存中删除 ESightEngine.Instance.RemoveEsSession(hostIp); } } }); } } }
using BDTest.Attributes; namespace BDTest.Tests; public class CustomInformationAttribute : TestInformationAttribute { public CustomInformationAttribute(string information) : base(information) { } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Windows.Storage; using BibleBrowserUWP; namespace BibleBrowserUWP { /// <summary> /// A tab that has a Bible and reference open. /// </summary> class BrowserTab : INotifyPropertyChanged { public enum NavigationMode { Previous, Add, Next } #region Property Changed Implementation public event PropertyChangedEventHandler PropertyChanged; // This method is called by the Set accessor of each property. // The CallerMemberName attribute that is applied to the optional propertyName // parameter causes the property name of the caller to be substituted as an argument. private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Constants and Static Elements private const string KEYHISTINDX = "tab_selected_index"; private static ApplicationDataContainer m_localSettings = ApplicationData.Current.LocalSettings; private static StorageFolder m_localFolder = ApplicationData.Current.LocalFolder; /// <summary> /// A list of open tabs. /// </summary> public static TrulyObservableCollection<BrowserTab> Tabs = new TrulyObservableCollection<BrowserTab>(); /// <summary> /// The currently selected browser tab. May return null. /// </summary> public static BrowserTab Selected { get { if (Tabs.Count == 0) { return null; } else if (Tabs.Count - 1 < SelectedIndex) { SelectedIndex = Tabs.IndexOf(Tabs.LastOrDefault()); return Tabs[SelectedIndex]; } else return Tabs[SelectedIndex]; } } /// <summary> /// The index of the currently open tab. /// Stored in application memory. /// </summary> public static int SelectedIndex { get { // First time the app is opened if (m_localSettings.Values[KEYHISTINDX] == null) { m_localSettings.Values[KEYHISTINDX] = Tabs.Count - 1; return Tabs.Count - 1; } else return (int)m_localSettings.Values[KEYHISTINDX]; } set { if (value < 0) { throw new Exception("Cannot set the selected index to less than zero"); } else if (value > Tabs.Count - 1) throw new Exception("Cannot set the selected index to more than the number of tabs"); else m_localSettings.Values[KEYHISTINDX] = value; } } /// <summary> /// Return the next available reference, or null if there is none more. /// </summary> public BibleReference Next { get { if(m_HistoryIndex < History.Count - 1) return History[m_HistoryIndex + 1]; else return null; } } /// <summary> /// Return the past visited reference, or null if there is none. /// </summary> public BibleReference Previous { get { if (m_HistoryIndex > 0) return History[m_HistoryIndex - 1]; else return null; } } /// <summary> /// All available versions except the present one. /// </summary> public ObservableCollection<BibleVersion> OtherVersions { get { ObservableCollection<BibleVersion> versions = BibleLoader.Bibles; versions.Remove(Reference.Version); return versions; } } #endregion #region Member Variables private int m_HistoryIndex = 0; #endregion #region Properties public bool IsNewTab { get; private set; } /// <summary> /// A list of the current and previous references visited under this tab. /// The last item is most recently viewed. /// </summary> public List<BibleReference> History { get; private set; } = new List<BibleReference>(); /// <summary> /// Get the currently active <c>BibleReference</c> from history. /// If there is none, return <c>null</c>. /// </summary> public BibleReference Reference { get { if (History.Count > 0) return History[m_HistoryIndex]; else //throw new Exception("Reference is null"); return null; } } /// <summary> /// The reference this tab is at, or a new tab appelation. /// </summary> public string TabName { get { if(IsNewTab) return "New tab"; else { return Reference.BookName + " " + Reference.Chapter; } } } /// <summary> /// Get the language code of the current version, like "en" or "fr" /// </summary> public string LanguageCode { get { return Reference.Version.Language.ToLower(); } } /// <summary> /// Add a reference to history as necessary. /// </summary> /// <param name="reference">The reference to visit; do not pass in <c>null</c>. /// This <c>ref</c> parameter returns the navigation result (so it can be navigated to).</param> /// <param name="mode">When the <c>NavigationMode</c> is <c>Previous</c> or <c>Next</c>, the reference is moved to but not added in history.</param> public void AddToHistory(ref BibleReference reference, NavigationMode mode = NavigationMode.Add) { if (reference == null) throw new Exception("Do not assign null to a Bible reference in history"); else { switch(mode) { case NavigationMode.Add: // Delete history that's past the current item for (int i = m_HistoryIndex; i < History.Count; i++) { if (i > m_HistoryIndex) History.RemoveAt(i); } History.Add(reference); m_HistoryIndex = History.Count - 1; NotifyPropertyChanged(); return; case NavigationMode.Previous: m_HistoryIndex = Math.Clamp(m_HistoryIndex - 1, 0, History.Count - 1); reference = History[m_HistoryIndex]; NotifyPropertyChanged(); return; case NavigationMode.Next: m_HistoryIndex = Math.Clamp(m_HistoryIndex + 1, 0, History.Count - 1); reference = History[m_HistoryIndex]; NotifyPropertyChanged(); return; } foreach(var item in History) { Debug.WriteLine("History item: " + item.FullReference + " " + item.IsSearch); } } } /// <summary> /// Uniquely identify each tab. /// </summary> public Guid Guid { get; private set; } #endregion #region Constructor /// <summary> /// Create a custom browser tab. /// </summary> public BrowserTab(BibleReference reference, bool isNewTab) { Worker(reference, IsNewTab); } /// <summary> /// Create a pre-existing browser tab. /// </summary> public BrowserTab(BibleReference reference) { Worker(reference, false); } /// <summary> /// Create a new tab with the default reference. /// </summary> public BrowserTab() { Worker(BibleReference.Default, true); } private void Worker(BibleReference reference, bool isNewTab) { if (reference == null) throw new ArgumentNullException("A new browser tab without a reference should be created with the overloaded constructor."); else History.Add(reference); Guid = Guid.NewGuid(); IsNewTab = IsNewTab; } #endregion #region Methods /// <summary> /// Overridden string method. /// </summary> /// <returns>A bible reference</returns> public override string ToString() { BibleReference reference = History.LastOrDefault(); // TODO if (reference == null) return Guid.ToString(); else return "[" + reference.Version + "] " + reference.SimplifiedReference; } /// <summary> /// Save the presently open tabs to an XML document. /// </summary> public static async Task SaveOpenTabs() { // Create a new XML document root node XDocument document = new XDocument(new XElement("SavedTabs")); // Save each open tab to the XML document foreach (BrowserTab tab in Tabs) { if (tab.Reference != null) { // Check, otherwise throwing in null will fail the constructor string comparisonVersion; if(tab.Reference.ComparisonVersion == null) { comparisonVersion = "Null"; } else { comparisonVersion = tab.Reference.ComparisonVersion.FileName; } XElement element = new XElement("Reference", new XElement("FileName", tab.Reference.Version.FileName), new XElement("ComparisonFileName", comparisonVersion), new XElement("BookName", tab.Reference.BookName), new XElement("Chapter", tab.Reference.Chapter), new XElement("Verse", tab.Reference.Verse) ); document.Root.Add(element); } } // Debug the file contents Debug.WriteLine("Tabs saved as :"); Debug.WriteLine(document); // Save the resulting XML document StorageFile writeFile = await m_localFolder.CreateFileAsync("SavedTabs.xml", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(writeFile, document.ToString()); } /// <summary> /// Initialize the tabs to when the browser was previously open. /// Assign the tabs to the loaded data. /// </summary> public static async Task LoadSavedTabs() { // There may not be a saved document try { // Read the saved XML tabs StorageFile readFile = await m_localFolder.GetFileAsync("SavedTabs.xml"); string text = await FileIO.ReadTextAsync(readFile); // Debug file contents Debug.WriteLine("The saved tabs xml file contents :"); Debug.WriteLine(text); XDocument XMLTabs = XDocument.Parse(text); // Debug the file contents Debug.WriteLine("Tabs loaded :"); Debug.WriteLine(XMLTabs); // Create the tab list from XML IEnumerable<XElement> tabs = XMLTabs.Descendants("Reference"); TrulyObservableCollection<BrowserTab> savedTabs = new TrulyObservableCollection<BrowserTab>(); foreach (XElement node in tabs) { // Get the information from XML BibleVersion bibleVersion = new BibleVersion(node.Element("FileName").Value); BibleVersion comparisonVersion; if(node.Element("ComparisonFileName").Value == "Null") { comparisonVersion = null; } else { comparisonVersion = new BibleVersion(node.Element("ComparisonFileName").Value); } string bookName = node.Element("BookName").Value; BibleBook book = BibleReference.StringToBook(bookName, bibleVersion); int chapter = int.Parse(node.Element("Chapter").Value); int verse = int.Parse(node.Element("Verse").Value); // Create the reference that goes in the tab BibleReference reference = new BibleReference(bibleVersion, comparisonVersion, book, chapter, verse); savedTabs.Add(new BrowserTab(reference)); } // Add the tabs to the browser foreach (BrowserTab tab in savedTabs) { Tabs.Add(tab); } RequireNewTab(); } catch(System.IO.FileNotFoundException fileNotFoundE) { Debug.WriteLine("A resource was not loaded correctly; this may be a missing bible version :"); Debug.WriteLine(fileNotFoundE.Message); RequireNewTab(); } catch (System.Xml.XmlException xmlE) // Parse error { Debug.WriteLine("Reading the saved tabs xml file choked :"); Debug.WriteLine(xmlE.Message); RequireNewTab(); } catch (Exception e) { Debug.WriteLine("Loading saved tabs was interrupted :"); Debug.WriteLine(e.Message); RequireNewTab(); } } /// <summary> /// Ensure that there is at least one tab open, even when none existed in app memory. /// </summary> private static void RequireNewTab() { // Avoid loading no tabs at first startup if (Tabs.Count == 0) { Tabs.Add(new BrowserTab()); } } #endregion } }
using RomashkaBase.Model; using RomashkaBase.ViewModel; using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RomashkaBase.View { /// <summary> /// Логика взаимодействия для CompaniesView.xaml /// </summary> public partial class CompaniesView : Page { public CompaniesView(ApplicationContext db) { InitializeComponent(); DataContext = new CompaniesViewModel(db); } private void ButtonOpenAddCompany_Click(object sender, RoutedEventArgs e) { ButtonOpenAddCompany.Visibility = Visibility.Collapsed; ButtonCloseCompany.Visibility = Visibility.Visible; ButtonRemoveCompany.Visibility = Visibility.Collapsed; } private void ButtonCloseCompany_Click(object sender, RoutedEventArgs e) { ButtonCloseCompany.Visibility = Visibility.Collapsed; ButtonOpenAddCompany.Visibility = Visibility.Visible; ButtonRemoveCompany.Visibility = Visibility.Visible; if (ButtonChangeSaveCompany.Visibility == Visibility.Visible) { ButtonChangeSaveCompany.Visibility = Visibility.Collapsed; ButtonAddSaveCompany.Visibility = Visibility.Visible; } ButtonOpenEditCompany.Visibility = Visibility.Visible; } private void ButtonOpenEditCompany_Click(object sender, RoutedEventArgs e) { ButtonOpenAddCompany.Visibility = Visibility.Collapsed; ButtonCloseCompany.Visibility = Visibility.Visible; ButtonRemoveCompany.Visibility = Visibility.Collapsed; ButtonChangeSaveCompany.Visibility = Visibility.Visible; ButtonOpenEditCompany.Visibility = Visibility.Collapsed; ButtonAddSaveCompany.Visibility = Visibility.Collapsed; } } }