/// <summary>Expert: called when re-writing queries under MultiSearcher. /// /// Create a single query suitable for use by all subsearchers (in 1-1 /// correspondence with queries). This is an optimization of the OR of /// all queries. We handle the common optimization cases of equal /// queries and overlapping clauses of boolean OR queries (as generated /// by MultiTermQuery.rewrite() and RangeQuery.rewrite()). /// Be careful overriding this method as queries[0] determines which /// method will be called and is not necessarily of the same type as /// the other queries. /// </summary> public virtual Query Combine(Query[] queries) { System.Collections.Hashtable uniques = new System.Collections.Hashtable(); for (int i = 0; i < queries.Length; i++) { Query query = queries[i]; BooleanClause[] clauses = null; // check if we can split the query into clauses bool splittable = (query is BooleanQuery); if (splittable) { BooleanQuery bq = (BooleanQuery)query; splittable = bq.IsCoordDisabled(); clauses = bq.GetClauses(); for (int j = 0; splittable && j < clauses.Length; j++) { splittable = (clauses[j].GetOccur() == BooleanClause.Occur.SHOULD); } } if (splittable) { for (int j = 0; j < clauses.Length; j++) { Query tmp = clauses[j].GetQuery(); if (uniques.Contains(tmp) == false) { uniques.Add(tmp, tmp); } } } else { if (uniques.Contains(query) == false) { uniques.Add(query, query); } } } // optimization: if we have just one query, just return it if (uniques.Count == 1) { System.Collections.IDictionaryEnumerator iter = uniques.GetEnumerator(); iter.MoveNext(); return(iter.Value as Query); } System.Collections.IDictionaryEnumerator it = uniques.GetEnumerator(); BooleanQuery result = new BooleanQuery(true); while (it.MoveNext()) { result.Add((Query)it.Value, BooleanClause.Occur.SHOULD); } return(result); }
// Dump all the raw entries public void DumpKeys() { Console.WriteLine("*** Debug dump of keys in scope #{0},{1} [", this.m_id, this.m_szDebugName); System.Collections.IDictionaryEnumerator e = m_table.GetEnumerator(); while (e.MoveNext()) { string str = (string)e.Key; SymEntry sym = (SymEntry)e.Value; Console.WriteLine("{0} is a {1}", str, sym.ToString()); } Console.WriteLine("] End dump"); }
private static System.Collections.Hashtable DifFiles(System.String[] files1, System.String[] files2) { System.Collections.Hashtable set1 = new System.Collections.Hashtable(); System.Collections.Hashtable set2 = new System.Collections.Hashtable(); System.Collections.Hashtable extra = new System.Collections.Hashtable(); for (int x = 0; x < files1.Length; x++) { SupportClass.CollectionsHelper.AddIfNotContains(set1, files1[x]); } for (int x = 0; x < files2.Length; x++) { SupportClass.CollectionsHelper.AddIfNotContains(set2, files2[x]); } System.Collections.IEnumerator i1 = set1.GetEnumerator(); while (i1.MoveNext()) { System.Object o = i1.Current; if (!set2.Contains(o)) { SupportClass.CollectionsHelper.AddIfNotContains(extra, o); } } System.Collections.IEnumerator i2 = set2.GetEnumerator(); while (i2.MoveNext()) { System.Object o = i2.Current; if (!set1.Contains(o)) { SupportClass.CollectionsHelper.AddIfNotContains(extra, o); } } return(extra); }
//fieldname MUST be interned prior to this call private static void GetTerms(Query query, System.Collections.Hashtable terms, bool prohibited, System.String fieldName) { try { if (query is BooleanQuery) { GetTermsFromBooleanQuery((BooleanQuery)query, terms, prohibited, fieldName); } else if (query is FilteredQuery) { GetTermsFromFilteredQuery((FilteredQuery)query, terms, prohibited, fieldName); } else { System.Collections.Hashtable nonWeightedTerms = new System.Collections.Hashtable(); query.ExtractTerms(nonWeightedTerms); System.Collections.IDictionaryEnumerator iter = nonWeightedTerms.GetEnumerator(); while (iter.MoveNext()) { Term term = (Term)iter.Value; if ((fieldName == null) || (term.Field() == fieldName)) { WeightedTerm temp = new WeightedTerm(query.GetBoost(), term.Text()); terms.Add(temp, temp); } } } } catch (System.NotSupportedException ignore) { //this is non-fatal for our purposes } }
/// <summary> /// 判断某用户是否已经登录,并强迫登录用户下线。可以放到页面基类里面实时监测。 /// </summary> /// <param name="id">为用户ID或用户名这个必须是用户的唯一标识</param> /// <returns>flase为没有登陆 true为被迫下线</returns> public bool ValidateForceLogin() { bool flag = false; System.Collections.Hashtable ht = (System.Collections.Hashtable)HttpContext.Current.Application[appKey]; if (ht != null) { System.Collections.IDictionaryEnumerator IDE = ht.GetEnumerator(); while (IDE.MoveNext()) { //找到自己的登陆ID if (IDE.Key.ToString().Equals(HttpContext.Current.Session.SessionID)) { //判断用户是否被注销 if (IDE.Value.ToString().Equals(logout)) { ht.Remove(HttpContext.Current.Session.SessionID); HttpContext.Current.Application.Lock(); HttpContext.Current.Application[appKey] = ht; HttpContext.Current.Application.UnLock(); HttpContext.Current.Session.RemoveAll(); //HttpContext.Current.Response.Write("<script type='text/javascript'>alert('你的帐号已在别处登陆,你被强迫下线!')</script>"); flag = true; } break; } } } return(flag); }
public override unsafe void SetPixels(System.Collections.Hashtable coordsAndColors) { SurfaceDescription sd = this.m_tx.GetLevelDescription(0); int nPitch; //uint* pData = (uint*)this.m_tx.LockRectangle(0, // LockFlags.None, out nPitch).InternalData.ToPointer(); uint[,] data = (uint[, ]) this.m_tx.LockRectangle(typeof(uint), 0, LockFlags.None, sd.Width, sd.Height); System.Collections.IDictionaryEnumerator en = coordsAndColors.GetEnumerator(); while (en.MoveNext()) { Point pnt = (Point)en.Key; data[pnt.X, pnt.Y] = (uint)((Color)en.Value).ToArgb(); } // for (int x = 0; x < sd.Width; x++) // { // for (int y = 0; y < sd.Height; y++) // data[x,y] = (uint)Color.FromArgb(100,200,233).ToArgb(); // } this.m_tx.UnlockRectangle(0); }
public static void CheckHits_(Query query, System.String defaultFieldName, Searcher searcher, int[] results, TestCase testCase) { Hits hits = searcher.Search(query); System.Collections.Hashtable correct = new System.Collections.Hashtable(); for (int i = 0; i < results.Length; i++) { correct.Add((System.Int32)results[i], null); } System.Collections.Hashtable actual = new System.Collections.Hashtable(); for (int i = 0; i < hits.Length(); i++) { actual.Add((System.Int32)hits.Id(i), null); } //Assert.AreEqual(correct, actual, query.ToString(defaultFieldName)); if (correct.Count != 0) { System.Collections.IDictionaryEnumerator iter = correct.GetEnumerator(); bool status = false; while (iter.MoveNext()) { status = actual.ContainsKey(iter.Key); if (status == false) { break; } } Assert.IsTrue(status, query.ToString(defaultFieldName)); } }
public static void CheckHits_(Query query, System.String defaultFieldName, Searcher searcher, int[] results, TestCase testCase) { Hits hits = searcher.Search(query); System.Collections.Hashtable correct = new System.Collections.Hashtable(); for (int i = 0; i < results.Length; i++) { correct.Add((System.Int32) results[i], null); } System.Collections.Hashtable actual = new System.Collections.Hashtable(); for (int i = 0; i < hits.Length(); i++) { actual.Add((System.Int32) hits.Id(i), null); } //Assert.AreEqual(correct, actual, query.ToString(defaultFieldName)); if (correct.Count != 0) { System.Collections.IDictionaryEnumerator iter = correct.GetEnumerator(); bool status = false; while (iter.MoveNext()) { status = actual.ContainsKey(iter.Key); if (status == false) break; } Assert.IsTrue(status, query.ToString(defaultFieldName)); } }
/// <summary> /// 根据指定字段列表获取对象 /// </summary> /// <param name="dir"></param> /// <returns></returns> public static T findByField(bool isOr, bool isLike, System.Collections.Hashtable ht) { try { StringBuilder where; if (isOr) { where = new StringBuilder("1=0"); } else { where = new StringBuilder("1=1"); } System.Collections.IDictionaryEnumerator ienum = ht.GetEnumerator(); while (ienum.MoveNext()) { if (isOr) { where.AppendFormat(" or {0}='{1}'", ienum.Key, ienum.Value); } else { where.AppendFormat(" and {0}='{1}'", ienum.Key, ienum.Value); } } return(db.find <T>(where.ToString()).first()); } catch { return(null); } }
/// <summary> /// 执行存储过程返回得到的数据库表 /// </summary> /// <param name="sp_cmd">存储过程名称</param> /// <param name="sp_Input_Params">哈希数据集</param> /// <returns>成功返回查询到的数据表, 失败返回null</returns> static public DataTable QueryInfoPro(string sp_cmd, System.Collections.Hashtable sp_Input_Params, out string error) { error = null; try { DataTable tempTable = new DataTable(); using (SqlConnection sqlconn = new SqlConnection(GlobalObject.GlobalParameter.StorehouseConnectionString)) { using (SqlDataAdapter da = new SqlDataAdapter(sp_cmd, sqlconn)) { DataSet ds = new DataSet(); da.SelectCommand = new SqlCommand(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.CommandText = sp_cmd; da.SelectCommand.Connection = sqlconn; da.SelectCommand.CommandTimeout = 40000; if (sp_Input_Params != null) { System.Collections.IDictionaryEnumerator InputEnume = sp_Input_Params.GetEnumerator(); while (InputEnume.MoveNext()) { SqlParameter param = new SqlParameter(); param.Direction = ParameterDirection.Input; param.ParameterName = InputEnume.Key.ToString(); param.Value = InputEnume.Value; da.SelectCommand.Parameters.Add(param); } } int rowcount = da.Fill(ds); if (rowcount == 0 && ds != null && ds.Tables.Count == 0) { error = "没有找到任何数据"; } else { tempTable = ds.Tables[ds.Tables.Count - 1]; } } } return(tempTable); } catch (Exception) { throw; } }
/// <summary> Builds a wordlist table, using words as both keys and values /// for backward compatibility. /// /// </summary> /// <param name="wordSet"> stopword set /// </param> private static System.Collections.Hashtable MakeWordTable(System.Collections.Hashtable wordSet) { System.Collections.Hashtable table = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); for (System.Collections.IEnumerator iter = wordSet.GetEnumerator(); iter.MoveNext();) { System.String word = (System.String)iter.Current; table[word] = word; } return(table); }
/* -------------------------- Private methods ---------------------------- */ /// <summary> Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of IpAddresses</summary> private System.Collections.ArrayList createInitialHosts(System.String l) { Tokenizer tok = new Tokenizer(l, ","); System.String t; Address addr; int port; System.Collections.ArrayList retval = new System.Collections.ArrayList(); System.Collections.Hashtable hosts = new System.Collections.Hashtable(); //to be removed later on while (tok.HasMoreTokens()) { try { t = tok.NextToken(); System.String host = t.Substring(0, (t.IndexOf((System.Char) '[')) - (0)); host = host.Trim(); port = System.Int32.Parse(t.Substring(t.IndexOf((System.Char) '[') + 1, (t.IndexOf((System.Char) ']')) - (t.IndexOf((System.Char) '[') + 1))); hosts.Add(host, port); } catch (System.FormatException e) { Stack.NCacheLog.Error("exeption is " + e); } catch (Exception e) { Stack.NCacheLog.Error("TcpPing.createInitialHosts", "Error: " + e.ToString()); throw new Exception("Invalid initial members list"); } } try { System.Collections.IDictionaryEnumerator ide; for (int i = 0; i < port_range; i++) { ide = hosts.GetEnumerator(); while (ide.MoveNext()) { port = Convert.ToInt32(ide.Value); addr = new Address((String)ide.Key, port + i); retval.Add(addr); } } } catch (Exception ex) { Stack.NCacheLog.Error("TcpPing.CreateInitialHosts()", "Error :" + ex); throw new Exception("Invalid initial memebers list"); } return(retval); }
public void Deactivate() { //--- go through each plugin and close it down System.Collections.IDictionaryEnumerator dicEnum = _hashTable.GetEnumerator(); string[] keys = new string[_hashTable.Keys.Count]; int i = 0; while (dicEnum.MoveNext()) { //Remove(dicEnum.Key.ToString()); keys[i] = dicEnum.Key.ToString(); i++; } foreach (string key in keys) { Remove(key); } }
static object GetHashtableValue(System.Collections.Hashtable hash, string Key) { if (hash.ContainsKey(Key)) { return(hash[Key]); } System.Collections.IDictionaryEnumerator enumer = hash.GetEnumerator(); while (enumer.MoveNext()) { if (enumer.Key.ToString().ToLower() == Key.ToLower()) { return(enumer.Value); } } return(null); }
internal void CommitPendingFiles() { if (pending != null) { if (deletable == null) { deletable = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); } System.Collections.IEnumerator it = pending.GetEnumerator(); while (it.MoveNext()) { deletable.Add(((System.Collections.DictionaryEntry)(it.Current)).Value); } pending = null; DeleteFiles(); } }
public virtual void TestShrinkToAfterShortestMatch3() { RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new TestPayloadAnalyzer(this), IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); doc.Add(new Field("content", new System.IO.StreamReader(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes("j k a l f k k p a t a k l k t a"))))); writer.AddDocument(doc); writer.Close(); IndexSearcher is_Renamed = new IndexSearcher(directory, true); SpanTermQuery stq1 = new SpanTermQuery(new Term("content", "a")); SpanTermQuery stq2 = new SpanTermQuery(new Term("content", "k")); SpanQuery[] sqs = new SpanQuery[] { stq1, stq2 }; SpanNearQuery snq = new SpanNearQuery(sqs, 0, true); Spans spans = snq.GetSpans(is_Renamed.IndexReader); TopDocs topDocs = is_Renamed.Search(snq, 1); System.Collections.Hashtable payloadSet = new System.Collections.Hashtable(); for (int i = 0; i < topDocs.ScoreDocs.Length; i++) { while (spans.Next()) { System.Collections.Generic.ICollection <byte[]> payloads = spans.GetPayload(); for (System.Collections.IEnumerator it = payloads.GetEnumerator(); it.MoveNext();) { CollectionsHelper.AddIfNotContains(payloadSet, new System.String(System.Text.UTF8Encoding.UTF8.GetChars((byte[])it.Current))); } } } Assert.AreEqual(2, payloadSet.Count); if (DEBUG) { System.Collections.IEnumerator pit = payloadSet.GetEnumerator(); while (pit.MoveNext()) { System.Console.Out.WriteLine("match:" + pit.Current); } } Assert.IsTrue(payloadSet.Contains("a:Noise:10")); Assert.IsTrue(payloadSet.Contains("k:Noise:11")); }
public static XmlDocument HashtableToXml(System.Collections.Hashtable ht) { XmlDocument doc = new XmlDocument(); System.Xml.XmlNode node, subnode; node = doc.CreateElement("root"); doc.AppendChild(node); System.Collections.IDictionaryEnumerator en = ht.GetEnumerator(); while (en.MoveNext()) { subnode = node.AppendChild(node.OwnerDocument.CreateElement(Convert.ToString(en.Key))); subnode.InnerText = Convert.ToString(en.Value); } return(doc); }
public virtual System.String[] pids() { System.String[] allpids = null; lock (byPid) { int n = byPid.Count; System.Collections.IDictionaryEnumerator keys = byPid.GetEnumerator(); allpids = new System.String[n]; int i = 0; keys.Reset(); while (keys.MoveNext()) { allpids[i++] = ((Erlang.Pid)(keys.Key)).ToString(); } } return(allpids); }
public virtual System.String[] names() { System.String[] allnames = null; lock (byName) { int n = byName.Count; System.Collections.IDictionaryEnumerator keys = byName.GetEnumerator(); allnames = new System.String[n]; int i = 0; keys.Reset(); while (keys.MoveNext()) { allnames[i++] = (System.String)(keys.Key); } } return(allnames); }
static StackObject *GetEnumerator_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Collections.Hashtable instance_of_this_method = (System.Collections.Hashtable) typeof(System.Collections.Hashtable).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetEnumerator(); object obj_result_of_this_method = result_of_this_method; if (obj_result_of_this_method is CrossBindingAdaptorType) { return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance)); } return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
/// <summary> /// 判断某用户是否已经登陆 /// </summary> /// <param name="id">为用户ID或用户名这个必须是用户的唯一标识</param> /// <returns>flase为没有登陆 true为被迫下线</returns> public bool IsLogin(object id) { bool flag = false; System.Collections.Hashtable ht = (System.Collections.Hashtable)HttpContext.Current.Application[appKey]; if (ht != null) { System.Collections.IDictionaryEnumerator IDE = ht.GetEnumerator(); while (IDE.MoveNext()) { //找到自己的登陆ID if (IDE.Value.ToString().Equals(id.ToString())) //if (IDE.Key.ToString().Equals(HttpContext.Current.Session.SessionID)) { flag = true; break; } } } return(flag); }
private float boost = 1.0f; // query boost factor #endregion Fields #region Methods /// <summary>Expert: merges the clauses of a set of BooleanQuery's into a single /// BooleanQuery. /// /// <p/>A utility for use by <see cref="Combine(Query[])" /> implementations. /// </summary> public static Query MergeBooleanQueries(BooleanQuery[] queries) { System.Collections.Hashtable allClauses = new System.Collections.Hashtable(); for (int i = 0; i < queries.Length; i++) { BooleanClause[] clauses = queries[i].GetClauses(); for (int j = 0; j < clauses.Length; j++) { SupportClass.CollectionsHelper.AddIfNotContains(allClauses, clauses[j]); } } bool coordDisabled = queries.Length == 0?false:queries[0].IsCoordDisabled(); BooleanQuery result = new BooleanQuery(coordDisabled); System.Collections.IEnumerator i2 = allClauses.GetEnumerator(); while (i2.MoveNext()) { result.Add((BooleanClause) i2.Current); } return result; }
public static string ReadToHtml(string htmlPath, System.Collections.Hashtable htReplace) { try { System.IO.TextReader reader = System.IO.File.OpenText(AppDomain.CurrentDomain.BaseDirectory + htmlPath); string text = reader.ReadToEnd(); reader.Close(); reader.Dispose(); System.Collections.IDictionaryEnumerator ie = htReplace.GetEnumerator(); while (ie.MoveNext()) { text = text.Replace(ie.Key.ToString(), ie.Value.ToString()); } return(text); } catch (Exception) { return(""); } }
/// <summary> /// Saves the class data in the form of INI file into the TextWriter /// </summary> /// <param name="sw">The destination for the output</param> public void Save(System.IO.TextWriter sw) { System.Collections.IDictionaryEnumerator Enumerator = Values.GetEnumerator(); //Print values sw.WriteLine("; The values in this group"); while (Enumerator.MoveNext()) { sw.WriteLine("{0} = {1}", Enumerator.Key, Enumerator.Value); } sw.WriteLine("; This is where the keys begins"); Enumerator = Keys.GetEnumerator(); while (Enumerator.MoveNext()) { System.Collections.IDictionaryEnumerator Enumerator2nd = ((System.Collections.Hashtable)Enumerator.Value).GetEnumerator(); sw.WriteLine("[{0}]", Enumerator.Key); while (Enumerator2nd.MoveNext()) { sw.WriteLine("{0} = {1}", Enumerator2nd.Key, Enumerator2nd.Value); } } }
/// <summary>Simulates a crash of OS or machine by overwriting /// unsynced files. /// </summary> public virtual void Crash() { lock (this) { crashed = true; openFiles = new System.Collections.Hashtable(); System.Collections.IEnumerator it = unSyncedFiles.GetEnumerator(); unSyncedFiles = new System.Collections.Hashtable(); int count = 0; while (it.MoveNext()) { System.String name = (System.String)((System.Collections.DictionaryEntry)it.Current).Value; RAMFile file = (RAMFile)fileMap_ForNUnit[name]; if (count % 3 == 0) { DeleteFile(name, true); } else if (count % 3 == 1) { // Zero out file entirely int numBuffers = file.NumBuffers(); for (int i = 0; i < numBuffers; i++) { byte[] buffer = file.GetBuffer(i); for (int j = 0; j < buffer.Length; j++) { buffer[j] = (byte)0; } } } else if (count % 3 == 2) { // Truncate the file: file.SetLength(file.GetLength() / 2); } count++; } } }
static int _m_GetEnumerator(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Collections.Hashtable gen_to_be_invoked = (System.Collections.Hashtable)translator.FastGetCSObj(L, 1); { System.Collections.IDictionaryEnumerator gen_ret = gen_to_be_invoked.GetEnumerator( ); translator.PushAny(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
/// <summary>Expert: merges the clauses of a set of BooleanQuery's into a single /// BooleanQuery. /// /// <p/>A utility for use by {@link #Combine(Query[])} implementations. /// </summary> public static Query MergeBooleanQueries(BooleanQuery[] queries) { System.Collections.Hashtable allClauses = new System.Collections.Hashtable(); for (int i = 0; i < queries.Length; i++) { BooleanClause[] clauses = queries[i].GetClauses(); for (int j = 0; j < clauses.Length; j++) { SupportClass.CollectionsHelper.AddIfNotContains(allClauses, clauses[j]); } } bool coordDisabled = queries.Length == 0?false:queries[0].IsCoordDisabled(); BooleanQuery result = new BooleanQuery(coordDisabled); System.Collections.IEnumerator i2 = allClauses.GetEnumerator(); while (i2.MoveNext()) { result.Add((BooleanClause)i2.Current); } return(result); }
/// <summary> Prints the names of the protocols, from the bottom to top. If include_properties is true, /// the properties for each protocol will also be printed. /// </summary> public virtual string printProtocolSpec(bool include_properties) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); Protocol prot = top_prot; string name; while (prot != null) { name = prot.Name; if (name != null) { if ("ProtocolStack".Equals(name)) { break; } sb.Append(name); if (include_properties) { System.Collections.Hashtable props = prot.getProperties(); System.Collections.DictionaryEntry entry; if (props != null) { sb.Append('\n'); for (System.Collections.IEnumerator it = props.GetEnumerator(); it.MoveNext();) { entry = (System.Collections.DictionaryEntry)it.Current; sb.Append(entry + "\n"); } } } sb.Append('\n'); prot = prot.DownProtocol; } } return(sb.ToString()); }
//fieldname MUST be interned prior to this call private static void GetTerms(Query query, System.Collections.Hashtable terms, bool prohibited, System.String fieldName) { try { if (query is BooleanQuery) GetTermsFromBooleanQuery((BooleanQuery) query, terms, prohibited, fieldName); else if (query is FilteredQuery) GetTermsFromFilteredQuery((FilteredQuery) query, terms, prohibited, fieldName); else { System.Collections.Hashtable nonWeightedTerms = new System.Collections.Hashtable(); query.ExtractTerms(nonWeightedTerms); System.Collections.IDictionaryEnumerator iter = nonWeightedTerms.GetEnumerator(); while (iter.MoveNext()) { Term term = (Term)iter.Value; if ((fieldName == null) || (term.Field() == fieldName)) { WeightedTerm temp = new WeightedTerm(query.GetBoost(), term.Text()); terms.Add(temp, temp); } } } } catch (System.NotSupportedException ignore) { //this is non-fatal for our purposes } }
static void Main(string[] args) { // Constants const string STR_KEYSTART = "<q1:KeyName>"; const string STR_KEYEND = "</q1:KeyName>"; const string STR_SETTINGSTART = "<q1:SettingString>"; const string STR_NUMBERSTART = "<q1:SettingNumber>"; const string STR_SETTINGEND = "</q1:SettingNumber>"; const string STR_NUMBEREND = "</q1:SettingString>"; if (args.Length < 2) { Console.WriteLine("[-] ERROR: requires two input files\nExample: win10sec.exe <gpo-backup-file> <secedit-export-file>"); return; } if (!(File.Exists(args[0]) && File.Exists(args[1]))) { Console.WriteLine("[-] ERROR: All input files does not exist!"); return; } // Parse arguments string strFilename = args[0]; string strTemplateFile = args[1]; // Read files string [] strFile = File.ReadAllLines(strFilename); string[] strGPResultXMLFile = File.ReadAllLines(strTemplateFile); // Variables System.Collections.Hashtable htRegistryValues = new System.Collections.Hashtable(); System.Collections.Hashtable htCurrentRegistrySettings = new System.Collections.Hashtable(); // Read the XML-file (gpreport.xml) that has been exported by Microsoft Security Compliance Manager (Export --> GPO Backup Folder) for (int i = 0; i < strGPResultXMLFile.Length; i++) { int pos = strGPResultXMLFile[i].IndexOf(STR_KEYSTART); if (pos >= 0) { int endPos = strGPResultXMLFile[i].IndexOf(STR_KEYEND); string strAdd = strGPResultXMLFile[i].Substring(pos + STR_KEYSTART.Length, endPos - pos - STR_KEYSTART.Length); int x = i; for (x = i; x < strGPResultXMLFile.Length; x++) { int posString = strGPResultXMLFile[x].IndexOf(STR_SETTINGSTART); int posNumber = strGPResultXMLFile[x].IndexOf(STR_NUMBERSTART); int max = Math.Max(posNumber, posString); string strComp = STR_NUMBERSTART; string strComp2 = STR_SETTINGEND; if (posNumber < posString) { strComp = STR_SETTINGSTART; strComp2 = STR_NUMBEREND; } string strTemp = strGPResultXMLFile[x]; int endPosMax = strTemp.IndexOf(strComp2); if (max >= 0) { string strValue = strTemp.Substring(max + strComp.Length, endPosMax - max - strComp.Length); htRegistryValues.Add(strAdd, strValue); break; } } i = x; } } // Read the .inf-file that has been exported from the template. bool bRegistryMode = false; for (int i = 0; i < strFile.Length; i++) { if (bRegistryMode) { if (strFile[i].IndexOf("[") >= 0) { bRegistryMode = false; } else { int pos = 0; int endPos = strFile[i].IndexOf("="); if (endPos > 0) { string strAdd = strFile[i].Substring(pos, endPos - pos); string strValue = strFile[i].Substring(endPos + 3); htCurrentRegistrySettings.Add(strAdd, strValue); } else { throw new FormatException(); } } } else { if (strFile[i].IndexOf("[Registry Values]") >= 0) { bRegistryMode = true; } } } // Print out the difference between settings System.Collections.IDictionaryEnumerator en = htRegistryValues.GetEnumerator(); while (en.MoveNext()) { string strKey = (string)en.Key; string strVal = (string)en.Value; Console.Write(en.Key + "|"); if (htCurrentRegistrySettings.ContainsKey(strKey)) { string strCurrentVal = (string)htCurrentRegistrySettings[strKey]; bool bEqual = (strCurrentVal == (string)htRegistryValues[strKey]); Console.WriteLine((string)htRegistryValues[strKey] + "|" + strCurrentVal + "|" + bEqual.ToString()); } else { Console.WriteLine("||Missing"); } } }
private void ByVendorsPerMonth(object sender, EventArgs e) { try { if( this.lbxObjects.SelectedItems.Count > 0 ){ List<Guid> ids = new List<Guid>(); //foreach( ListViewItem obj in this.lbxObjects.SelectedItems ){ foreach( DataRowView obj in this.lbxObjects.SelectedItems ){ if (!System.Convert.IsDBNull(obj["VendorID"])) ids.Add((Guid)obj["VendorID"]); } System.Data.SqlClient.SqlCommand mnth = Statistics.Purchases.ByVendorsPerMonth(ids); mnth.Connection = this.connection; System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(mnth); System.Data.DataTable st = new System.Data.DataTable("Summary"); sda.Fill(st); ZedGraph.GraphPane pane = this.zgcStatistics.GraphPane; pane.CurveList.Clear(); pane.GraphObjList.Clear(); pane.YAxis.Title.Text = "Сумма, р"; System.Collections.Hashtable lsts = new System.Collections.Hashtable(); foreach (System.Data.DataRow row in st.Rows) { ZedGraph.PointPairList list = null; string v_name = (string)row["VendorName"]; if (lsts.ContainsKey(v_name)) { list = (ZedGraph.PointPairList)lsts[v_name]; } else { list = new ZedGraph.PointPairList(); lsts.Add(v_name, list); } int year = 1970; int month = 1; if (!System.Convert.IsDBNull(row["Year"]) && !System.Convert.IsDBNull(row["Month"])) { year = (int)row["Year"]; month = (int)row["Month"]; System.DateTime dt = new DateTime(year, month, 1); ZedGraph.XDate xDate = new ZedGraph.XDate(dt); decimal val = (decimal)row["Summary"]; list.Add(xDate.XLDate, (double)val); } } Random rand = new Random(); System.Collections.IEnumerator lenum = lsts.GetEnumerator(); while(lenum.MoveNext() ) { int r = rand.Next(255); int g = rand.Next(255); int b = rand.Next(255); Color clr = Color.FromArgb(r, g, b); System.Collections.DictionaryEntry lde = (System.Collections.DictionaryEntry)lenum.Current; ZedGraph.BarItem curve = pane.AddBar((string)lde.Key, (ZedGraph.PointPairList)lde.Value, clr); } // Для оси X установим календарный тип pane.XAxis.Type = ZedGraph.AxisType.Date; // pretty it up a little pane.Chart.Fill = new ZedGraph.Fill(Color.White, Color.LightGoldenrodYellow, 45.0f); pane.Fill = new ZedGraph.Fill(Color.White, Color.FromArgb(220, 220, 255), 45.0f); // Tell ZedGraph to calculate the axis ranges this.zgcStatistics.AxisChange(); this.zgcStatistics.Invalidate(); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } return; }
static void Main(string[] args) { // Constants const string STR_KEYSTART = "<q1:KeyName>"; const string STR_KEYEND = "</q1:KeyName>"; const string STR_SETTINGSTART = "<q1:SettingString>"; const string STR_NUMBERSTART = "<q1:SettingNumber>"; const string STR_SETTINGEND = "</q1:SettingNumber>"; const string STR_NUMBEREND = "</q1:SettingString>"; if (args.Length < 2) { Console.WriteLine("[-] ERROR: requires two input files\nExample: win10sec.exe <gpo-backup-file> <secedit-export-file>"); return; } if (!(File.Exists(args[0]) && File.Exists(args[1]))) { Console.WriteLine("[-] ERROR: All input files does not exist!"); return; } // Parse arguments string strFilename = args[0]; string strTemplateFile = args[1]; // Read files string [] strFile = File.ReadAllLines(strFilename); string[] strGPResultXMLFile = File.ReadAllLines(strTemplateFile); // Variables System.Collections.Hashtable htRegistryValues = new System.Collections.Hashtable(); System.Collections.Hashtable htCurrentRegistrySettings = new System.Collections.Hashtable(); // Read the XML-file (gpreport.xml) that has been exported by Microsoft Security Compliance Manager (Export --> GPO Backup Folder) for (int i = 0; i < strGPResultXMLFile.Length; i++) { int pos = strGPResultXMLFile[i].IndexOf(STR_KEYSTART); if (pos >= 0) { int endPos = strGPResultXMLFile[i].IndexOf(STR_KEYEND); string strAdd = strGPResultXMLFile[i].Substring(pos + STR_KEYSTART.Length, endPos - pos - STR_KEYSTART.Length); int x = i; for (x = i; x < strGPResultXMLFile.Length; x++) { int posString = strGPResultXMLFile[x].IndexOf(STR_SETTINGSTART); int posNumber = strGPResultXMLFile[x].IndexOf(STR_NUMBERSTART); int max = Math.Max(posNumber, posString); string strComp = STR_NUMBERSTART; string strComp2 = STR_SETTINGEND; if (posNumber < posString) { strComp = STR_SETTINGSTART; strComp2 = STR_NUMBEREND; } string strTemp = strGPResultXMLFile[x]; int endPosMax = strTemp.IndexOf(strComp2); if (max >= 0) { string strValue = strTemp.Substring(max + strComp.Length, endPosMax - max - strComp.Length); htRegistryValues.Add(strAdd, strValue); break; } } i = x; } } // Read the .inf-file that has been exported from the template. bool bRegistryMode = false; for (int i = 0; i < strFile.Length; i++) { if (bRegistryMode) { if (strFile[i].IndexOf("[") >= 0) { bRegistryMode = false; } else { int pos = 0; int endPos = strFile[i].IndexOf("="); if (endPos > 0) { string strAdd = strFile[i].Substring(pos, endPos - pos); string strValue = strFile[i].Substring(endPos + 3); htCurrentRegistrySettings.Add(strAdd, strValue); } else { throw new FormatException(); } } } else { if (strFile[i].IndexOf("[Registry Values]") >= 0) { bRegistryMode = true; } } } // Print out the difference between settings System.Collections.IDictionaryEnumerator en = htRegistryValues.GetEnumerator(); while(en.MoveNext()) { string strKey = (string) en.Key; string strVal = (string) en.Value; Console.Write(en.Key + "|"); if (htCurrentRegistrySettings.ContainsKey(strKey)) { string strCurrentVal = (string)htCurrentRegistrySettings[strKey]; bool bEqual = (strCurrentVal == (string)htRegistryValues[strKey]); Console.WriteLine((string)htRegistryValues[strKey] + "|" + strCurrentVal + "|" + bEqual.ToString()); } else { Console.WriteLine("||Missing"); } } }
/// <summary>Expert: called when re-writing queries under MultiSearcher. /// /// Create a single query suitable for use by all subsearchers (in 1-1 /// correspondence with queries). This is an optimization of the OR of /// all queries. We handle the common optimization cases of equal /// queries and overlapping clauses of boolean OR queries (as generated /// by MultiTermQuery.rewrite() and RangeQuery.rewrite()). /// Be careful overriding this method as queries[0] determines which /// method will be called and is not necessarily of the same type as /// the other queries. /// </summary> public virtual Query Combine(Query[] queries) { System.Collections.Hashtable uniques = new System.Collections.Hashtable(); for (int i = 0; i < queries.Length; i++) { Query query = queries[i]; BooleanClause[] clauses = null; // check if we can split the query into clauses bool splittable = (query is BooleanQuery); if (splittable) { BooleanQuery bq = (BooleanQuery) query; splittable = bq.IsCoordDisabled(); clauses = bq.GetClauses(); for (int j = 0; splittable && j < clauses.Length; j++) { splittable = (clauses[j].GetOccur() == BooleanClause.Occur.SHOULD); } } if (splittable) { for (int j = 0; j < clauses.Length; j++) { Query tmp = clauses[j].GetQuery(); if (uniques.Contains(tmp) == false) { uniques.Add(tmp, tmp); } } } else { if (uniques.Contains(query) == false) { uniques.Add(query, query); } } } // optimization: if we have just one query, just return it if (uniques.Count == 1) { System.Collections.IDictionaryEnumerator iter = uniques.GetEnumerator(); iter.MoveNext(); return iter.Value as Query; } System.Collections.IDictionaryEnumerator it = uniques.GetEnumerator(); BooleanQuery result = new BooleanQuery(true); while (it.MoveNext()) { result.Add((Query) it.Value, BooleanClause.Occur.SHOULD); } return result; }
private static System.Collections.Hashtable DifFiles(System.String[] files1, System.String[] files2) { System.Collections.Hashtable set1 = new System.Collections.Hashtable(); System.Collections.Hashtable set2 = new System.Collections.Hashtable(); System.Collections.Hashtable extra = new System.Collections.Hashtable(); for (int x = 0; x < files1.Length; x++) { Support.CollectionsHelper.AddIfNotContains(set1, files1[x]); } for (int x = 0; x < files2.Length; x++) { Support.CollectionsHelper.AddIfNotContains(set2, files2[x]); } System.Collections.IEnumerator i1 = set1.GetEnumerator(); while (i1.MoveNext()) { System.Object o = i1.Current; if (!set2.Contains(o)) { Support.CollectionsHelper.AddIfNotContains(extra, o); } } System.Collections.IEnumerator i2 = set2.GetEnumerator(); while (i2.MoveNext()) { System.Object o = i2.Current; if (!set1.Contains(o)) { Support.CollectionsHelper.AddIfNotContains(extra, o); } } return extra; }
public static void csvAllResult(System.Collections.Hashtable raceStat, string datFile, infoRace currInfoRace) { System.Collections.ArrayList sorted = new System.Collections.ArrayList(); System.Collections.IDictionaryEnumerator tmpRaceStat = raceStat.GetEnumerator(); while (tmpRaceStat.MoveNext()) //for each player { raceStats p = (raceStats)tmpRaceStat.Value; sorted.Add(p); } raceStats.modeSort = (int)sortRaceStats.SORT_RESULT; sorted.Sort(); if (!Directory.Exists("Export")) { System.IO.Directory.CreateDirectory("Export"); } var raceEngine = new DelimitedFileEngine <infoRace>(); raceEngine.HeaderText = "datFile,currentTrackName,maxSplit,weather,wind,raceLaps,sraceLaps,qualMins,HName,currLap,isToc"; var raceResults = new List <infoRace>(); currInfoRace.datFile = datFile; raceResults.Add(currInfoRace); raceEngine.WriteFile("Export/" + datFile + "_race.csv", raceResults); var engine = new DelimitedFileEngine <raceStats>(); engine.HeaderText = "datFile,UCID,PLID,userName,nickName,Plate,bestSplit1,lapBestSplit1,bestSplit2,lapBestSplit2,bestSplit3,lapBestSplit3,bestLastSplit,lapBestLastSplit,cumuledTime,bestSpeed,lapBestSpeed,numStop,cumuledStime,resultNum,finalPos,finished,finPLID,totalTime,bestLap,lapBestLap,CName,penalty,gridPos,lapsLead,tmpTime,firstTime,avgTime,curBestSplit,curWrSplit,curLapBestSplit,lapStability,curSplit1,curSplit2,curSplit3,yellowFlags,inYellow,blueFlags,inBlue,sFlags,numPen,lastSplit,CurrIdxSplit"; List <raceStats> results = new List <raceStats>(); foreach (raceStats r in sorted) { r.datFile = datFile; results.Add(r); } engine.WriteFile("Export/" + datFile + "_results_race.csv", results); List <Lap> lapResults = new List <Lap>(); foreach (raceStats r in sorted) { int i = 1; foreach (Lap lap in r.lap) { lap.datFile = datFile; lap.UCID = r.UCID; lap.PLID = r.PLID; lap.lap = i++; lapResults.Add((Lap)lap); } } var engine2 = new DelimitedFileEngine <Lap>(); engine2.HeaderText = "datFile,UCID,PLID,lap,split1,split2,split3,lapTime,cumuledTime"; engine2.WriteFile("Export/" + datFile + "_results_race_laps.csv", lapResults); ////this.ContentTypeFilters.Register(ContentType.Csv, CsvSerializer.SerializeToStream, CsvSerializer.DeserializeFromStream); ////using (System.IO.StreamWriter sw = new System.IO.StreamWriter("Export/" + datFile + "_results_race.csv")) ////{ // //int curPos = 0; // for (int i = 0; i < sorted.Count; i++) // { // raceStats p = (raceStats)sorted[i]; // //curPos++; // //raceStats p = (raceStats)sorted[i]; // //if (i == 0) // //{ // // firstMaxLap = p.lap.Count; // // firstTotalTime = p.totalTime; // //} // //string resultLine = formatLine; // //resultLine = resultLine.Replace("[RaceResults ", ""); // //resultLine = resultLine.Replace("]", ""); // //resultLine = resultLine.Replace("{Position}", curPos.ToString()); // //// resultLine = resultLine.Replace("{Position}", p.resultNum.ToString() ); // //resultLine = resultLine.Replace("{PlayerName}", p.nickName.Replace("^0", "").Replace("^1", "").Replace("^2", "").Replace("^3", "").Replace("^4", "").Replace("^5", "").Replace("^6", "").Replace("^7", "").Replace("^8", "")); // //resultLine = resultLine.Replace("{UserName}", p.userName); // //resultLine = resultLine.Replace("{Car}", p.CName); // //// if Racer do not finish // //if (p.resultNum == 999) // // resultLine = resultLine.Replace("{Gap}", "DNF"); // //else // //{ // // if (firstMaxLap == p.lap.Count) // // { // // if (i == 0) // // resultLine = resultLine.Replace("{Gap}", raceStats.LfstimeToString(p.totalTime)); // // else // // { // // long tres; // // tres = p.totalTime - firstTotalTime; // // resultLine = resultLine.Replace("{Gap}", "+" + raceStats.LfstimeToString(tres)); // // } // // } // // else // // resultLine = resultLine.Replace("{Gap}", "+" + ((int)(firstMaxLap - p.lap.Count)).ToString() + " laps"); // //} // //resultLine = resultLine.Replace("{BestLap}", raceStats.LfstimeToString(p.bestLap)); // //resultLine = resultLine.Replace("{LapsDone}", p.lap.Count.ToString()); // //resultLine = resultLine.Replace("{PitsDone}", p.numStop.ToString()); // //resultLine = resultLine.Replace("{Penalty}", p.penalty); // //resultLine = resultLine.Replace("{PosGrid}", p.gridPos.ToString()); // //resultLine = resultLine.Replace("{Flags}", p.sFlags); // //sw.WriteLine(resultLine); // } ////} }
/* -------------------------- Private methods ---------------------------- */ /// <summary> Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of IpAddresses</summary> private System.Collections.ArrayList createInitialHosts(System.String l) { Global.Tokenizer tok = new Global.Tokenizer(l, ","); System.String t; Address addr; int port; System.Collections.ArrayList retval = new System.Collections.ArrayList(); System.Collections.Hashtable hosts = new System.Collections.Hashtable(); //to be removed later on while (tok.HasMoreTokens()) { try { t = tok.NextToken(); System.String host = t.Substring(0, (t.IndexOf((System.Char)'[')) - (0)); host = host.Trim(); port = System.Int32.Parse(t.Substring(t.IndexOf((System.Char)'[') + 1, (t.IndexOf((System.Char)']')) - (t.IndexOf((System.Char)'[') + 1))); hosts.Add(host, port); } catch (System.FormatException e) { Stack.NCacheLog.Error("exeption is " + e); } catch (Exception e) { Stack.NCacheLog.Error("TcpPing.createInitialHosts", "Error: " + e.ToString()); throw new Exception("Invalid initial members list"); } } try { System.Collections.IDictionaryEnumerator ide; for(int i = 0; i< port_range; i++) { ide = hosts.GetEnumerator(); while(ide.MoveNext()) { port = Convert.ToInt32(ide.Value); addr = new Address((String)ide.Key, port + i); retval.Add(addr); } } } catch(Exception ex) { Stack.NCacheLog.Error("TcpPing.CreateInitialHosts()", "Error :" + ex); throw new Exception("Invalid initial memebers list"); } return retval; }
/** * <p>Detects a Data Matrix Code in an image.</p> * * @return {@link DetectorResult} encapsulating results of detecting a QR Code * @throws ReaderException if no Data Matrix Code can be found */ public DetectorResult detect() { if (!BlackPointEstimationMethod.TWO_D_SAMPLING.Equals(image.getLastEstimationMethod())) { image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0); } int height = image.getHeight(); int width = image.getWidth(); int halfHeight = height >> 1; int halfWidth = width >> 1; int iSkip = Math.Max(1, height / (MAX_MODULES << 3)); int jSkip = Math.Max(1, width / (MAX_MODULES << 3)); int minI = 0; int maxI = height; int minJ = 0; int maxJ = width; ResultPoint pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); minI = (int) pointA.getY() - 1; ResultPoint pointB = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, -jSkip, minJ, maxJ, halfHeight >> 1); minJ = (int) pointB.getX() - 1; ResultPoint pointC = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, jSkip, minJ, maxJ, halfHeight >> 1); maxJ = (int) pointC.getX() + 1; ResultPoint pointD = findCornerFromCenter(halfHeight, iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); maxI = (int) pointD.getY() + 1; // Go try to find point A again with better information -- might have been off at first. pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 2); // Point A and D are across the diagonal from one another, // as are B and C. Figure out which are the solid black lines // by counting transitions System.Collections.ArrayList transitions = new System.Collections.ArrayList(4); transitions.Add(transitionsBetween(pointA, pointB)); transitions.Add(transitionsBetween(pointA, pointC)); transitions.Add(transitionsBetween(pointB, pointD)); transitions.Add(transitionsBetween(pointC, pointD)); Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator()); // Sort by number of transitions. First two will be the two solid sides; last two // will be the two alternating black/white sides ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions) transitions[0]; ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions) transitions[1]; // Figure out which point is their intersection by tallying up the number of times we see the // endpoints in the four endpoints. One will show up twice. System.Collections.Hashtable pointCount = new System.Collections.Hashtable(); increment(pointCount, lSideOne.getFrom()); increment(pointCount, lSideOne.getTo()); increment(pointCount, lSideTwo.getFrom()); increment(pointCount, lSideTwo.getTo()); ResultPoint maybeTopLeft = null; ResultPoint bottomLeft = null; ResultPoint maybeBottomRight = null; System.Collections.IEnumerator points = pointCount.GetEnumerator(); while (points.MoveNext()) { ResultPoint point = (ResultPoint) points.Current; int value = (int) pointCount[point]; if (value == 2) { bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides } else { // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now if (maybeTopLeft == null) { maybeTopLeft = point; } else { maybeBottomRight = point; } } } if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { throw new ReaderException(); } // Bottom left is correct but top left and bottom right might be switched ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight }; // Use the dot product trick to sort them out GenericResultPoint.orderBestPatterns(corners); // Now we know which is which: ResultPoint bottomRight = corners[0]; bottomLeft = corners[1]; ResultPoint topLeft = corners[2]; // Which point didn't we find in relation to the "L" sides? that's the top right corner ResultPoint topRight; if (!pointCount.ContainsKey(pointA)) { topRight = pointA; } else if (!pointCount.ContainsKey(pointB)) { topRight = pointB; } else if (!pointCount.ContainsKey(pointC)) { topRight = pointC; } else { topRight = pointD; } // Next determine the dimension by tracing along the top or right side and counting black/white // transitions. Since we start inside a black module, we should see a number of transitions // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to // end on a black module: // The top right point is actually the corner of a module, which is one of the two black modules // adjacent to the white module at the top right. Tracing to that corner from either the top left // or bottom right should work here, but, one will be more reliable since it's traced straight // up or across, rather than at a slight angle. We use dot products to figure out which is // better to use: int dimension; if (GenericResultPoint.crossProductZ(bottomLeft, bottomRight, topRight) < GenericResultPoint.crossProductZ(topRight, topLeft, bottomLeft)) { dimension = transitionsBetween(topLeft, topRight).getTransitions(); } else { dimension = transitionsBetween(bottomRight, topRight).getTransitions(); } dimension += 2; BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension); return new DetectorResult(bits, new ResultPoint[] {pointA, pointB, pointC, pointD}); }
/// <summary> /// Finds the nearest point to the requested location that is within the tolerance radius. /// </summary> /// <param name="ProjectedRadius">The tolerance radius in projected units used to search for the nearest point that can be snapped to. </param> /// <param name="x">x coordinate in projected map units</param> /// <param name="y">y coordinate in projected map units</param> /// <param name="BestPoint">A PointD class with the location of the nearest point to snap to if there is are any within the tolerance, null if no points are found.</param> /// <returns>Returns true if there is a point to snap to.</returns> public bool CanSnap(double ProjectedRadius, double x, double y, ref System.Collections.ArrayList BestPoints) { PointD BestPoint = null; System.Collections.IDictionaryEnumerator ie = m_lists.GetEnumerator(); while (ie.MoveNext()) { int snaplayeridx = (int)ie.Key; if (((System.Collections.SortedList)m_lists[snaplayeridx]).Count == 0) { continue; } try { double val = (x - ProjectedRadius); int first = FindFirst(((System.Collections.SortedList)m_lists[snaplayeridx]), val); double bestX = x + ProjectedRadius, bestY = y + ProjectedRadius; double curX; if (first == -1) { System.Diagnostics.Debug.WriteLine("Could not find any points to snap to"); return(false); } curX = (double)((System.Collections.SortedList)m_lists[snaplayeridx]).GetKey(first); while (curX < (x + ProjectedRadius)) { if (Math.Abs(curX - x) < Math.Abs(bestX - x)) { // the current x is closer to the x value than the previous best // now we think we have a new best x, try to find a better y value System.Collections.SortedList tList = (System.Collections.SortedList)((System.Collections.SortedList)m_lists[snaplayeridx]).GetByIndex(first); for (int j = 0; j < tList.Count; j++) { double curY = (double)tList.GetKey(j); if (Math.Abs(curY - y) < Math.Abs(bestY - y)) { // the current y is closer to the y value than the previous best BestPoint = new PointD(curX, curY); if (BestPoints == null) { BestPoints = new System.Collections.ArrayList(); } BestPoints.AddRange((System.Collections.ArrayList)tList.GetByIndex(j)); // only reset the bestX and bestY when both are better than the previous. bestX = curX; bestY = curY; } } } first++; if (first < ((System.Collections.SortedList)m_lists[snaplayeridx]).Count) { curX = (double)((System.Collections.SortedList)m_lists[snaplayeridx]).GetKey(first); } else { break; } } } catch (System.Exception ex) { errCnt++; System.Diagnostics.Debug.WriteLine(errCnt + " " + ex.Message); } } if (BestPoints == null) { return(false); } else { return(true); } }
/// <summary> Tests that a query matches the an expected set of documents using a /// HitCollector. /// /// <p> /// Note that when using the HitCollector API, documents will be collected /// if they "match" regardless of what their score is. /// </p> /// </summary> /// <param name="query">the query to test /// </param> /// <param name="searcher">the searcher to test the query against /// </param> /// <param name="defaultFieldName">used for displaing the query in assertion messages /// </param> /// <param name="results">a list of documentIds that must match the query /// </param> /// <seealso cref="Searcher.Search(Query,HitCollector)"> /// </seealso> /// <seealso cref="checkHits"> /// </seealso> public static void CheckHitCollector(Query query, System.String defaultFieldName, Searcher searcher, int[] results) { System.Collections.ArrayList correct = new System.Collections.ArrayList(results.Length); for (int i = 0; i < results.Length; i++) { correct.Add(results[i]); } System.Collections.Hashtable actual = new System.Collections.Hashtable(); searcher.Search(query, new AnonymousClassHitCollector(actual)); System.Collections.IDictionaryEnumerator e = actual.GetEnumerator(); while (e.MoveNext()) { Assert.Contains(e.Key, correct, query.ToString(defaultFieldName)); } QueryUtils.Check(query, searcher); }
/** * <p>Detects a Data Matrix Code in an image.</p> * * @return {@link DetectorResult} encapsulating results of detecting a QR Code * @throws ReaderException if no Data Matrix Code can be found */ public DetectorResult detect() { if (!BlackPointEstimationMethod.TWO_D_SAMPLING.Equals(image.getLastEstimationMethod())) { image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0); } int height = image.getHeight(); int width = image.getWidth(); int halfHeight = height >> 1; int halfWidth = width >> 1; int iSkip = Math.Max(1, height / (MAX_MODULES << 3)); int jSkip = Math.Max(1, width / (MAX_MODULES << 3)); int minI = 0; int maxI = height; int minJ = 0; int maxJ = width; ResultPoint pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); minI = (int)pointA.getY() - 1; ResultPoint pointB = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, -jSkip, minJ, maxJ, halfHeight >> 1); minJ = (int)pointB.getX() - 1; ResultPoint pointC = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, jSkip, minJ, maxJ, halfHeight >> 1); maxJ = (int)pointC.getX() + 1; ResultPoint pointD = findCornerFromCenter(halfHeight, iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); maxI = (int)pointD.getY() + 1; // Go try to find point A again with better information -- might have been off at first. pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 2); // Point A and D are across the diagonal from one another, // as are B and C. Figure out which are the solid black lines // by counting transitions System.Collections.ArrayList transitions = new System.Collections.ArrayList(4); transitions.Add(transitionsBetween(pointA, pointB)); transitions.Add(transitionsBetween(pointA, pointC)); transitions.Add(transitionsBetween(pointB, pointD)); transitions.Add(transitionsBetween(pointC, pointD)); Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator()); // Sort by number of transitions. First two will be the two solid sides; last two // will be the two alternating black/white sides ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions)transitions[0]; ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions)transitions[1]; // Figure out which point is their intersection by tallying up the number of times we see the // endpoints in the four endpoints. One will show up twice. System.Collections.Hashtable pointCount = new System.Collections.Hashtable(); increment(pointCount, lSideOne.getFrom()); increment(pointCount, lSideOne.getTo()); increment(pointCount, lSideTwo.getFrom()); increment(pointCount, lSideTwo.getTo()); ResultPoint maybeTopLeft = null; ResultPoint bottomLeft = null; ResultPoint maybeBottomRight = null; System.Collections.IEnumerator points = pointCount.GetEnumerator(); while (points.MoveNext()) { ResultPoint point = (ResultPoint)points.Current; int value = (int)pointCount[point]; if (value == 2) { bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides } else { // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now if (maybeTopLeft == null) { maybeTopLeft = point; } else { maybeBottomRight = point; } } } if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { throw new ReaderException(); } // Bottom left is correct but top left and bottom right might be switched ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight }; // Use the dot product trick to sort them out GenericResultPoint.orderBestPatterns(corners); // Now we know which is which: ResultPoint bottomRight = corners[0]; bottomLeft = corners[1]; ResultPoint topLeft = corners[2]; // Which point didn't we find in relation to the "L" sides? that's the top right corner ResultPoint topRight; if (!pointCount.ContainsKey(pointA)) { topRight = pointA; } else if (!pointCount.ContainsKey(pointB)) { topRight = pointB; } else if (!pointCount.ContainsKey(pointC)) { topRight = pointC; } else { topRight = pointD; } // Next determine the dimension by tracing along the top or right side and counting black/white // transitions. Since we start inside a black module, we should see a number of transitions // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to // end on a black module: // The top right point is actually the corner of a module, which is one of the two black modules // adjacent to the white module at the top right. Tracing to that corner from either the top left // or bottom right should work here, but, one will be more reliable since it's traced straight // up or across, rather than at a slight angle. We use dot products to figure out which is // better to use: int dimension; if (GenericResultPoint.crossProductZ(bottomLeft, bottomRight, topRight) < GenericResultPoint.crossProductZ(topRight, topLeft, bottomLeft)) { dimension = transitionsBetween(topLeft, topRight).getTransitions(); } else { dimension = transitionsBetween(bottomRight, topRight).getTransitions(); } dimension += 2; BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension); return(new DetectorResult(bits, new ResultPoint[] { pointA, pointB, pointC, pointD })); }
public virtual void TestShrinkToAfterShortestMatch3() { RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new TestPayloadAnalyzer(this), IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); doc.Add(new Field("content", new System.IO.StreamReader(new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes("j k a l f k k p a t a k l k t a"))))); writer.AddDocument(doc); writer.Close(); IndexSearcher is_Renamed = new IndexSearcher(directory); SpanTermQuery stq1 = new SpanTermQuery(new Term("content", "a")); SpanTermQuery stq2 = new SpanTermQuery(new Term("content", "k")); SpanQuery[] sqs = new SpanQuery[]{stq1, stq2}; SpanNearQuery snq = new SpanNearQuery(sqs, 0, true); Spans spans = snq.GetSpans(is_Renamed.GetIndexReader()); TopDocs topDocs = is_Renamed.Search(snq, 1); System.Collections.Hashtable payloadSet = new System.Collections.Hashtable(); for (int i = 0; i < topDocs.ScoreDocs.Length; i++) { while (spans.Next()) { System.Collections.Generic.ICollection<byte[]> payloads = spans.GetPayload(); for (System.Collections.IEnumerator it = payloads.GetEnumerator(); it.MoveNext(); ) { Support.CollectionsHelper.AddIfNotContains(payloadSet, new System.String(System.Text.UTF8Encoding.UTF8.GetChars((byte[]) it.Current))); } } } Assert.AreEqual(2, payloadSet.Count); if (DEBUG) { System.Collections.IEnumerator pit = payloadSet.GetEnumerator(); while (pit.MoveNext()) { System.Console.Out.WriteLine("match:" + pit.Current); } } Assert.IsTrue(payloadSet.Contains("a:Noise:10")); Assert.IsTrue(payloadSet.Contains("k:Noise:11")); }