public void StringProperties() { IDictionary<string, object> dict = new Dictionary<string, object>(); dict["intprop"] = 1; string json = JSON.ToJSON(dict); Assert.AreEqual("{\"intprop\":1}",json); dict.Clear(); dict["stringprop"] = "foo"; json = JSON.ToJSON(dict); Assert.AreEqual("{\"stringprop\":\"foo\"}", json); dict.Clear(); dict["arrayprop"] = new int[] { 1, 2, 3 }; json = JSON.ToJSON(dict); Assert.AreEqual("{\"arrayprop\":[1,2,3]}", json); dict.Clear(); dict["1"] = "bar"; json = JSON.ToJSON(dict); Assert.AreEqual("{\"1\":\"bar\"}", json); dict.Clear(); dict["false"] = "foobar"; json = JSON.ToJSON(dict); Assert.AreEqual("{\"false\":\"foobar\"}", json); }
void CollectViews() { var view = android_ass.GetType ("Android.Views.View"); var animation = android_ass.GetType ("Android.Views.Animations.Animation"); var layoutparams = android_ass.GetType ("Android.Views.ViewGroup+LayoutParams"); targets.Add (view); var d = new Dictionary<Type,bool> (); foreach (var ass in asses) foreach (var t in ass.GetTypes ()) CheckIfTypeIsTarget (view, d, t); views.AddRange (from e in d where e.Value select e.Key); targets.AddRange (views); d.Clear (); targets.Add (animation); foreach (var ass in asses) foreach (var t in ass.GetTypes ()) CheckIfTypeIsTarget (animation, d, t); anims.AddRange (from e in d where e.Value select e.Key); targets.AddRange (anims); d.Clear (); layparams.Add (layoutparams); foreach (var ass in asses) foreach (var t in ass.GetTypes ()) CheckIfTypeIsTarget (layoutparams, d, t); layparams.AddRange (from e in d where e.Value select e.Key); targets.AddRange (layparams); d.Clear (); GenerateCode (); }
public void NotifyChangedText() { var propDict = new Dictionary<string, string>(); JsonObject jso = new JsonObject(); jso.PropertyChanged += (obj, e) => { propDict.Add(e.PropertyName, ""); }; dynamic djso = jso; Assert.IsFalse(propDict.ContainsKey("Name")); djso.Name = "JP"; Assert.IsTrue(propDict.ContainsKey("Name")); propDict.Clear(); Assert.IsFalse(propDict.ContainsKey("Name")); djso["Name"] = "JP"; Assert.IsTrue(propDict.ContainsKey("Name")); propDict.Clear(); djso.RemoveAll(); Assert.IsFalse(propDict.ContainsKey("Name")); djso.Add("Name", "JP"); Assert.IsTrue(propDict.ContainsKey("Name")); propDict.Clear(); }
/// <summary> /// Do the specified input and output. /// </summary> /// <param name="input">Input.</param> /// <param name="output">Output.</param> public void Do(BlockingCollection<ISkeleton> input, Action<IEnumerable<Result>> fireNewCommand) { var data = new Dictionary<JointType, InputVector>(); foreach (var skeleton in input.GetConsumingEnumerable()) { foreach (var joint in skeleton.Joints) { if (!data.ContainsKey(joint.JointType)) { data.Add(joint.JointType, new InputVector()); } data[joint.JointType].Stream.Add(joint.Point); } if (data.First().Value.Stream.Count < 5) { continue; } var results = Recognizer.Recognize(data); try { fireNewCommand(results); } catch (Exception) { if (data.First().Value.Stream.Count > 40) { data.Clear(); } continue; } data.Clear(); } }
/// <summary> /// Метод удаляет лист заказа вместе с горячей статистикой /// </summary> /// <param name="orderNum">Номер листа заказа</param> public static void deleteOrder(string orderNum) { Dictionary<string, string> Dict = new Dictionary<string, string>(); Dict.Add("ORDER_NUM", orderNum); SQLOracle.delete("delete from USP_HOT_STATS where ORDER_NUM = :ORDER_NUM", Dict); Dict.Clear(); if (!AssemblyOrders.isProject(orderNum)) { int id = _ASSEMBLIES.getId_OrderNum(orderNum); Dict.Add("ID", id.ToString()); SQLOracle.delete("delete from USP_ASSEMBLIES where ID = :ID", Dict); SQLOracle.delete("delete from USP_ASSEMBLY_ELEMENTS where ASSEMBLY_ID = :ID", Dict); Dict.Clear(); } if (isTZ(orderNum)) { string idDoc = getTZId(orderNum); Dict.Add("ID_DOC", idDoc); string cmdUpdate = "update USP_TZ_DATA set UTV = 1, HP_KOL_EDEN = null where ID_DOC = :ID_DOC"; SQLOracle.update(cmdUpdate, Dict); cmdUpdate = "update USP_TZ_DATA_TP set OBOZN_KOMP = NULL, NAIM_KOMP = NULL, KOL = null where ID_DOC = :ID_DOC"; SQLOracle.update(cmdUpdate, Dict); } Dict.Clear(); Dict.Add("ORDER_NUM", orderNum); SQLOracle.delete("delete from USP_ASSEMBLY_ORDERS where NUM = :ORDER_NUM", Dict); }
private static void Main(string[] args) { var connector = Credentials.MyConnector(); var paramlist = new Dictionary<string, string> { {"account", "test"}, {"tablename", "sdktest1"}, {"fileurl", "http://maplarge-data.s3.amazonaws.com/TwitterS3.zip"} }; //CREATE TABLE SYNCHRONOUS (NO WEB CALL) //MapLargeConnector.NO_WEB_CALLS = true; var response = connector.InvokeAPIRequest("CreateTableSynchronous", paramlist); Console.WriteLine(response); MapLargeConnector.NO_WEB_CALLS = false; //RETRIEVE REMOTE USER AUTH TOKEN response = connector.GetRemoteAuthToken(Credentials.UserName, Credentials.Password, "255.255.255.255"); Console.WriteLine(response); //LIST GROUPS paramlist.Clear(); paramlist.Add("account", "test"); response = connector.InvokeAPIRequestPost("ListGroups", paramlist); Console.WriteLine(response); //CREATE TABLE WITH FILES SYNCHRONOUS paramlist.Clear(); paramlist.Add("account", "test"); paramlist.Add("tablename", "sdktest2"); response = connector.InvokeAPIRequestPost("CreateTableWithFilesSynchronous", paramlist, new[] {@"C:\MapLarge\Small.csv"}); Console.WriteLine(response); }
public bool IsValidSudoku(char[,] board) { IDictionary<char, bool> dic = new Dictionary<char, bool> (); for (int i = 0; i < board.GetLength (0); ++i) { // row dic.Clear(); for (int j = 0; j < board.GetLength (1); ++j) { if (board [i, j] == '.') { continue; } if (dic.ContainsKey (board [i, j])) { return false; } else { dic[board[i, j]] = true; } } // col dic.Clear(); for (int j = 0; j < board.GetLength (1); ++j) { if (board [j, i] == '.') { continue; } if (dic.ContainsKey (board [j, i])) { return false; } else { dic[board[j, i]] = true; } } } // part for (int i = 0; i < board.GetLength (0); i += 3) { for (int j = 0; j < board.GetLength (1); j += 3) { dic.Clear (); for (int ii = 0; ii < 3; ++ii) { for (int jj = 0; jj < 3; ++jj) { char c = board [i + ii, j + jj]; if (c == '.') { continue; } if (dic.ContainsKey (c)) { return false; } else { dic[c] = true; } } } } } return true; }
public static void Run() { Console.WriteLine("Running test configured with App.config."); using (WorkflowRuntimeManager manager = new WorkflowRuntimeManager(new WorkflowRuntime("WorkflowRuntime"))) { manager.MessageEvent += delegate(object sender, WorkflowLogEventArgs e) { Console.WriteLine(e.Message); }; manager.WorkflowRuntime.StartRuntime(); Dictionary<string, object> wfArguments = new Dictionary<string, object>(); //wfArguments.Add("InputString", "1"); ManagedWorkflowInstance instance1 = manager.StartWorkflow(@"C:\Documents and Settings\Administrator\Desktop\Pro WF\chapter 17\WorkflowDesignerApp\bin\Debug\Test.xoml", @"C:\Documents and Settings\Administrator\Desktop\Pro WF\chapter 17\WorkflowDesignerApp\bin\Debug\Test.rules", wfArguments); //ManagedWorkflowInstance instance1 = manager.StartWorkflow(typeof(Workflow1), wfArguments); //instance1.WorkflowInstance.Terminate("Manual Termination"); wfArguments.Clear(); wfArguments.Add("InputString", "2"); ManagedWorkflowInstance instance2 = manager.StartWorkflow(typeof(Workflow1), wfArguments); instance2.WorkflowInstance.Suspend("Manual Suspension"); instance2.WorkflowInstance.Resume(); wfArguments.Clear(); wfArguments.Add("InputString", "3"); manager.StartWorkflow(typeof(Workflow1), wfArguments); manager.WaitAll(15000); foreach (ManagedWorkflowInstance managedInstance in manager.Workflows.Values) { if (managedInstance.Outputs.ContainsKey("Result")) { Console.WriteLine(managedInstance.Outputs["Result"]); } if (managedInstance.Exception != null) { Console.WriteLine("{0} - Exception: {1}", managedInstance.Id, managedInstance.Exception.Message); } if (managedInstance.ReasonSuspended.Length > 0) { Console.WriteLine("{0} - Suspended: {1}", managedInstance.Id, managedInstance.ReasonSuspended); } } manager.ClearAllWorkflows(); } }
private void ListBucket() { backupProgress.EnterAction(BackupAction.ListingBucket); try { files.RemoveRemoteFiles(); if (Settings.Default.Bucket != null) { try { S3 s3 = new S3(Settings.Default.Bucket.AccessKeyId, Settings.Default.Bucket.SecretAccessKey); IDictionary<string, BackupFileAttributes> remoteFiles = new Dictionary<string, BackupFileAttributes>(); foreach (IS3Object file in s3.ListObjects(Settings.Default.Bucket.BucketName)) { executor.CheckAbortion(); remoteFiles.Add(GetFileName(file.Key), new BackupFileAttributes(file.Size, file.LastModified, file.ETag)); if (remoteFiles.Count == 1000) { files.AddRemoteFiles(remoteFiles); remoteFiles.Clear(); } } files.AddRemoteFiles(remoteFiles); } catch (S3Exception e) { MessageBox.Show(e.Message); } } } finally { backupProgress.ExitAction(BackupAction.ListingBucket); } }
static Worksheet _sheet; //current worksheet #endregion Fields #region Methods public void parseMessage(String str) { Message m = Json.deserialize(str); switch (m.action) { case "init": //send the whoami message Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("type", "alex"); dict.Add("doctype", "spreadsheet"); dict.Add("setup", "desktop"); Message whoami = new Message("whoami", dict); net.send(Json.serialize(whoami)); dict.Clear(); //send the alex.imap message dict.Add("imap", "test"); Message imap = new Message("alex.imap", dict); net.send(Json.serialize(imap)); break; case "alex.select": default: MessageBox.Show(str); break; } }
public static List<CatTable> Fill(DbJet db) { OleDbDataReader reader = db.Read("select * from 0cat order by catord asc"); List<CatTable> tables = new List<CatTable>(); Dictionary<string, object> fields = new Dictionary<string, object>(); while (reader.Read()) { // Fields will help us to overcome non seq order fields.Clear(); for (int i = 0; i < reader.FieldCount; i++) { fields.Add(reader.GetName(i).ToLower(), reader.GetValue(i)); } CatTable table = new CatTable(); table.id = long.Parse(fields["id"].ToString()); table.name = fields["name"].ToString(); table.catord = long.Parse(fields["catord"].ToString()); table.lvl = long.Parse(fields["lvl"].ToString()); tables.Add(table); } return tables; }
public MainPage() { InitializeComponent(); xml = App.GetResourceStream(new Uri("dinesafe.xml", UriKind.Relative)); loadedData = XDocument.Load(xml.Stream); var data = from query in loadedData.Descendants("ROW") select new DineSafe { Name = (string)query.Attribute("N"), FoodType = (string)query.Attribute("T"), Address = (string)query.Attribute("A"), Status = (string)query.Attribute("S"), Details = (string)query.Attribute("D"), Date = (string)query.Attribute("I"), Severity = (string)query.Attribute("X") }; original = data.ToArray<DineSafe>(); Dictionary<string, short> seenEntries = new Dictionary<string, short>(); foreach (DineSafe dineSafe in data) { string key = dineSafe.GetKey(); if (!seenEntries.ContainsKey(key)) { uniques.Add(dineSafe); seenEntries.Add(key, 0); } } seenEntries.Clear(); array = uniques.ToArray(); }
public RootController() : base(new RootElement ("Netstat")) { Settings = Settings.Instance; section = new Section (); Root.Add (section); displayedEntries = new Dictionary<NetstatEntry,DateTime> (); RefreshRequested += (sender, e) => { Populate (); ReloadComplete (); }; Settings.Modified += (sender, e) => InvokeOnMainThread (() => { displayedEntries.Clear (); Populate (); }); timer = NSTimer.CreateRepeatingTimer (1.0, () => { if (View.Hidden || !Settings.AutoRefresh) return; Populate (); }); NSRunLoop.Main.AddTimer (timer, NSRunLoopMode.Default); }
public static bool IsmorphicString(string s, string t) { //"egg" "add" return true; //"foo" "bar" return false; //"paper" "title" return false; Dictionary<char, char> dic = new Dictionary<char, char>(); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(int i=0; i<s.Length; i++) { if (dic.ContainsKey(s[i])) sb1.Append(dic[s[i]]); else { dic.Add(s[i], Convert.ToChar(i)); sb1.Append(Convert.ToChar(i)); } } dic.Clear(); for(int i=0; i<t.Length;i++) { if (dic.ContainsKey(t[i])) sb2.Append(dic[t[i]]); else { dic.Add(t[i], Convert.ToChar(i)); sb2.Append(Convert.ToChar(i)); } } return sb1.ToString() == sb2.ToString(); }
private void GetTests() { methods = methods ?? new LinkedList<MethodInfo>(); methods.Clear(); status = status ?? new Dictionary<MethodInfo, Status>(); status.Clear(); toggleGroup = toggleGroup ?? new Dictionary<string, bool>(); var bindingFlags = BindingFlags.Public; bindingFlags |= BindingFlags.Static; bindingFlags |= BindingFlags.DeclaredOnly; Type[] typelist = GetTypesInNamespace("Exodrifter.ExpressionParser.Test"); for (int i = 0; i < typelist.Length; i++) { foreach (var method in typelist[i].GetMethods(bindingFlags)) { if (0 == method.GetParameters().Length) { methods.AddLast(method); status.Add(method, Status.UNKNOWN); if (!toggleGroup.ContainsKey(method.DeclaringType.Name)) { toggleGroup[method.DeclaringType.Name] = false; } } } } }
private void setupDeck(List<CardDB.cardIDEnum> cardsPlayed, List<CardDB.Card> deckGuessed, Dictionary<CardDB.cardIDEnum, int> knownCards) { deckGuessed.Clear(); knownCards.Clear(); foreach (CardDB.cardIDEnum crdidnm in cardsPlayed) { if (crdidnm == CardDB.cardIDEnum.GAME_005) continue; //(im sure, he has no coins in his deck :D) if (knownCards.ContainsKey(crdidnm)) { knownCards[crdidnm]++; } else { if (CardDB.Instance.getCardDataFromID(crdidnm).rarity == 5) { //you cant own rare ones more than once! knownCards.Add(crdidnm, 2); continue; } knownCards.Add(crdidnm, 1); } } foreach (KeyValuePair<CardDB.cardIDEnum, int> kvp in knownCards) { if (kvp.Value == 1) deckGuessed.Add(CardDB.Instance.getCardDataFromID(kvp.Key)); } }
public static void Main(string[] args) { /* List Operations */ List<int> list = new List<int>(); list.Add (10); list.AddRange (new List<int> () { 20, 30, 40 }); list.Remove (10); list.Insert (0, 10); list.Clear (); /* Dictionary Operations */ Dictionary<int, string> dictionary = new Dictionary<int, string> (); dictionary.Add (1, "Sanjana"); dictionary.Add (2, "Sumana"); dictionary.ContainsValue ("Sanjana"); dictionary.Remove (1); dictionary.Add (3, "Srinivas"); dictionary.Clear (); }
public unsafe static NetworkInterface[] GetLinuxNetworkInterfaces() { Dictionary<string, LinuxNetworkInterface> interfacesByName = new Dictionary<string, LinuxNetworkInterface>(); const int MaxTries = 3; for (int attempt = 0; attempt < MaxTries; attempt++) { int result = Interop.Sys.EnumerateInterfaceAddresses( (name, ipAddr, maskAddr) => { LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name); lni.ProcessIpv4Address(ipAddr, maskAddr); }, (name, ipAddr, scopeId) => { LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name); lni.ProcessIpv6Address( ipAddr, *scopeId); }, (name, llAddr) => { LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name); lni.ProcessLinkLayerAddress(llAddr); }); if (result == 0) { return interfacesByName.Values.ToArray(); } else { interfacesByName.Clear(); } } throw new NetworkInformationException(SR.net_PInvokeError); }
static void Main(string[] args) { string text; string patternRepl = @"\s{2,}"; Regex regexRepl = new Regex(patternRepl); string pattern = @"([^=&]+)=([^&=]+)"; Regex regex = new Regex(pattern); MatchCollection matches; var query = new Dictionary<string, List<string>>(); while (!((text = Console.ReadLine()) == "END")) { text = text.Replace("%20", " ").Replace("+", " ").Replace("?", "&"); text = regexRepl.Replace(text, " "); matches = regex.Matches(text); foreach (Match match in matches) { string field = match.Groups[1].ToString().Trim(); string value = match.Groups[2].ToString().Trim(); if (!query.ContainsKey(field)) { query.Add(field, new List<string>()); } query[field].Add(value); } foreach (string field in query.Keys) { Console.Write("{0}=[{1}]", field, string.Join(", ", query[field])); } Console.WriteLine(); query.Clear(); } }
public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method Clear ."); try { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("txt", "notepad.exe"); dictionary.Add("bmp", "paint.exe"); dictionary.Add("dib", "paint.exe"); dictionary.Add("rtf", "wordpad.exe"); dictionary.Clear(); int actual = dictionary.Count; int expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method Clear Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public void TestMostCommon() { var largest = new Dictionary<string, int>(); // Init a dictionary to store quantities of people of varying nationalities. Dictionary<string, int> dict = _dictionary; int max = dict.Values.Max(); foreach (var kvp in dict) { if (max == kvp.Value) largest.Add(kvp.Key, kvp.Value); } Assert.AreEqual(42, max); Assert.Contains("b", largest.Keys); Assert.Contains("d", largest.Keys); largest.Clear(); largest = dict.Where(kvp => max == kvp.Value).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); Assert.AreEqual(42, max); Assert.Contains("b", largest.Keys); Assert.Contains("d", largest.Keys); }
/// <summary> /// replace every <include/> node in the document with the nodes that it references /// </summary> /// <param name="dom"></param>= public void ProcessDom(string parentPath, XmlDocument dom) { Dictionary<string, XmlDocument> cachedDoms = new Dictionary<string, XmlDocument>(); cachedDoms.Add(parentPath, dom); ProcessDom(cachedDoms, null, dom); cachedDoms.Clear(); }
/// <summary> /// 新增区域,返回新增区域的对象 /// </summary> /// <param name="area"></param> /// <returns></returns> public object AddArea(Area area) { using (DBHelper db = DBHelper.Create()) { area.ID = Guid.NewGuid().ToString().Replace("-", ""); string selectCode = "select max(code) from T_Area where PID = @PID"; Dictionary<string, object> paramList = new Dictionary<string, object>(); paramList.Add("PID", area.PID); object maxCode = db.ExcuteScular(selectCode, paramList); string code = maxCode == null ? "" : maxCode.ToString(); string selectPCode = "select code from T_Area where ID = @ID"; paramList.Clear(); paramList.Add("ID", area.PID); object PCode = db.ExcuteScular(selectPCode, paramList); if (string.IsNullOrEmpty(code)) code = PCode + "0001"; else code = code.Substring(0, code.Length - 4) + (Convert.ToInt32(code.Substring(code.Length - 4)) + 1).ToString().PadLeft(4, '0'); area.Code = code; area.Code = PCode + area.Code; try { return db.Insert<Area>(area); } catch (System.Exception ex) { area.State = "1"; area.Errormsg = ex.Message; return area; } } }
public void WritePdb(SymbolData symData) { m_docWriters = new Dictionary<int, ISymbolDocumentWriter>(); ImageDebugDirectory debugDirectory; byte[] debugInfo = null; // Rather than use the emitter here, we are just careful enough to emit pdb metadata that // matches what is already in the assembly image. object emitter = null; // We must be careful to close the writer before updating the debug headers. The writer has an // open file handle on the assembly we want to update. m_writer = SymbolAccess.GetWriterForFile(m_symFormat, m_outputAssembly, ref emitter); // We don't actually need the emitter in managed code at all, so release the CLR reference on it Marshal.FinalReleaseComObject(emitter); try { WriteEntryPoint(symData.entryPointToken); WriteFiles(symData.sourceFiles); WriteMethods(symData.methods); debugInfo = m_writer.GetDebugInfo(out debugDirectory); } finally { m_writer.Close(); ((IDisposable)m_writer).Dispose(); m_writer = null; m_docWriters.Clear(); } UpdatePEDebugHeaders(debugInfo); }
//Given s string, Find max size of a sub-string, in which no duplicate chars present. public int MaxSubString(string str) { int max = 0; int count = 0; int current = 0; Dictionary<char, int> result = new Dictionary<char, int>(); while (current!=str.Length) { if (result.ContainsKey(str[current])) { if (count > max) { max = count; } count = 0; result.Clear(); str = str.Substring(current+1); current = 0; } else { result.Add(str[current], 1); count++; current++; } } if (count > max) max = count; return max; }
void LoadDictionary(Dictionary<int, string> dic, IniSection section) { dic.Clear(); if (section == null) return; foreach (IniKey iKey in section.Keys) { if (iKey.IsComment) continue; // entry is commented out string key = iKey.Name; string value = iKey.Value; #if DEBUG if (key.Trim().StartsWith("EOF")) break; // for testing purposes #else if (key.Trim().StartsWith("EOF")) continue; // ignore #endif if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) dic.Add(int.Parse(key), value); } }
static void GetQuaries(string consoleInput) { Dictionary<string, List<string>> result = new Dictionary<string,List<string>>(); string pattern = @"(?:\w+)(?:[\%\d\+])*=(?:[\%20|\+])*(([\w\d]*)(?:\%20|\+)*)*(?=[\n\b\&]|$)"; Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(consoleInput); foreach(Match match in matches) { string filteredQuery = FilterQuery(match.Value); string key = GetKey(filteredQuery).Trim(); string values = GetValues(filteredQuery).Trim(); if (!result.ContainsKey(key)) result.Add(key, new List<string>()); result[key].Add(values); } PrintQueries(result); Console.WriteLine(); result.Clear(); }
public static bool IsMatch(string testUrl,out IDictionary<string,object> paramter) { string clearUrl; var urlSplits = GetUrlSplit(testUrl,out clearUrl); if (urlSplits==null) { //首页自行处理 paramter = null; return false; } if (RouteMappings != null) { IDictionary<string, object> dict = new Dictionary<string, object>(); foreach (var match in RouteMappings) { dict.Clear(); if (match.IsMatch(urlSplits, ref dict)) { paramter = dict; return true; } } } paramter = null; return false; }
public void Bind(MapperGenerator.Library.Model.TemplateSource.FileModel model, Dictionary<TreeNode, object> templateFileModelMap, TreeView treeFileTemplateModel) { treeFileTemplateModel.Nodes.Clear(); templateFileModelMap.Clear(); var fileNode = new TreeNode("File"); templateFileModelMap.Add(fileNode, model); foreach (var ns in model.Namespaces) { var nsNode = new TreeNode(ns.Name.PascalCase); templateFileModelMap.Add(nsNode, ns); foreach (var cs in ns.Entities) { var csNode = new TreeNode(cs.Name.PascalCase); templateFileModelMap.Add(csNode, cs); foreach (var ps in cs.Properties) { var psNode = new TreeNode(ps.Name.PascalCase); templateFileModelMap.Add(psNode, ps); csNode.Nodes.Add(psNode); } nsNode.Nodes.Add(csNode); } fileNode.Nodes.Add(nsNode); } treeFileTemplateModel.Nodes.Add(fileNode); treeFileTemplateModel.SelectedNode = fileNode; treeFileTemplateModel.ExpandAll(); }
public static void Main(string[] args) { Dictionary<string,int> dict=new Dictionary<string,int>(); dict.Add("one",1); dict.Add("two",2); dict.Add("three",3); dict.Add("four",4); dict.Remove("one"); Console.WriteLine(dict.ContainsKey("dsaf")); Console.WriteLine("Key Value Pairs after Dictionary related operations:"); foreach (var pair in dict) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } dict.Clear (); List<string> strList = new List<string> (); strList.Add ("one"); strList.Add ("two"); strList.Add ("three"); strList.Add ("four"); strList.Add ("five"); strList.Insert (3, "great"); string[] newList = new string[3]{ "ten", "eleven", "twelve" }; strList.AddRange (newList); strList.InsertRange (3, newList); Console.WriteLine ("Output after all list related operations i.e. add, insert, addrange, insertrange,remove"); foreach (var i in strList) Console.WriteLine (i); }
/// <summary> /// Clear the replacement values. /// </summary> static public void ClearReplacements() { mReplacement.Clear(); }
public void Clear() { Dictionary.Clear(); }
// Token: 0x060009CA RID: 2506 RVA: 0x00030EF8 File Offset: 0x0002F0F8 public static void CollectAchievementDefs(Dictionary<string, AchievementDef> map) { List<AchievementDef> list = new List<AchievementDef>(); map.Clear(); foreach (Type type2 in from type in typeof(BaseAchievement).Assembly.GetTypes() where type.IsSubclassOf(typeof(BaseAchievement)) orderby type.Name select type) { RegisterAchievementAttribute registerAchievementAttribute = (RegisterAchievementAttribute)type2.GetCustomAttributes(false).FirstOrDefault((object v) => v is RegisterAchievementAttribute); if (registerAchievementAttribute != null) { if (map.ContainsKey(registerAchievementAttribute.identifier)) { Debug.LogErrorFormat("Class {0} attempted to register as achievement {1}, but class {2} has already registered as that achievement.", new object[] { type2.FullName, registerAchievementAttribute.identifier, AchievementManager.achievementNamesToDefs[registerAchievementAttribute.identifier].type.FullName }); } else { AchievementDef achievementDef = new AchievementDef { identifier = registerAchievementAttribute.identifier, unlockableRewardIdentifier = registerAchievementAttribute.unlockableRewardIdentifier, prerequisiteAchievementIdentifier = registerAchievementAttribute.prerequisiteAchievementIdentifier, nameToken = "ACHIEVEMENT_" + registerAchievementAttribute.identifier.ToUpper() + "_NAME", descriptionToken = "ACHIEVEMENT_" + registerAchievementAttribute.identifier.ToUpper() + "_DESCRIPTION", iconPath = "Textures/AchievementIcons/tex" + registerAchievementAttribute.identifier + "Icon", type = type2, serverTrackerType = registerAchievementAttribute.serverTrackerType }; AchievementManager.achievementIdentifiers.Add(registerAchievementAttribute.identifier); map.Add(registerAchievementAttribute.identifier, achievementDef); list.Add(achievementDef); UnlockableDef unlockableDef = UnlockableCatalog.GetUnlockableDef(achievementDef.unlockableRewardIdentifier); if (unlockableDef != null) { unlockableDef.getHowToUnlockString = (() => Language.GetStringFormatted("UNLOCK_VIA_ACHIEVEMENT_FORMAT", new object[] { Language.GetString(achievementDef.nameToken), Language.GetString(achievementDef.descriptionToken) })); unlockableDef.getUnlockedString = (() => Language.GetStringFormatted("UNLOCKED_FORMAT", new object[] { unlockableDef.getHowToUnlockString() })); } } } } AchievementManager.achievementDefs = list.ToArray(); AchievementManager.SortAchievements(AchievementManager.achievementDefs); AchievementManager.serverAchievementDefs = (from achievementDef in AchievementManager.achievementDefs where achievementDef.serverTrackerType != null select achievementDef).ToArray<AchievementDef>(); for (int i = 0; i < AchievementManager.achievementDefs.Length; i++) { AchievementManager.achievementDefs[i].index = new AchievementIndex { intValue = i }; } for (int j = 0; j < AchievementManager.serverAchievementDefs.Length; j++) { AchievementManager.serverAchievementDefs[j].serverIndex = new ServerAchievementIndex { intValue = j }; } for (int k = 0; k < AchievementManager.achievementIdentifiers.Count; k++) { string currentAchievementIdentifier = AchievementManager.achievementIdentifiers[k]; map[currentAchievementIdentifier].childAchievementIdentifiers = (from v in AchievementManager.achievementIdentifiers where map[v].prerequisiteAchievementIdentifier == currentAchievementIdentifier select v).ToArray<string>(); } Action action = AchievementManager.onAchievementsRegistered; if (action == null) { return; } action(); }
public void FlushInputCache() { InputStateCache.Clear(); }
public string GetRtf(Range r) { this.tb = r.tb; var styles = new Dictionary <StyleIndex, object>(); var sb = new StringBuilder(); var tempSB = new StringBuilder(); var currentStyleId = StyleIndex.None; r.Normalize(); int currentLine = r.Start.iLine; styles[currentStyleId] = null; colorTable.Clear(); // var lineNumberColor = GetColorTableNumber(r.tb.LineNumberColor); if (IncludeLineNumbers) { tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", currentLine + 1, lineNumberColor); } // foreach (Place p in r) { Char c = r.tb[p.iLine][p.iChar]; if (c.style != currentStyleId) { Flush(sb, tempSB, currentStyleId); currentStyleId = c.style; styles[currentStyleId] = null; } if (p.iLine != currentLine) { for (int i = currentLine; i < p.iLine; i++) { tempSB.AppendLine(@"\line"); if (IncludeLineNumbers) { tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", i + 2, lineNumberColor); } } currentLine = p.iLine; } switch (c.c) { case '\\': tempSB.Append(@"\\"); break; case '{': tempSB.Append(@"\{"); break; case '}': tempSB.Append(@"\}"); break; default: var ch = c.c; var code = (int)ch; if (code < 128) { tempSB.Append(c.c); } else { tempSB.AppendFormat(@"{{\u{0}}}", code); } break; } } Flush(sb, tempSB, currentStyleId); //build color table var list = new SortedList <int, Color>(); foreach (var pair in colorTable) { list.Add(pair.Value, pair.Key); } tempSB.Length = 0; tempSB.AppendFormat(@"{{\colortbl;"); foreach (var pair in list) { tempSB.Append(GetColorAsString(pair.Value) + ";"); } tempSB.AppendLine("}"); // if (UseOriginalFont) { sb.Insert(0, string.Format(@"{{\fonttbl{{\f0\fmodern {0};}}}}{{\fs{1} ", tb.Font.Name, (int)(2 * tb.Font.SizeInPoints), tb.CharHeight)); sb.AppendLine(@"}"); } sb.Insert(0, tempSB.ToString()); sb.Insert(0, @"{\rtf1\ud\deff0"); sb.AppendLine(@"}"); return(sb.ToString()); }
public static void ClearReq() { reqs.Clear(); }
private string Generate(Solution solution, List <Solution.Configuration> configurations, string solutionPath, string solutionFile, out bool updated) { // Create the target folder (solutions and projects are folders in XCode). string solutionFolder = Util.GetCapitalizedPath(solutionPath + Path.DirectorySeparatorChar + solutionFile + SolutionExtension); Directory.CreateDirectory(solutionFolder); // Main solution file. string solutionFileContentsPath = solutionFolder + Path.DirectorySeparatorChar + SolutionContentsFileName; FileInfo solutionFileContentsInfo = new FileInfo(solutionFileContentsPath); bool projectsWereFiltered; List <Solution.ResolvedProject> solutionProjects = solution.GetResolvedProjects(configurations, out projectsWereFiltered).ToList(); solutionProjects.Sort((a, b) => string.Compare(a.ProjectName, b.ProjectName)); // Ensure all projects are always in the same order to avoid random shuffles // Move the first executable project on top. foreach (Solution.ResolvedProject resolvedProject in solutionProjects) { if (resolvedProject.Configurations[0].Output == Project.Configuration.OutputType.Exe) { solutionProjects.Remove(resolvedProject); solutionProjects.Insert(0, resolvedProject); break; } } if (solutionProjects.Count == 0) { updated = solutionFileContentsInfo.Exists; if (updated) { File.Delete(solutionFileContentsPath); } return(solutionFolder); } var fileGenerator = new FileGenerator(); fileGenerator.Write(Template.Header); _solutionFolderCache.Clear(); List <SolutionFile> solutionsFiles = solutionProjects.Select(project => { var solutionFileItem = new SolutionFile() { Name = project.ProjectFile, Parent = ParseSolutionFolder(project.SolutionFolder) }; solutionFileItem.RegisterToParent(); return(solutionFileItem); }).ToList(); List <SolutionItem> solutionsItems = solutionsFiles.GroupBy(solutionsItem => solutionsItem.GetRoot()).Select(group => group.Key).ToList(); solutionsItems.Sort((a, b) => string.Compare(a.Name, b.Name)); foreach (var solutionItem in solutionsItems) { //Sort of folders content (solutionItem as SolutionFolder)?.Sort(); WriteSolutionItem(fileGenerator, solutionItem); } fileGenerator.Write(Template.Footer); // Write the solution file updated = _builder.Context.WriteGeneratedFile(solution.GetType(), solutionFileContentsInfo, fileGenerator.ToMemoryStream()); return(solutionFileContentsInfo.FullName); }
public void Clear() { items.Clear(); InvokeOnChanged(); }
internal void ClearUsedEdges() { _usedEdges.Clear(); }
/// <summary> /// Clear all branches for this event /// </summary> public void ClearBranches() { Dictionary <string, ConditionState> branches = GetBranches(); branches.Clear(); }
// public static void RemoveAll() { customCacheDictionary.Clear(); customCacheDictionary = new Dictionary <string, KeyValuePair <object, DateTime> >(); }
public void Clear() { _typeLookup.Clear(); }
private void parseIniFile(string[] lines) { // Clear already parsed ini file data ParsedIniFile.Clear(); // Specify current section string currentSection = ""; // For each line in ini file foreach (string line in lines) { // If line starts with '[', it is a section if (line.StartsWith("[")) { int length = line.Length - 1; // Line should end with a ']' // But if it doesn't, we don't want to halt the entire program if (line.EndsWith("]")) { length--; } // Get section of line with section name string sectionName = line.Substring(1, length); // Set current section to newly parsed currentSection = sectionName; // Check/add section to parsed data if (!ParsedIniFile.ContainsKey(currentSection)) { ParsedIniFile.Add(currentSection, new Dictionary <string, string>()); } } else { // If line doesn't start with [, it is a key/value pair int index = line.IndexOf('='); // If line contains no '=', skip as it's invalid if (index < 0) { continue; } // Get key from line and trim whitespace string key = line.Substring(0, index).Trim(); string value = ""; // If '=' character is last character, the value is empty // We check for the opposite to see if there is a value if (line.Length - 1 != index) { // Get value from line and trim whitespace value = line.Substring(index + 1).Trim(); } // Add key/value pair to parsed ini file data ParsedIniFile[currentSection].Add(key, value); } } }
private void reset() { Characters.Clear(); }
public void CalcBar( ) { List<ImgFile> imList; _il.ImgListOut(out imList); DateTime dtOriginal = DateTime.MinValue; DateTime nullDate = DateTime.MinValue; DateTime minDate = DateTime.MaxValue; DateTime maxDate = DateTime.MinValue; int fCount = 0; int fCountExif = -1; int dateCount = 0; DateTime priorDate = DateTime.MinValue; var spanDict = new Dictionary<int, int>(); _posList.Clear(); _priorList.Clear(); _rangeDict.Clear(); // dict for time gaps foreach (ImgFile imf in imList) { string picPath = imf.fName; dtOriginal = imf.fDateOriginal; fCount++; string fName = Path.GetFileName(picPath); int pPos = fName.IndexOf("+"); if (pPos > -1){ _posList.Add(fCount); } if (dtOriginal != nullDate){ //Debug.WriteLine("path: " + picPath + " " + dtOriginal.ToString()); fCountExif = fCount; dateCount++; imf.fDateOriginal = dtOriginal; if (priorDate > dtOriginal){ //Debug.WriteLine("prior date: " + fCount); _priorList.Add(fCount); } if (minDate > dtOriginal) minDate = dtOriginal; if (maxDate < dtOriginal) maxDate = dtOriginal; if (dateCount > 1){ TimeSpan span = dtOriginal.Subtract(priorDate); int spanSec = Math.Abs((int) span.TotalSeconds); spanDict.Add(fCount, spanSec); } priorDate = dtOriginal; } else { // no exif date if (fCountExif == fCount - 1){ // gap to exif date spanDict.Add(fCount, Int32.MaxValue); } } } // span values if (dateCount > 0){ TimeSpan imgSpan = maxDate.Subtract(minDate); //Debug.WriteLine("min: " + minDate.ToString() + " max: " + maxDate.ToString()); //Debug.WriteLine("range: " + imgSpan.ToString()); int mean = (int) imgSpan.TotalSeconds / dateCount; long sumVar = 0; foreach (KeyValuePair<int, int> sd in spanDict) { if (sd.Value != Int32.MaxValue){ long var = (long) Math.Pow((mean - sd.Value), 2); sumVar += var; //Debug.WriteLine("F Num: " + dfn.Key + " " + dfn.Value); } } int stdDev = (int) Math.Sqrt(sumVar / dateCount); //Debug.WriteLine("mean / std: {0}/{1}", mean, stdDev); int breakVal = mean + stdDev * 2; //int wi = 2; if (imgSpan.TotalDays > 730){ _rangeType = 1; // years } else if (imgSpan.TotalDays > 60){ _rangeType = 2; // months } else if (imgSpan.TotalDays > 1){ _rangeType = 3; // days } else { _rangeType = 4; // hours } int i = 0; // largest breaks string p0Path = ""; if (_il.DirPathPos(ref p0Path, 1)){ ExifRead.ExifODate(out _r0Date, p0Path); } foreach (KeyValuePair<int, int> sd in spanDict.OrderByDescending(key=> key.Value)) { i++; //Debug.WriteLine("pic no / dist: {0}/{1}", sd.Key, sd.Value); if (sd.Value < breakVal) break; string piPath = ""; DateTime dOriginal = nullDate; if (_il.DirPathPos(ref piPath, sd.Key)){ ExifRead.ExifODate(out dOriginal, piPath); } _rangeDict.Add(sd.Key, dOriginal); } } }
/// <summary> /// Called on the manager's close. /// </summary> void IHub.Close() { SentMessages.Clear(); }
public void ResetTypeHandlers() { _typeHandlers.Clear(); }
public static void ClearCache() { CachedTextures.Clear(); }
public void Clear() { FreeAllBusy(); cacheDic.Clear(); cache.Clear(); }
/// <summary> /// Clears all the entries. /// </summary> public void Clear() { m_dictionary.Clear(); }
public static void clearEventIDs() { eventIDs.Clear(); }
/// <summary> /// Clears all resources from collection. /// </summary> public void Clear() { resourceDescs.Clear(); }
public static void ClearCache() => _keyCache.Clear();
public void Clear() { cache.Clear(); accessTimes.Clear(); cleanupCalls = 0; }
/// <summary> /// Resets the list of providers /// </summary> public static void ResetProviders() { s_Providers.Clear(); }
public void ClearAll() { _publishers.Clear(); }
public new void Layout(List <string> PrimaryKeys) { //選取的結點的完整路徑 List <string> selectPath = new List <string>(); #region 記錄選取的結點的完整路徑 var selectNode = advTree1.SelectedNode; if (selectNode != null) { while (selectNode != null) { selectPath.Insert(0, selectNode.Text); selectNode = selectNode.Parent; } } #endregion advTree1.Nodes.Clear(); items.Clear(); // 取得刪除教師 ID List <string> DeletedTeacheIDList = new List <string>(); List <string> checkDeletedTeacheIDList = new List <string>(); List <JHSchool.Data.JHTeacherRecord> TeacherRecs = JHSchool.Data.JHTeacher.SelectAll(); foreach (JHSchool.Data.JHTeacherRecord tr in TeacherRecs) { if (tr.Status == K12.Data.TeacherRecord.TeacherStatus.刪除) { DeletedTeacheIDList.Add(tr.ID); } } SortedList <int?, List <string> > gradeYearList = new SortedList <int?, List <string> >(); List <string> noGradYearList = new List <string>(); DevComponents.AdvTree.Node rootNode = new DevComponents.AdvTree.Node(); int TotalCount = 0; foreach (var key in PrimaryKeys) { // 過濾刪除教師 if (DeletedTeacheIDList.Contains(key)) { checkDeletedTeacheIDList.Add(key); continue; } var teacherRec = Teacher.Instance.Items[key]; foreach (var classRec in Class.Instance.GetTecaherSupervisedClass(teacherRec)) { string gradeYear = (classRec == null ? "" : classRec.GradeYear); int gyear = 0; int?g; if (int.TryParse(gradeYear, out gyear)) { g = gyear; if (!gradeYearList.ContainsKey(g)) { gradeYearList.Add(g, new List <string>()); } if (!gradeYearList[g].Contains(key)) { gradeYearList[g].Add(key); } } else { g = null; if (!noGradYearList.Contains(key)) { noGradYearList.Add(key); } } } } foreach (var gyear in gradeYearList.Keys) { DevComponents.AdvTree.Node gyearNode = new DevComponents.AdvTree.Node(); switch (gyear) { //case 1: // gyearNode.Text = "一年級"; // break; //case 2: // gyearNode.Text = "二年級"; // break; //case 3: // gyearNode.Text = "三年級"; // break; //case 4: // gyearNode.Text = "四年級"; // break; default: gyearNode.Text = "" + gyear + "年級"; break; } // TotalCount += gradeYearList[gyear].Count; gyearNode.Text += "(" + gradeYearList[gyear].Count + ")"; items.Add(gyearNode, gradeYearList[gyear]); rootNode.Nodes.Add(gyearNode); } List <string> tmp = new List <string>(); foreach (List <string> strList in gradeYearList.Values) { foreach (string str in strList) { if (!tmp.Contains(str)) { tmp.Add(str); } } } if (noGradYearList.Count > 0) { // TotalCount += noGradYearList.Count; DevComponents.AdvTree.Node gyearNode = new DevComponents.AdvTree.Node(); gyearNode.Text = "未分年級" + "(" + noGradYearList.Count + ")"; items.Add(gyearNode, noGradYearList); rootNode.Nodes.Add(gyearNode); } rootNode.Text = "所有班導師(" + TotalCount + ")"; rootNode.Expand(); advTree1.Nodes.Add(rootNode); // 這裡在加入所有班導師 teacherKeys.Clear(); //foreach (List<string> str in gradeYearList.Values) // teacherKeys.AddRange(str); // 有年級 foreach (string str in tmp) { teacherKeys.Add(str); } // 無年級 foreach (string str in noGradYearList) { if (!teacherKeys.Contains(str)) { teacherKeys.Add(str); } } TotalCount = teacherKeys.Count; rootNode.Text = "所有班導師(" + TotalCount + ")"; //items.Add(rootNode, PrimaryKeys); items.Add(rootNode, teacherKeys); if (selectPath.Count != 0) { selectNode = SelectNode(selectPath, 0, advTree1.Nodes); if (selectNode != null) { advTree1.SelectedNode = selectNode; } } // 加入刪除教師 if (checkDeletedTeacheIDList.Count > 0) { //TotalCount += DeletedTeacheIDList.Count; DevComponents.AdvTree.Node DelTeacheNode = new DevComponents.AdvTree.Node(); DelTeacheNode.Text = "刪除教師" + "(" + checkDeletedTeacheIDList.Count + ")"; items.Add(DelTeacheNode, checkDeletedTeacheIDList); advTree1.Nodes.Add(DelTeacheNode); //rootNode.Nodes.Add(DelTeacheNode); } // 非班導師 // 是班導師ID List <string> isClassTeacherID = new List <string>(); List <string> NotClassTeacherID = new List <string>(); foreach (JHSchool.Data.JHClassRecord classRec in JHSchool.Data.JHClass.SelectAll()) { isClassTeacherID.Add(classRec.RefTeacherID); } foreach (JHSchool.Data.JHTeacherRecord teachRec in JHSchool.Data.JHTeacher.SelectAll()) { if (!isClassTeacherID.Contains(teachRec.ID)) { if (teachRec.Status == K12.Data.TeacherRecord.TeacherStatus.一般) { NotClassTeacherID.Add(teachRec.ID); } } } DevComponents.AdvTree.Node NotClassTeacherNode = new DevComponents.AdvTree.Node(); NotClassTeacherNode.Text = "非班導師 (" + NotClassTeacherID.Count + ")"; items.Add(NotClassTeacherNode, NotClassTeacherID); advTree1.Nodes.Add(NotClassTeacherNode); //advTree1.Focus(); }
public Bitmap ResolveObjects( TangraConfig.PhotometryReductionMethod photometryReductionMethod, TangraConfig.PsfQuadrature psfQuadrature, TangraConfig.PsfFittingMethod psfFittingMethod, TangraConfig.BackgroundMethod backgroundMethod, TangraConfig.PreProcessingFilter filter, Guid magnitudeBandId, Rectangle osdRectangleToExclude, Rectangle rectToInclude, bool limitByInclusion, IAstrometrySettings astrometrySettings, ObjectResolverSettings objectResolverSettings) { m_AstrometrySettings = astrometrySettings; StarMap starMap = new StarMap( astrometrySettings.PyramidRemoveNonStellarObject, astrometrySettings.MinReferenceStarFWHM, astrometrySettings.MaxReferenceStarFWHM, astrometrySettings.MaximumPSFElongation, astrometrySettings.LimitReferenceStarDetection); starMap.FindBestMap(StarMapInternalConfig.Default, m_Image, osdRectangleToExclude, rectToInclude, limitByInclusion); float r0 = 0; m_MagnitudeFit = StarMagnitudeFit.PerformFit( m_AstrometryController, m_VideoController, m_Image.Pixelmap.BitPixCamera, m_Image.Pixelmap.MaxSignalValue, m_Astrometry.FitInfo, photometryReductionMethod, psfQuadrature, psfFittingMethod, backgroundMethod, filter, m_Stars, magnitudeBandId, 1.0f, TangraConfig.KnownCameraResponse.Undefined, null, null, null, ref r0); m_BackgroundFlux = m_MagnitudeFit.GetBackgroundIntencity(); m_BackgroundMag = m_MagnitudeFit.GetMagnitudeForIntencity(m_BackgroundFlux); if (TangraConfig.Settings.TraceLevels.PlateSolving.TraceVerbose()) { Trace.WriteLine(string.Format("Plate FWHM: {0}", 2 * Math.Sqrt(Math.Log(2)) * r0)); } PeakPixelResolver resolver = new PeakPixelResolver(m_Image); resolver.ResolvePeakPixels(osdRectangleToExclude, rectToInclude, limitByInclusion, objectResolverSettings.ExcludeEdgeAreaPixels, objectResolverSettings.MinDistanceBetweenPeakPixels); List <double> identifiedMagnitudes = new List <double>(); List <double> identifiedR0s = new List <double>(); m_IdentifiedObjects.Clear(); m_UidentifiedObjects.Clear(); foreach (KeyValuePair <int, int> peakPixel in resolver.PeakPixels.Keys) { int x = peakPixel.Key; int y = peakPixel.Value; bool isSaturated; double intencity = m_MagnitudeFit.GetIntencity(new ImagePixel(255, x, y), out isSaturated); double magnitude = m_MagnitudeFit.GetMagnitudeForIntencity(intencity); if (magnitude < m_MaxMagForAstrometry) { double RADeg, DEDeg; PSFFit fit; starMap.GetPSFFit(x, y, PSFFittingMethod.NonLinearFit, out fit); if (fit.IMax < 0) { continue; } if (fit.IMax < fit.I0) { continue; } if (fit.Certainty < objectResolverSettings.MinCertainty) { continue; } if (fit.FWHM < objectResolverSettings.MinFWHM) { continue; } if (fit.IMax - fit.I0 < objectResolverSettings.MinAmplitude) { continue; } m_Astrometry.GetRADEFromImageCoords(fit.XCenter, fit.YCenter, out RADeg, out DEDeg); // All stars closer than 2 arcsec to this position List <IStar> matchingStars = m_Stars.Where(s => Math.Abs(AngleUtility.Elongation(s.RADeg, s.DEDeg, RADeg, DEDeg) * 3600.0) < objectResolverSettings.MaxStarMatchMagDif).ToList(); bool identified = false; if (matchingStars.Count >= 1) { foreach (IStar star in matchingStars) { if (objectResolverSettings.MaxStarMatchMagDif >= Math.Abs(magnitude - star.Mag)) { // The star is identified. Do we care more? if (TangraConfig.Settings.TraceLevels.PlateSolving.TraceVerbose()) { Trace.WriteLine(string.Format("STAR ({0}, {1}) No -> {2}; Mag -> {3} (Expected: {4}); R0 = {5}", x, y, star.StarNo, magnitude.ToString("0.00"), star.Mag.ToString("0.00"), fit.R0.ToString("0.0"))); } identifiedMagnitudes.Add(magnitude); identifiedR0s.Add(fit.R0); m_IdentifiedObjects.Add(fit, star); identified = true; break; } } } if (matchingStars.Count == 0 || !identified) { // The object is not in the star database // TODO: Test for hot pixel. Match to hot pixel profile from the brightest pixel in the area m_UidentifiedObjects.Add(fit, magnitude); } } else { // Don't bother with too faint objects } } if (m_IdentifiedObjects.Count > 0) { double mean = identifiedR0s.Average(); double variance = 0; foreach (double rr0 in identifiedR0s) { variance += (rr0 - mean) * (rr0 - mean); } variance = Math.Sqrt(variance / (m_IdentifiedObjects.Count - 1)); double minR0 = mean - variance; double maxR0 = mean + variance; identifiedMagnitudes.Sort(); double maxStarMag = identifiedMagnitudes[Math.Max(0, (int)Math.Truncate(0.9 * identifiedMagnitudes.Count))]; if (TangraConfig.Settings.TraceLevels.PlateSolving.TraceVerbose()) { Trace.WriteLine(string.Format("Max Star Mag: {0}; R0 ({1}, {2})", maxStarMag.ToString("0.00"), minR0.ToString("0.0"), maxR0.ToString("0.0"))); } // NOTE: The R0 exclusion may ignore bright comets ! m_UnknownObjects = m_UidentifiedObjects .Where(p => p.Value < maxStarMag && p.Key.R0 >= minR0 && p.Key.R0 <= maxR0) .ToDictionary(p => p.Key, p => p.Value); if (TangraConfig.Settings.TraceLevels.PlateSolving.TraceVerbose()) { foreach (PSFFit obj in m_UnknownObjects.Keys) { Trace.WriteLine(string.Format("UNK: ({0}, {1}) Mag -> {2}; R0 = {3}", obj.XCenter.ToString("0.0"), obj.YCenter.ToString("0.0"), m_UnknownObjects[obj].ToString("0.00"), obj.R0.ToString("0.0"))); } } } Bitmap bitmap = m_Image.Pixelmap.CreateDisplayBitmapDoNotDispose(); using (Graphics g = Graphics.FromImage(bitmap)) { foreach (PSFFit star in m_IdentifiedObjects.Keys) { float x = (float)star.XCenter; float y = (float)star.YCenter; g.DrawEllipse(Pens.GreenYellow, x - 5, y - 5, 10, 10); } foreach (PSFFit star in m_UnknownObjects.Keys) { float x = (float)star.XCenter; float y = (float)star.YCenter; g.DrawEllipse(Pens.Tomato, x - 8, y - 8, 16, 16); } g.Save(); } return(bitmap); }
/// <summary> /// Clears the values stored in the current instance. /// </summary> public override void Clear () { SimpleTags.Clear(); }
static void Main(string[] args) { string line = Console.ReadLine(); Dictionary <string, List <int> > info = new Dictionary <string, List <int> >(); while (line != "Results") { string[] tokens = line.Split(":", StringSplitOptions.RemoveEmptyEntries); string command = tokens[0]; if (command == "Add") { string person = tokens[1]; int health = int.Parse(tokens[2]); int energy = int.Parse(tokens[3]); if (info.ContainsKey(person)) { info[person][0] += health; } else { info.Add(person, new List <int>() { health, energy }); } } else if (command == "Attack") { string attacker = tokens[1]; string defender = tokens[2]; int demage = int.Parse(tokens[3]); if (info.ContainsKey(attacker) && info.ContainsKey(defender)) { info[defender][0] -= demage; info[attacker][1] -= 1; if (info[defender][0] <= 0) { Console.WriteLine($"{defender} was disqualified!"); info.Remove(defender); } if (info[attacker][1] == 0) { Console.WriteLine($"{attacker} was disqualified!"); info.Remove(attacker); } } } else if (command == "Delete") { string action = tokens[1]; if (action == "All") { info.Clear(); } if (info.ContainsKey(action)) { info.Remove(action); } } line = Console.ReadLine(); } Console.WriteLine($"People count: {info.Count}"); foreach (var item in info.OrderByDescending(x => x.Value[0]).ThenBy(x => x.Key)) { Console.WriteLine($"{item.Key} - {item.Value[0]} - {item.Value[1]}"); } }