Example #1
0
		public virtual void  TestPhrasePrefix()
		{
			RAMDirectory indexStore = new RAMDirectory();
			IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true);
			Document doc1 = new Document();
			Document doc2 = new Document();
			Document doc3 = new Document();
			Document doc4 = new Document();
			Document doc5 = new Document();
			doc1.Add(Field.Text("body", "blueberry pie"));
			doc2.Add(Field.Text("body", "blueberry strudel"));
			doc3.Add(Field.Text("body", "blueberry pizza"));
			doc4.Add(Field.Text("body", "blueberry chewing gum"));
			doc5.Add(Field.Text("body", "piccadilly circus"));
			writer.AddDocument(doc1);
			writer.AddDocument(doc2);
			writer.AddDocument(doc3);
			writer.AddDocument(doc4);
			writer.AddDocument(doc5);
			writer.Optimize();
			writer.Close();
			
			IndexSearcher searcher = new IndexSearcher(indexStore);
			
			PhrasePrefixQuery query1 = new PhrasePrefixQuery();
			PhrasePrefixQuery query2 = new PhrasePrefixQuery();
			query1.Add(new Term("body", "blueberry"));
			query2.Add(new Term("body", "strawberry"));
			
			System.Collections.ArrayList termsWithPrefix = new System.Collections.ArrayList();
			IndexReader ir = IndexReader.Open(indexStore);
			
			// this TermEnum gives "piccadilly", "pie" and "pizza".
			System.String prefix = "pi";
			TermEnum te = ir.Terms(new Term("body", prefix + "*"));
			do 
			{
				if (te.Term().Text().StartsWith(prefix))
				{
					termsWithPrefix.Add(te.Term());
				}
			}
			while (te.Next());
			
			query1.Add((Term[]) termsWithPrefix.ToArray(typeof(Term)));
			query2.Add((Term[]) termsWithPrefix.ToArray(typeof(Term)));
			
			Hits result;
			result = searcher.Search(query1);
			Assert.AreEqual(2, result.Length());
			
			result = searcher.Search(query2);
			Assert.AreEqual(0, result.Length());
		}
Example #2
0
        public Interface[] InterfacesArray()
        {
            System.Collections.ArrayList arrList = new System.Collections.ArrayList();
                        int i = 0;

                        while (true)
                        {
                                IntPtr cIf;
                                Interface iface;

                                cIf = UnmanagedGetInterfaceN(cNode, i);

                                if (cIf == IntPtr.Zero)
                                {
                                        //Debug.WriteLine("UnmanagedAttribute zero pointer");
                                        break;
                                }

                                iface = new Interface(cIf);
                                i++;
                                arrList.Add(iface);
                        }
                        Interface[] array = (Interface[])arrList.ToArray(typeof(Interface));

                        Debug.WriteLine("NodeList with " + i + " nodes");

                        return array;
        }
Example #3
0
        public virtual OutputQueueData[] getAllOutputQueueData()
        {
            System.Collections.ArrayList ary = new System.Collections.ArrayList();

            if (outputQueue.Count == 0)
                return null;
            else
            {

                System.Collections.IEnumerator ie = outputQueue.GetEnumerator();
                while (ie.MoveNext())
                {
                    OutputQueueData quedata = (OutputQueueData)((System.Collections.DictionaryEntry)ie.Current).Value;

                    ary.Add(quedata);

                }
            }

            ary.Sort();
            object[] data = ary.ToArray();

            OutputQueueData[] retobjs = new OutputQueueData[data.Length];

            for (int i = 0; i < data.Length; i++)
                retobjs[i] =(OutputQueueData)data[i];

            return retobjs;
        }
		public QueryTermVector(System.String queryString, Analyzer analyzer)
		{
			if (analyzer != null)
			{
				TokenStream stream = analyzer.TokenStream("", new System.IO.StringReader(queryString));
				if (stream != null)
				{
					System.Collections.ArrayList terms = new System.Collections.ArrayList();
					try
					{
						bool hasMoreTokens = false;
						
						stream.Reset();
						TermAttribute termAtt = (TermAttribute) stream.AddAttribute(typeof(TermAttribute));
						
						hasMoreTokens = stream.IncrementToken();
						while (hasMoreTokens)
						{
							terms.Add(termAtt.Term());
							hasMoreTokens = stream.IncrementToken();
						}
						ProcessTerms((System.String[]) terms.ToArray(typeof(System.String)));
					}
					catch (System.IO.IOException e)
					{
					}
				}
			}
		}
        public StartUIACacheRequestCommand()
        {
            System.Collections.ArrayList defaultPropertiesList =
                new System.Collections.ArrayList();
            defaultPropertiesList.Add("Name");
            defaultPropertiesList.Add("AutomationId");
            defaultPropertiesList.Add("ClassName");
            defaultPropertiesList.Add("ControlType");
            defaultPropertiesList.Add("NativeWindowHandle");
            defaultPropertiesList.Add("BoundingRectangle");
            defaultPropertiesList.Add("ClickablePoint");
            defaultPropertiesList.Add("IsEnabled");
            defaultPropertiesList.Add("IsOffscreen");
            this.Property = (string[])defaultPropertiesList.ToArray(typeof(string));

            System.Collections.ArrayList defaultPatternsList =
                new System.Collections.ArrayList();
            defaultPatternsList.Add("ExpandCollapsePattern");
            defaultPatternsList.Add("InvokePattern");
            defaultPatternsList.Add("ScrollItemPattern");
            defaultPatternsList.Add("SelectionItemPattern");
            defaultPatternsList.Add("SelectionPattern");
            defaultPatternsList.Add("TextPattern");
            defaultPatternsList.Add("TogglePattern");
            defaultPatternsList.Add("ValuePattern");
            this.Pattern = (string[])defaultPatternsList.ToArray(typeof(string));

            this.Scope = "SUBTREE";

            this.Filter = "RAW";
        }
Example #6
0
 private object ProcessStartsWithPlaylist(string buffer)
 {
     System.Collections.ArrayList result = new System.Collections.ArrayList(5);
     foreach (string line in buffer.Split('\n'))
         if (line.StartsWith("playlist: "))
             result.Add(line.Substring(10)); // "playlist: ".Length
     return result.ToArray(typeof(string));
 }
		private string[] GetAvailableDestinationTables()
		{
			System.Collections.ArrayList result = new System.Collections.ArrayList();
			result.Add("New table");
			foreach (Altaxo.Data.DataTable table in Current.Project.DataTableCollection)
				result.Add(table.Name);

			return (string[])result.ToArray(typeof(string));
		}
Example #8
0
 public static byte[] String_To_Bytes(string[] S)
 {
     System.Collections.ArrayList BB = new System.Collections.ArrayList();
     foreach (string s in S)
     {
         // check for empty strings
         if (!(s.Equals("")))
             BB.AddRange(String_To_Bytes(s));
         BB.Add((byte) 10); // Adds the newline character at the end of each string.
     }
     return (byte[]) BB.ToArray(typeof (byte));
 }
Example #9
0
 public override object[] BuildContent( int baseSequence, out int finalSequence)
 {
     int sequence = baseSequence;
     System.Collections.ArrayList batchObjects = new System.Collections.ArrayList();
     foreach (RequestObject req in _batchedRequests)
     {
         req.Sequence = sequence++;
         batchObjects.Add(req.ToRequestObject());
     }
     finalSequence = sequence;
     return new object[] { _sessionInfo.ToRequestObject(), batchObjects.ToArray(), _field2  };
 }
Example #10
0
 public static byte[] Array_To_Bytes(System.Array Arr)
 {
     System.Collections.ArrayList BB = new System.Collections.ArrayList();
     foreach (var V in Arr)
     {
         string S = V.ToString();
         // check for empty strings
         if (!(S.Equals("")))
             BB.AddRange(String_To_Bytes(S));
         BB.Add((byte)10); // Adds the newline character at the end of each array item.
     }
     return (byte[]) BB.ToArray(typeof (byte));
 }
Example #11
0
		/// <summary> Returns sub IndexReader that contains the given document id.
		/// 
		/// </summary>
		/// <param name="doc">id of document
		/// </param>
		/// <param name="reader">parent reader
		/// </param>
		/// <returns> sub reader of parent which contains the specified doc id
		/// </returns>
		public static IndexReader SubReader(int doc, IndexReader reader)
		{
			System.Collections.ArrayList subReadersList = new System.Collections.ArrayList();
			ReaderUtil.GatherSubReaders(subReadersList, reader);
			IndexReader[] subReaders = (IndexReader[]) subReadersList.ToArray(typeof(IndexReader));
			int[] docStarts = new int[subReaders.Length];
			int maxDoc = 0;
			for (int i = 0; i < subReaders.Length; i++)
			{
				docStarts[i] = maxDoc;
				maxDoc += subReaders[i].MaxDoc();
			}
			return subReaders[ReaderUtil.SubIndex(doc, docStarts)];
		}
 /**************************************************�ַ��������㷨**************************************************/
 public static string DecryptString(string str)
 {
     if ((str.Length % 4) != 0)
     {
         throw new ArgumentException("������ȷ��BASE64���룬���顣", "str");
     }
     if (!System.Text.RegularExpressions.Regex.IsMatch(str, "^[A-Z0-9/+=]*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
     {
         throw new ArgumentException("��������ȷ��BASE64���룬���顣", "str");
     }
     string Base64Code = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";
     int page = str.Length / 4;
     System.Collections.ArrayList outMessage = new System.Collections.ArrayList(page * 3);
     char[] message = str.ToCharArray();
     for (int i = 0; i < page; i++)
     {
         byte[] instr = new byte[4];
         instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
         instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
         instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
         instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
         byte[] outstr = new byte[3];
         outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
         if (instr[2] != 64)
         {
             outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
         }
         else
         {
             outstr[2] = 0;
         }
         if (instr[3] != 64)
         {
             outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
         }
         else
         {
             outstr[2] = 0;
         }
         outMessage.Add(outstr[0]);
         if (outstr[1] != 0)
             outMessage.Add(outstr[1]);
         if (outstr[2] != 0)
             outMessage.Add(outstr[2]);
     }
     byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
     return System.Text.Encoding.Default.GetString(outbyte);
 }
Example #13
0
    public static string[] NullTermPtrToStringArray (IntPtr null_term_array, bool owned) {
      if (null_term_array == IntPtr.Zero)
        return new string [0];

      int count = 0;
      System.Collections.ArrayList result = new System.Collections.ArrayList ();
      IntPtr s = Marshal.ReadIntPtr (null_term_array, count++ * IntPtr.Size);
      while (s != IntPtr.Zero) {
        result.Add (Gst.GLib.Marshaller.Utf8PtrToString (s));
        s = Marshal.ReadIntPtr (null_term_array, count++ * IntPtr.Size);
      }

      if (owned)
        g_strfreev (null_term_array);

      return (string[]) result.ToArray (typeof (string));
    }
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            //var cols = base.GetProperties();
            var dictionary = value as IDictionary<String, object>;
            var properties = new System.Collections.ArrayList();
            foreach (var e in dictionary)
            {
                properties.Add(new DictionaryPropertyDescriptor(dictionary, e.Key));
                if (e.Value != null)
                    TypeDescriptorModifier.modifyType(e.Value.GetType());
            }

            PropertyDescriptor[] props =
                (PropertyDescriptor[])properties.ToArray(typeof(PropertyDescriptor));

            return new PropertyDescriptorCollection(props);
        }
        /// <summary>
        /// Get list of unique SourceSystem values present in the collection
        /// </summary>
        /// <returns></returns>
        public BusinessObjects.WorkManagement.eWMSourceSystem[] GetSourceSystems()
        {
            BusinessObjects.WorkManagement.eWMSourceSystem[] arrPropertyValues = null;
            System.Collections.ArrayList colPropertyValues = new System.Collections.ArrayList();

            foreach (AssignmentDetails objDetails in this)
            {
                if (colPropertyValues.IndexOf(objDetails.SourceSystem) < 0)
                {
                    colPropertyValues.Add(objDetails.SourceSystem);
                }
            }

            if (colPropertyValues.Count > 0)
            {
                arrPropertyValues = (BusinessObjects.WorkManagement.eWMSourceSystem[])colPropertyValues.ToArray(typeof(BusinessObjects.WorkManagement.eWMSourceSystem));
            }

            return arrPropertyValues;
        }
 // the same as InvokeSelectItem_RadioButton()
 public void InvokeSelectionItemState_RadioButton()
 {
     string name1 = "RadioButton1";
     string auId1 = "rb111";
     string name2 = "RadioButton2";
     string auId2 = "rb222";
     string expectedResult = "True";
     ControlToForm ctf = 
         new ControlToForm(
             System.Windows.Automation.ControlType.RadioButton,
             name1,
             auId1, 
             TimeoutsAndDelays.Control_Delay0);
     System.Collections.ArrayList arrList = 
         new System.Collections.ArrayList();
     arrList.Add(ctf);
     ctf = 
         new ControlToForm(
             System.Windows.Automation.ControlType.RadioButton,
             name2,
             auId2, 
             TimeoutsAndDelays.Control_Delay0);
     arrList.Add(ctf);
     MiddleLevelCode.StartProcessWithFormAndControl(
         UIAutomationTestForms.Forms.WinFormsEmpty, 
         0,
         (ControlToForm[])arrList.ToArray(typeof(ControlToForm)));
     CmdletUnitTest.TestRunspace.RunAndEvaluateAreEqual(
         @"$null = Get-UiaWindow -pn " + 
         MiddleLevelCode.TestFormProcess +
         " | Get-UiaRadioButton -AutomationId '" + 
         auId1 + 
         "' | Invoke-UiaRadioButtonSelectItem -ItemName '" + 
         name1 +
         @"';" +
         @"Get-UiaRadioButton -AutomationId '" + 
         auId1 + 
         "' | Get-UiaRadioButtonSelectionItemState;",
         expectedResult);
 }
		public virtual void  TestMissingTerms()
		{
			System.String fieldName = "field1";
			MockRAMDirectory rd = new MockRAMDirectory();
			IndexWriter w = new IndexWriter(rd, new KeywordAnalyzer(), MaxFieldLength.UNLIMITED);
			for (int i = 0; i < 100; i++)
			{
				Document doc = new Document();
				int term = i * 10; //terms are units of 10;
				doc.Add(new Field(fieldName, "" + term, Field.Store.YES, Field.Index.NOT_ANALYZED));
				w.AddDocument(doc);
			}
			w.Close();

            IndexReader reader = IndexReader.Open(rd, true);
			IndexSearcher searcher = new IndexSearcher(reader);
			int numDocs = reader.NumDocs();
			ScoreDoc[] results;
			MatchAllDocsQuery q = new MatchAllDocsQuery();
			
			System.Collections.ArrayList terms = new System.Collections.ArrayList();
			terms.Add("5");
			results = searcher.Search(q, new FieldCacheTermsFilter(fieldName, (System.String[]) terms.ToArray(typeof(System.String))), numDocs).ScoreDocs;
			Assert.AreEqual(0, results.Length, "Must match nothing");
			
			terms = new System.Collections.ArrayList();
			terms.Add("10");
            results = searcher.Search(q, new FieldCacheTermsFilter(fieldName, (System.String[])terms.ToArray(typeof(System.String))), numDocs).ScoreDocs;
			Assert.AreEqual(1, results.Length, "Must match 1");
			
			terms = new System.Collections.ArrayList();
			terms.Add("10");
			terms.Add("20");
			results = searcher.Search(q, new FieldCacheTermsFilter(fieldName, (System.String[]) terms.ToArray(typeof(System.String))), numDocs).ScoreDocs;
			Assert.AreEqual(2, results.Length, "Must match 2");
			
			reader.Close();
			rd.Close();
		}
        public void GetControl_Win32_X2_SearchInAutomationIdClassName_Timeout2000()
        {
            string expectedClass = "button";
            System.Collections.ArrayList arrList =
                new System.Collections.ArrayList();
            ControlToForm ctf1 =
                new ControlToForm(
                    System.Windows.Automation.ControlType.Edit,
                    "aaa",
                    expectedClass,
                    0);
            arrList.Add(ctf1);
            ControlToForm ctf2 =
                new ControlToForm(
                    System.Windows.Automation.ControlType.Edit,
                    "bbb",
                    "auid2",
                    0);
            arrList.Add(ctf2);
            ControlToForm ctf3 =
                new ControlToForm(
                    System.Windows.Automation.ControlType.Button,
                    "ccc",
                    expectedClass,
                    0);
            arrList.Add(ctf3);

            MiddleLevelCode.StartProcessWithFormAndControl(
                UIAutomationTestForms.Forms.WinFormsEmpty,
                0,
                (ControlToForm[])arrList.ToArray(typeof(ControlToForm)));
            CmdletUnitTest.TestRunspace.RunAndEvaluateAreEqual(
                @"(Get-UIAWindow -n " +
                MiddleLevelCode.TestFormNameEmpty +
                " | Get-UIAControl '" +
                expectedClass +
                "' -Win32 -Timeout 2000).Count;",
                "2");
        }
 public void GetControl_X2_SearchInName_Timeout2000()
 {
     string expectedName = "my_name";
     System.Collections.ArrayList arrList = 
         new System.Collections.ArrayList();
     ControlToForm ctf1 = 
         new ControlToForm(
             System.Windows.Automation.ControlType.Button,
             expectedName,
             "1", 
             0);
     arrList.Add(ctf1);
     ControlToForm ctf2 = 
         new ControlToForm(
             System.Windows.Automation.ControlType.Button,
             "e2",
             "2", 
             0);
     arrList.Add(ctf2);
     ControlToForm ctf3 = 
         new ControlToForm(
             System.Windows.Automation.ControlType.Button,
             expectedName,
             "3", 
             0);
     arrList.Add(ctf3);
     
     MiddleLevelCode.StartProcessWithFormAndControl(
         UIAutomationTestForms.Forms.WinFormsEmpty, 
         0,
         (ControlToForm[])arrList.ToArray(typeof(ControlToForm)));
     CmdletUnitTest.TestRunspace.RunAndEvaluateAreEqual(
         @"(Get-UiaWindow -n " + 
         MiddleLevelCode.TestFormNameEmpty +
         " | Get-UiaControl '" +
         expectedName +
         "' -Timeout 2000).Count;",
         "2");
 }
 public QueryTermVector(System.String queryString, Analyzer analyzer)
 {
     if (analyzer != null)
     {
         TokenStream stream = analyzer.TokenStream("", new System.IO.StringReader(queryString));
         if (stream != null)
         {
             System.Collections.ArrayList terms = new System.Collections.ArrayList();
             try
             {
                 Token reusableToken = new Token();
                 for (Token nextToken = stream.Next(reusableToken); nextToken != null; nextToken = stream.Next(reusableToken))
                 {
                     terms.Add(nextToken.Term());
                 }
                 ProcessTerms((System.String[]) terms.ToArray(typeof(System.String)));
             }
             catch (System.IO.IOException)
             {
             }
         }
     }
 }
		public QueryTermVector(System.String queryString, Analyzer analyzer)
		{
			if (analyzer != null)
			{
				TokenStream stream = analyzer.TokenStream("", new System.IO.StringReader(queryString));
				if (stream != null)
				{
					Token next = null;
					System.Collections.ArrayList terms = new System.Collections.ArrayList();
					try
					{
						while ((next = stream.Next()) != null)
						{
							terms.Add(next.TermText());
						}
						ProcessTerms((System.String[]) terms.ToArray(typeof(System.String)));
					}
					catch (System.IO.IOException)
					{
					}
				}
			}
		}
		private void UpdateRootTiles()
		{
			int numberRows = (int)(180.0f/m_lzts);
			
			System.Collections.ArrayList tileList = new System.Collections.ArrayList();

			int istart = 0;
			int iend = numberRows;
			int jstart = 0;
			int jend = numberRows * 2;

			for(int i = istart; i < iend; i++)
			{
				for(int j = jstart; j < jend; j++)
				{
					double north = (i + 1) * m_lzts - 90.0f;
					double south = i  * m_lzts - 90.0f;
					double west = j * m_lzts - 180.0f;
					double east = (j + 1) * m_lzts - 180.0f;
					
					ProjectedVectorTile newTile = new ProjectedVectorTile(
						new GeographicBoundingBox(
						north,
						south,
						west,
						east),
						this);

					newTile.Level = 0;
					newTile.Row = i;
					newTile.Col = j;
					tileList.Add(newTile);
				}
			}

			m_rootTiles = (ProjectedVectorTile[])tileList.ToArray(typeof(ProjectedVectorTile));
		}
Example #23
0
        // --
        public JobCrush(CrushParams p) : base("Compress CD")
        {
            // Check for input files
            // :: --------------------
            if (!CDCRUSH.check_file_(p.inputFile, ".cue"))
            {
                fail(msg: CDCRUSH.ERROR);
                return;
            }

            if (string.IsNullOrEmpty(p.outputDir))
            {
                p.outputDir = Path.GetDirectoryName(p.inputFile);
            }

            if (!FileTools.createDirectory(p.outputDir))
            {
                fail(msg: "Can't create Output Dir " + p.outputDir);
                return;
            }

            p.tempDir = Path.Combine(CDCRUSH.TEMP_FOLDER, Guid.NewGuid().ToString().Substring(0, 12));
            if (!FileTools.createDirectory(p.tempDir))
            {
                fail(msg: "Can't create TEMP dir");
                return;
            }

            // IMPORTANT!! sharedData gets set by value, NOT A POINTER, do not make changes to p after this
            jobData = p;

            // --
            // - Read the CUE file ::
            add(new CTask((t) =>
            {
                var cd     = new CueReader();
                jobData.cd = cd;

                if (!cd.load(p.inputFile))
                {
                    t.fail(msg: cd.ERROR);
                    return;
                }

                // Post CD CUE load ::

                if (!string.IsNullOrWhiteSpace(p.cdTitle))        // valid:
                {
                    cd.CD_TITLE = FileTools.sanitizeFilename(p.cdTitle);
                }

                // Real quality to string name
                if (p.audioQuality == 0)
                {
                    cd.CD_AUDIO_QUALITY = "FLAC";
                }
                else
                {
                    cd.CD_AUDIO_QUALITY = FFmpeg.QUALITY[(p.audioQuality - 1)].ToString() + "kbps";
                }

                // This flag notes that all files will go to the TEMP folder
                jobData.workFromTemp = !cd.MULTIFILE;

                // Generate the final arc name now that I have the CD TITLE
                jobData.finalArcPath = Path.Combine(p.outputDir, cd.CD_TITLE + ".arc");

                t.complete();
            }, "Reading", true));


            // - Cut tracks if it has to
            // ---------------------------
            add(new TaskCutTrackFiles());

            // - Compress tracks
            // ---------------------
            add(new CTask((t) =>
            {
                CueReader cd = jobData.cd;
                foreach (CueTrack tr in cd.tracks)
                {
                    addNextAsync(new TaskCompressTrack(tr));
                }        //--
                t.complete();
            }, "Preparing"));


            // Create Archive
            // Add all tracks to the final archive
            // ---------------------
            add(new CTask((t) => {
                CueReader cd = jobData.cd;

                // -- Get list of files::
                System.Collections.ArrayList files = new System.Collections.ArrayList();
                foreach (var tr in cd.tracks)
                {
                    files.Add(tr.workingFile);             // Working file is valid, was set earlier
                }

                var arc = new FreeArc(CDCRUSH.TOOLS_PATH);
                t.handleCliReport(arc);
                arc.compress((string[])files.ToArray(typeof(string)), jobData.finalArcPath);

                t.killExtra = () => arc.kill();
            }, "Compressing"));


            // - Create CD SETTINGS and push it to the final archive
            // ( I am appending these files so that they can be quickly loaded later )
            // --------------------
            add(new CTask((t) =>
            {
                CueReader cd = jobData.cd;

                        #if DEBUG
                cd.debugInfo();
                        #endif

                string path_settings = Path.Combine(p.tempDir, CDCRUSH.CDCRUSH_SETTINGS);
                if (!cd.saveJson(path_settings))
                {
                    t.fail(msg: cd.ERROR);
                    return;
                }

                // - Cover Image Set?
                string path_cover;
                if (p.cover != null)
                {
                    path_cover = Path.Combine(p.tempDir, CDCRUSH.CDCRUSH_COVER);
                    File.Copy(p.cover, path_cover);
                }
                else
                {
                    path_cover = null;
                }

                // - Append the file(s)
                var arc = new FreeArc(CDCRUSH.TOOLS_PATH);
                t.handleCliReport(arc);
                arc.appendFiles(new string[] { path_settings, path_cover }, jobData.finalArcPath);

                t.killExtra = () => arc.kill();
            }, "Finalizing"));

            // - Get post data
            add(new CTask((t) =>
            {
                var finfo           = new FileInfo(jobData.finalArcPath);
                jobData.crushedSize = (int)finfo.Length;
                t.complete();
            }, "Finalizing"));

            // -- COMPLETE --
        }// -----------------------------------------
Example #24
0
        // --
        public JobCrush(CrushParams p) : base("Compress CD")
        {
            // Check for input files
            // :: --------------------
            if (!CDCRUSH.check_file_(p.inputFile, ".cue"))
            {
                fail(msg: CDCRUSH.ERROR);
                return;
            }

            if (string.IsNullOrEmpty(p.outputDir))
            {
                p.outputDir = Path.GetDirectoryName(p.inputFile);
            }

            if (!FileTools.createDirectory(p.outputDir))
            {
                fail(msg: "Can't create Output Dir " + p.outputDir);
                return;
            }

            p.tempDir = Path.Combine(CDCRUSH.TEMP_FOLDER, Guid.NewGuid().ToString().Substring(0, 12));
            if (!FileTools.createDirectory(p.tempDir))
            {
                fail(msg: "Can't create TEMP dir");
                return;
            }

            // -
            p.flag_convert_only = false;

            // IMPORTANT!! sharedData gets set by value, NOT A POINTER, do not make changes to p after this
            jobData = p;

            //
            hack_setExpectedProgTracks(p.expectedTracks + 3);

            // --
            // - Read the CUE file ::
            add(new CTask((t) =>
            {
                var cd     = new CueReader();
                jobData.cd = cd;

                if (!cd.load(p.inputFile))
                {
                    t.fail(msg: cd.ERROR);
                    return;
                }

                // Meaning the tracks are going to be extracted in the temp folder
                jobData.flag_sourceTracksOnTemp = (!cd.MULTIFILE && cd.tracks.Count > 1);

                // In case user named the CD, otherwise it's going to be the same
                if (!string.IsNullOrWhiteSpace(p.cdTitle))
                {
                    cd.CD_TITLE = FileTools.sanitizeFilename(p.cdTitle);
                }

                // Real quality to string name
                cd.CD_AUDIO_QUALITY = CDCRUSH.getAudioQualityString(p.audioQuality);

                // Generate the final arc name now that I have the CD TITLE
                jobData.finalArcPath = Path.Combine(p.outputDir, cd.CD_TITLE + ".arc");

                t.complete();
            }, "-Reading"));

            // - Cut tracks
            // ---------------------------
            add(new TaskCutTrackFiles());

            // - Compress tracks
            // ---------------------
            add(new CTask((t) =>
            {
                CueReader cd = jobData.cd;
                foreach (CueTrack tr in cd.tracks)
                {
                    addNextAsync(new TaskCompressTrack(tr));
                }        //--
                t.complete();
            }, "-Preparing"));


            // Create Archive
            // Add all tracks to the final archive
            // ---------------------
            add(new CTask((t) => {
                CueReader cd = jobData.cd;

                // -- Get list of files::
                System.Collections.ArrayList files = new System.Collections.ArrayList();
                foreach (var tr in cd.tracks)
                {
                    files.Add(tr.workingFile);             // Working file is valid, was set earlier
                }

                // Compress all the track files
                var arc = new FreeArc(CDCRUSH.TOOLS_PATH);
                t.handleCliReport(arc);
                arc.compress((string[])files.ToArray(typeof(string)), jobData.finalArcPath, p.compressionLevel);
                arc.onProgress = (pr) => t.PROGRESS = pr;
                t.killExtra    = () => arc.kill();
            }, "Compressing"));


            // - Create CD SETTINGS and push it to the final archive
            // ( I am appending these files so that they can be quickly loaded later )
            // --------------------
            add(new CTask((t) =>
            {
                CueReader cd = jobData.cd;

                        #if DEBUG
                LOG.log(cd.getDetailedInfo());
                        #endif

                string path_settings = Path.Combine(p.tempDir, CDCRUSH.CDCRUSH_SETTINGS);
                if (!cd.saveJson(path_settings))
                {
                    t.fail(msg: cd.ERROR);
                    return;
                }

                // - Cover Image Set?
                string path_cover;
                if (p.cover != null)
                {
                    path_cover = Path.Combine(p.tempDir, CDCRUSH.CDCRUSH_COVER);
                    File.Copy(p.cover, path_cover);
                }
                else
                {
                    path_cover = null;
                }

                // - Append the file(s)
                var arc = new FreeArc(CDCRUSH.TOOLS_PATH);
                t.handleCliReport(arc);
                arc.appendFiles(new string[] { path_settings, path_cover }, jobData.finalArcPath);

                t.killExtra = () => arc.kill();
            }, "Finalizing"));

            // - Get post data
            add(new CTask((t) =>
            {
                var finfo           = new FileInfo(jobData.finalArcPath);
                jobData.crushedSize = (int)finfo.Length;
                t.complete();
            }, "-Finalizing"));

            // -- COMPLETE --
        }// -----------------------------------------
Example #25
0
            public bool EvaluateW(double x, double y, ref SySal.BasicTypes.Vector sloped, ref SySal.DAQSystem.Scanning.IntercalibrationInfo posd)
            {
                int    ix = (int)((x - RefRect.MinX) / CellSize - 0.5);
                int    iy = (int)((y - RefRect.MinY) / CellSize - 0.5);
                int    iix, iiy;
                int    i, j;
                double dx, dy;

                System.Collections.ArrayList arr = new System.Collections.ArrayList();
                if (ix >= 0 && ix < XCells && iy >= 0 && iy < YCells && m_Grid[ix, iy].Result == NumericalTools.ComputationResult.OK && m_Grid[ix, iy].Matches >= MinMatches)
                {
                    arr.Add(m_Grid[ix, iy]);
                }
                foreach (int [] dv in dirs)
                {
                    for (i = 0; i < MaxXYCells; i++)
                    {
                        iix = ix + dv[0] + i * dv[2];
                        if (iix < 0 || iix >= XCells)
                        {
                            continue;
                        }
                        iiy = iy + dv[1] + i * dv[3];
                        if (iiy < 0 || iiy >= YCells)
                        {
                            continue;
                        }
                        if (m_Grid[iix, iiy].Result == NumericalTools.ComputationResult.OK && m_Grid[iix, iiy].Matches >= MinMatches)
                        {
                            arr.Add(m_Grid[iix, iiy]);
                            break;
                        }
                    }
                }
                RTrackCell[] activecells         = (RTrackCell[])arr.ToArray(typeof(RTrackCell));
                if (activecells.Length == 0)
                {
                    return(false);
                }
                double[] w                       = new double[activecells.Length];
                double[] mw                      = new double[activecells.Length];
                double   w_all                   = 0.0;

                for (i = 0; i < activecells.Length; i++)
                {
                    dx    = x - activecells[i].Average.X;
                    dy    = y - activecells[i].Average.Y;
                    mw[i] = dx * dx + dy * dy;
                }
                for (i = 0; i < w.Length; i++)
                {
                    w[i] = 1.0;
                    for (j = 0; j < mw.Length; j++)
                    {
                        if (i != j)
                        {
                            w[i] *= mw[j];
                        }
                    }
                }
                for (i = 0; i < w.Length; i++)
                {
                    w_all += w[i];
                }
                for (i = 0; i < w.Length; i++)
                {
                    w[i] /= w_all;
                }
                posd.MXX = posd.MXY = posd.MYX = posd.MYY = posd.TX = posd.TY = posd.TZ = 0.0;
                sloped.X = sloped.Y = 0;
                for (i = 0; i < w.Length; i++)
                {
                    posd.MXX += activecells[i].AlignInfo.MXX * w[i];
                    posd.MXY += activecells[i].AlignInfo.MXY * w[i];
                    posd.MYX += activecells[i].AlignInfo.MYX * w[i];
                    posd.MYY += activecells[i].AlignInfo.MYY * w[i];
                    posd.TX  += (activecells[i].AlignInfo.TX + activecells[i].AlignInfo.MXX * (x - activecells[i].AlignInfo.RX) + activecells[i].AlignInfo.MXY * (y - activecells[i].AlignInfo.RY) + (activecells[i].AlignInfo.RX - x)) * w[i];
                    posd.TY  += (activecells[i].AlignInfo.TY + activecells[i].AlignInfo.MYX * (x - activecells[i].AlignInfo.RX) + activecells[i].AlignInfo.MYY * (y - activecells[i].AlignInfo.RY) + (activecells[i].AlignInfo.RY - y)) * w[i];
                    posd.TZ  += activecells[i].AlignInfo.TZ * w[i];
                    sloped.X += activecells[i].SlopeAlignInfo.X * w[i];
                    sloped.Y += activecells[i].SlopeAlignInfo.Y * w[i];
                }
                sloped.Z = 0.0;
                posd.RX  = x;
                posd.RY  = y;
                return(true);
            }
Example #26
0
        /// <summary>
        /// Reads data from the provided data reader and returns
        /// an array of mapped objects.
        /// </summary>
        /// <param name="reader">The <see cref="System.Data.IDataReader"/> object to read data from the table.</param>
        /// <param name="startIndex">The index of the first record to map.</param>
        /// <param name="length">The number of records to map.</param>
        /// <param name="totalRecordCount">A reference parameter that returns the total number
        /// of records in the reader object if 0 was passed into the method; otherwise it returns -1.</param>
        /// <returns>An array of <see cref="VoteRow"/> objects.</returns>
        protected virtual VoteRow[] MapRecords(IDataReader reader,
                                               int startIndex, int length, ref int totalRecordCount)
        {
            if (0 > startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
            }
            if (0 > length)
            {
                throw new ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
            }

            int vote_IDColumnIndex           = reader.GetOrdinal("Vote_ID");
            int userIDColumnIndex            = reader.GetOrdinal("UserID");
            int vote_TitleColumnIndex        = reader.GetOrdinal("Vote_Title");
            int vote_StartDateColumnIndex    = reader.GetOrdinal("Vote_StartDate");
            int vote_EndDateColumnIndex      = reader.GetOrdinal("Vote_EndDate");
            int vote_ParentColumnIndex       = reader.GetOrdinal("Vote_Parent");
            int vote_Parent_ImageColumnIndex = reader.GetOrdinal("Vote_Parent_Image");
            int vote_InitContentColumnIndex  = reader.GetOrdinal("Vote_InitContent");
            int cat_IDColumnIndex            = reader.GetOrdinal("Cat_ID");

            System.Collections.ArrayList recordList = new System.Collections.ArrayList();
            int ri = -startIndex;

            while (reader.Read())
            {
                ri++;
                if (ri > 0 && ri <= length)
                {
                    VoteRow record = new VoteRow();
                    recordList.Add(record);

                    record.Vote_ID = Convert.ToInt32(reader.GetValue(vote_IDColumnIndex));
                    if (!reader.IsDBNull(userIDColumnIndex))
                    {
                        record.UserID = Convert.ToString(reader.GetValue(userIDColumnIndex));
                    }
                    record.Vote_Title = Convert.ToString(reader.GetValue(vote_TitleColumnIndex));
                    if (!reader.IsDBNull(vote_StartDateColumnIndex))
                    {
                        record.Vote_StartDate = Convert.ToDateTime(reader.GetValue(vote_StartDateColumnIndex));
                    }
                    if (!reader.IsDBNull(vote_EndDateColumnIndex))
                    {
                        record.Vote_EndDate = Convert.ToDateTime(reader.GetValue(vote_EndDateColumnIndex));
                    }
                    if (!reader.IsDBNull(vote_ParentColumnIndex))
                    {
                        record.Vote_Parent = Convert.ToInt32(reader.GetValue(vote_ParentColumnIndex));
                    }
                    if (!reader.IsDBNull(vote_Parent_ImageColumnIndex))
                    {
                        record.Vote_Parent_Image = Convert.ToString(reader.GetValue(vote_Parent_ImageColumnIndex));
                    }
                    if (!reader.IsDBNull(vote_InitContentColumnIndex))
                    {
                        record.Vote_InitContent = Convert.ToString(reader.GetValue(vote_InitContentColumnIndex));
                    }
                    record.Cat_ID = Convert.ToInt32(reader.GetValue(cat_IDColumnIndex));

                    if (ri == length && 0 != totalRecordCount)
                    {
                        break;
                    }
                }
            }

            totalRecordCount = 0 == totalRecordCount ? ri + startIndex : -1;
            return((VoteRow[])(recordList.ToArray(typeof(VoteRow))));
        }
Example #27
0
 /// <summary>Returns the set of terms in this phrase. </summary>
 public virtual Term[] GetTerms()
 {
     return((Term[])terms.ToArray(typeof(Term)));
 }
Example #28
0
        public JsonResult ListPhyDelOld()
        {
            #region 权限控制
            int[] iRangePage         = { AddPageNodeId, EditPageNodeId };
            int   iCurrentPageNodeId = AddPageNodeId;
            int   iCurrentButtonId   = (int)EButtonType.PhyDelete;
            var   tempNoAuth         = Utits.IsOperateAuth(iRangePage, iCurrentPageNodeId, iCurrentButtonId);
            if (tempNoAuth.ErrorType != 1)
            {
                return(Json(tempNoAuth));
            }
            #endregion

            string _ids = RequestParameters.Pstring("ids");
            if (string.IsNullOrEmpty(_ids))
            {
                var sRetrunModel = new ResultMessage();
                sRetrunModel.ErrorType      = 0;
                sRetrunModel.MessageContent = "参数错误.";
                return(Json(sRetrunModel));
            }
            string[] strids = _ids.Split(',');
            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            for (int i = 0; i < strids.Length; i++)
            {
                if (RegexValidate.IsGuid(strids[i]))
                {
                    arrayList.Add(strids[i]);
                }
            }
            string[] ids = (string[])arrayList.ToArray(typeof(string));
            if (!ids.Any())
            {
                var sRetrunModel = new ResultMessage();
                sRetrunModel.ErrorType      = 0;
                sRetrunModel.MessageContent = "参数错误.";
                return(Json(sRetrunModel));
            }
            string   _bedIds   = RequestParameters.Pstring("bedIds");
            string[] strbedIds = _bedIds.Split(',');
            System.Collections.ArrayList arrayBedIdList = new System.Collections.ArrayList();
            for (int i = 0; i < strbedIds.Length; i++)
            {
                if (RegexValidate.IsGuid(strbedIds[i]))
                {
                    ParamID += strids[i] + ",";
                    arrayBedIdList.Add(strbedIds[i]);
                }
            }
            string[] bedIds          = (string[])arrayBedIdList.ToArray(typeof(string));
            var      welfareCentreId = Utits.WelfareCentreID;
            var      cBll            = new PaymentPlanBll();
            bool     isFlag          = cBll.PhysicalDeleteByCondition(ids);
            if (isFlag)
            {
                ParamState = "4";
                var cLog = new LogsBll();
                cLog.Log(ParamID.TrimEnd(','), ParamName, ParamState, Utits.CurrentUserID.ToString(), Utits.CurrentRealName.ToString(), Utits.WelfareCentreID.ToString(), Utits.ClientIPAddress.ToString());

                var sRetrunModel = new ResultMessage();
                sRetrunModel.ErrorType      = 1;
                sRetrunModel.MessageContent = "操作成功.";
                return(Json(sRetrunModel));
            }
            else
            {
                var sRetrunModel = new ResultMessage();
                sRetrunModel.ErrorType      = 0;
                sRetrunModel.MessageContent = "操作失败.";
                return(Json(sRetrunModel));
            }
        }
Example #29
0
 public override string[] GetUsableInputs()
 {
     System.Collections.ArrayList inputsArray = new System.Collections.ArrayList();
     for (int i = 0; i < InputValues.Length; i++)
     {
         if (InputValues[i] == "") continue;
         inputsArray.Add(InputValues[i]);
     }
     return (string[])inputsArray.ToArray(typeof(string));
 }
Example #30
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            // The request was not a request to invoke a server-side method.
            // Now, we will render the Javascript that will be used on the
            // client to run as a proxy or wrapper for the methods marked
            // with the AjaxMethodAttribute.

            if (context.Trace.IsEnabled)
            {
                context.Trace.Write(Constant.AjaxID, "Render class proxy Javascript");
            }


            // Check wether the javascript is already rendered and cached in the
            // current context.

            string etag     = context.Request.Headers["If-None-Match"];
            string modSince = context.Request.Headers["If-Modified-Since"];

            string path = type.FullName + "," + type.Assembly.FullName.Split(',')[0];

            if (type.Assembly.GetName().Name.StartsWith("App_Web"))
            {
                var baseType = type.BaseType;
                path = type.FullName + "," + type.Assembly.FullName.Split(',')[0];
            }
            if (Utility.Settings.UseAssemblyQualifiedName)
            {
                path = type.AssemblyQualifiedName;
            }

            if (Utility.Settings != null && Utility.Settings.UrlNamespaceMappings.ContainsValue(path))
            {
                foreach (string key in Utility.Settings.UrlNamespaceMappings.Keys)
                {
                    if (Utility.Settings.UrlNamespaceMappings[key].ToString() == path)
                    {
                        path = key;
                        break;
                    }
                }
            }

            if (context.Cache[path] != null)
            {
                CacheInfo ci = (CacheInfo)context.Cache[path];

                if (etag != null)
                {
                    if (etag == ci.ETag)        // TODO: null check
                    {
                        context.Response.StatusCode      = 304;
                        context.Response.SuppressContent = true;
                        return;
                    }
                }

                if (modSince != null)
                {
                    if (modSince.IndexOf(";") > 0)
                    {
                        // If-Modified-Since: Tue, 06 Jun 2006 10:13:38 GMT; length=2935
                        modSince = modSince.Split(';')[0];
                    }

                    try
                    {
                        DateTime modSinced = Convert.ToDateTime(modSince.ToString()).ToUniversalTime();
                        if (DateTime.Compare(modSinced, ci.LastModified.ToUniversalTime()) >= 0)
                        {
                            context.Response.StatusCode      = 304;
                            context.Response.SuppressContent = true;
                            return;
                        }
                    }
                    catch (FormatException)
                    {
                        if (context.Trace.IsEnabled)
                        {
                            context.Trace.Write(Constant.AjaxID, "The header value for If-Modified-Since = " + modSince + " could not be converted to a System.DateTime.");
                        }
                    }
                }
            }

            etag = type.AssemblyQualifiedName;
            etag = Hash5Helper.GetHash(System.Text.Encoding.Default.GetBytes(etag));

            DateTime now     = DateTime.Now;
            DateTime lastMod = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); // .ToUniversalTime();

            context.Response.AddHeader("Content-Type", "application/x-javascript");
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
            context.Response.Cache.SetETag(etag);
            context.Response.Cache.SetLastModified(lastMod);

            // Ok, we do not have the javascript rendered, yet.
            // Build the javascript source and save it to the current
            // Application context.


            string url = context.Request.ApplicationPath + (context.Request.ApplicationPath.EndsWith("/") ? "" : "/") + Utility.HandlerPath + "/" + AjaxPro.Utility.GetSessionUri() + path + Utility.HandlerExtension;



            // find all methods that are able to be used with AjaxPro

            MethodInfo[] mi = type.GetMethods();
            MethodInfo   method;

#if (NET20)
            List <MethodInfo> methods = new List <MethodInfo>();
#else
            MethodInfo[] methods;
            System.Collections.ArrayList methodList = new System.Collections.ArrayList();

            int mc = 0;
#endif

            for (int y = 0; y < mi.Length; y++)
            {
                method = mi[y];

                if (!method.IsPublic)
                {
                    continue;
                }

                AjaxMethodAttribute[] ma = (AjaxMethodAttribute[])method.GetCustomAttributes(typeof(AjaxMethodAttribute), true);

                if (ma.Length == 0)
                {
                    continue;
                }

                PrincipalPermissionAttribute[] ppa = (PrincipalPermissionAttribute[])method.GetCustomAttributes(typeof(PrincipalPermissionAttribute), true);
                if (ppa.Length > 0)
                {
                    bool permissionDenied = true;
                    for (int p = 0; p < ppa.Length && permissionDenied; p++)
                    {
#if (_____NET20)
                        if (Roles.Enabled)
                        {
                            try
                            {
                                if (!String.IsNullOrEmpty(ppa[p].Role) && !Roles.IsUserInRole(ppa[p].Role))
                                {
                                    continue;
                                }
                            }
                            catch (Exception)
                            {
                                // Should we disable this AjaxMethod of there is an exception?
                                continue;
                            }
                        }
                        else
#endif
                        if (ppa[p].Role != null && ppa[p].Role.Length > 0 && context.User != null && context.User.Identity.IsAuthenticated && !context.User.IsInRole(ppa[p].Role))
                        {
                            continue;
                        }

                        permissionDenied = false;
                    }

                    if (permissionDenied)
                    {
                        continue;
                    }
                }

#if (NET20)
                methods.Add(method);
#else
                //methods[mc++] = method;
                methodList.Add(method);
#endif
            }

#if (!NET20)
            methods = (MethodInfo[])methodList.ToArray(typeof(MethodInfo));
#endif

            // render client-side proxy file

            System.Text.StringBuilder sb  = new System.Text.StringBuilder();
            TypeJavaScriptProvider    jsp = null;

            if (Utility.Settings.TypeJavaScriptProvider != null)
            {
                try
                {
                    Type jspt = Type.GetType(Utility.Settings.TypeJavaScriptProvider);
                    if (jspt != null && typeof(TypeJavaScriptProvider).IsAssignableFrom(jspt))
                    {
                        jsp = (TypeJavaScriptProvider)Activator.CreateInstance(jspt, new object[3] {
                            type, url, sb
                        });
                    }
                }
                catch (Exception)
                {
                }
            }

            if (jsp == null)
            {
                jsp = new TypeJavaScriptProvider(type, url, sb);
            }

            jsp.RenderNamespace();
            jsp.RenderClassBegin();
#if (NET20)
            jsp.RenderMethods(methods.ToArray());
#else
            jsp.RenderMethods(methods);
#endif
            jsp.RenderClassEnd();

            context.Response.Write(sb.ToString());
            context.Response.Write("\r\n");


            // save the javascript in current Application context to
            // speed up the next requests.

            // TODO: was können wir hier machen??
            // System.Web.Caching.CacheDependency fileDepend = new System.Web.Caching.CacheDependency(type.Assembly.Location);

            context.Cache.Add(path, new CacheInfo(etag, lastMod), null,
                              System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration,
                              System.Web.Caching.CacheItemPriority.Normal, null);

            if (context.Trace.IsEnabled)
            {
                context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
            }
        }
Example #31
0
        public static void StartProcessWithFormAndControl(
            UIAutomationTestForms.Forms formCode,
            TimeoutsAndDelays formDelayEn,
            System.Windows.Automation.ControlType controlType,
            string controlName,
            string controlAutomationId,
            TimeoutsAndDelays controlDelayEn)
        {
            ControlToForm controlToForm =
                new ControlToForm(
                    controlType,
                    controlName,
                    controlAutomationId,
                    controlDelayEn);
            System.Collections.ArrayList arr =
                new System.Collections.ArrayList();
            arr.Add(controlToForm);

            StartProcessWithFormAndControl(
                formCode,
                formDelayEn,
                ((ControlToForm[])arr.ToArray(typeof(ControlToForm))));
        }
Example #32
0
 ///<summary>
 ///Copies the elements of the SymbolInfoArrayList to a new SymbolInfo array.
 ///</summary>
 ///<returns>An SymbolInfo array containing copies of the elements of the SymbolInfoArrayList.</returns>
 public SymbolInfo[] ToArray()
 {
     return((SymbolInfo[])(arr.ToArray(typeof(SymbolInfo))));
 }
Example #33
0
        private void cmdToVertex_Click(object sender, EventArgs e)
        {
            if (m_VF.Count <= 0)
            {
                return;
            }
            SySal.TotalScan.Track [] tklist = new SySal.TotalScan.Track[m_VF.Count];
            int i;

            System.Collections.ArrayList vtxaltered = new System.Collections.ArrayList();
            for (i = 0; i < tklist.Length; i++)
            {
                SySal.TotalScan.VertexFit.TrackFit tf = m_VF.Track(i);
                tklist[i] = m_V.Tracks[((SySal.TotalScan.BaseTrackIndex)tf.Id).Id];
                tklist[i].SetAttribute(SySal.TotalScan.Vertex.TrackWeightAttribute, tf.Weight);
                bool isupstream             = (tklist[i].Downstream_Z + tklist[i].Upstream_Z) > (tf.MaxZ + tf.MinZ);
                SySal.TotalScan.Vertex vtxa = isupstream ? tklist[i].Upstream_Vertex : tklist[i].Downstream_Vertex;
                if (vtxa != null)
                {
                    if (vtxaltered.Contains(vtxa) == false)
                    {
                        vtxaltered.Add(vtxa);
                    }
                    vtxa.RemoveTrack(tklist[i]);
                }
            }
            int[] ids = new int[vtxaltered.Count];
            for (i = 0; i < ids.Length; i++)
            {
                ids[i] = ((SySal.TotalScan.Vertex)vtxaltered[i]).Id;
            }
            System.Collections.ArrayList vtxremove = new System.Collections.ArrayList();
            foreach (SySal.TotalScan.Vertex vtx in vtxaltered)
            {
                try
                {
                    vtx.NotifyChanged();
                    if (vtx.AverageDistance >= 0.0)
                    {
                        continue;
                    }
                }
                catch (Exception)
                {
                    vtxremove.Add(vtx.Id);
                }
            }

            ((SySal.TotalScan.Flexi.Volume.VertexList)m_V.Vertices).Remove((int[])vtxremove.ToArray(typeof(int)));
            SySal.TotalScan.Flexi.Vertex nv = new SySal.TotalScan.Flexi.Vertex(((SySal.TotalScan.Flexi.Track)tklist[0]).DataSet, m_V.Vertices.Length);
            nv.SetId(m_V.Vertices.Length);
            for (i = 0; i < tklist.Length; i++)
            {
                SySal.TotalScan.VertexFit.TrackFit tf = m_VF.Track(i);
                if ((tklist[i].Downstream_Z + tklist[i].Upstream_Z) > (tf.MaxZ + tf.MinZ))
                {
                    nv.AddTrack(tklist[i], false);
                    tklist[i].SetUpstreamVertex(nv);
                }
                else
                {
                    nv.AddTrack(tklist[i], true);
                    tklist[i].SetDownstreamVertex(nv);
                }
            }
            try
            {
                nv.NotifyChanged();
                if (nv.AverageDistance >= 0.0)
                {
                    ((SySal.TotalScan.Flexi.Volume.VertexList)m_V.Vertices).Insert(new SySal.TotalScan.Flexi.Vertex[1] {
                        nv
                    });
                }
            }
            catch (Exception x)
            {
                MessageBox.Show("Can't create new vertex - check geometry/topology.", "Vertex error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                nv.SetId(-1);
            }
            if (nv.Id >= 0)
            {
                string s = "";
                if (ids.Length > 0)
                {
                    s += "\r\nVertices altered: {";
                    for (i = 0; i < ids.Length; i++)
                    {
                        if (i == 0)
                        {
                            s += ids[i].ToString();
                        }
                        else
                        {
                            s += ", " + ids[i].ToString();
                        }
                    }
                    s += "}";
                }
                if (vtxremove.Count > 0)
                {
                    s += "\r\nVertices removed: {";
                    for (i = 0; i < vtxremove.Count; i++)
                    {
                        if (i == 0)
                        {
                            s += vtxremove[i].ToString();
                        }
                        else
                        {
                            s += ", " + vtxremove[i].ToString();
                        }
                    }
                    s += "}";
                }
                MessageBox.Show("New vertex " + nv.Id + " created." + s + "\r\nPlease regenerate the plot to see the changes.", "Vertex created", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            TrackBrowser.RefreshAll();
            VertexBrowser.RefreshAll();
        }
Example #34
0
        public long m_lngGetFiltedItems(System.Security.Principal.IPrincipal p_objPrincipal,
                                        string[] p_strApplyUnitIDArr, string[] p_strInputGroupIDArr, out string[] p_strItemResultArr)
        {
            long lngRes = 0;

            p_strItemResultArr = null;
            if (p_strApplyUnitIDArr == null || p_strInputGroupIDArr == null)
            {
                return(-1);
            }

            clsPrivilegeHandleService objPrivilege = new clsPrivilegeHandleService();

            lngRes = objPrivilege.m_lngCheckCallPrivilege(p_objPrincipal,
                                                          "com.digitalwave.iCare.middletier.LIS.clsInputGroupSvc", "m_lngGetFiltedItems");
            if (lngRes < 0)
            {
                return(-1);
            }


            string strSQL1 = @"SELECT a.check_item_id_chr
   FROM t_aid_lis_apply_unit_detail a
  WHERE a.apply_unit_id_chr IN ('3333'*)";
            string strSQL2 = @"SELECT b.check_item_id_chr
   FROM t_bse_lis_input_group_detail b
  WHERE b.input_group_id_chr IN ('333'#)";

            com.digitalwave.iCare.middletier.HRPService.clsHRPTableService objHRPSvc = new clsHRPTableService();

            IDataParameter[] objParamArr1 = null;
            objHRPSvc.CreateDatabaseParameter(p_strApplyUnitIDArr.Length, out objParamArr1);
            IDataParameter[] objParamArr2 = null;
            objHRPSvc.CreateDatabaseParameter(p_strInputGroupIDArr.Length, out objParamArr2);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < p_strApplyUnitIDArr.Length; i++)
            {
                sb.Append(",?");
                objParamArr1[i].Value = p_strApplyUnitIDArr[i];
            }
            strSQL1 = strSQL1.Replace("*", sb.ToString());

            sb = new System.Text.StringBuilder();
            for (int j = 0; j < p_strInputGroupIDArr.Length; j++)
            {
                sb.Append(",?");
                objParamArr2[j].Value = p_strInputGroupIDArr[j];
            }
            strSQL2 = strSQL2.Replace("#", sb.ToString());

            DataTable dtbUnitItem = new DataTable();

            try
            {
                lngRes = objHRPSvc.lngGetDataTableWithParameters(strSQL1, ref dtbUnitItem, objParamArr1);
                if (lngRes > 0)
                {
                    DataTable dtbGroupItem = new DataTable();
                    lngRes = 0;
                    lngRes = objHRPSvc.lngGetDataTableWithParameters(strSQL2, ref dtbGroupItem, objParamArr2);
                    if (lngRes > 0)
                    {
                        System.Collections.ArrayList arlItem = new System.Collections.ArrayList();
                        if (dtbUnitItem != null)
                        {
                            foreach (DataRow dtr in dtbUnitItem.Rows)
                            {
                                arlItem.Add(dtr[0].ToString());
                            }
                        }
                        if (dtbGroupItem != null)
                        {
                            foreach (DataRow dtr in dtbGroupItem.Rows)
                            {
                                arlItem.Add(dtr[0].ToString());
                            }
                        }
                        p_strItemResultArr = (string[])arlItem.ToArray(typeof(string));
                    }
                }
            }
            catch (Exception objEx)
            {
                com.digitalwave.Utility.clsLogText objLogger = new clsLogText();
                bool blnRes = objLogger.LogError(objEx);//要在LogError方法中抛出异常。
                lngRes = 0;
            }
            return(lngRes);
        }
Example #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            //初始化
            int p           = int.Parse(this.textBox2.Text);
            int Generations = int.Parse(this.textBox4.Text);//迭代次数

            if (p <= Parameter.m)
            {
                Parameter.p = p;
                GA GAAlgo = new GA();
                System.Collections.ArrayList bestFitness = new System.Collections.ArrayList();
                GAAlgo.MutationRate = double.Parse(this.textBox5.Text);
                GAAlgo.CrossRate    = double.Parse(this.textBox6.Text);
                if (comboBox1.Text == (string)comboBox1.Items[1])
                {
                    GAAlgo.Selection = GA.SelectionType.Tournment;
                }
                if (comboBox2.Text == (string)comboBox2.Items[1])
                {
                    GAAlgo.Crosstype = 2;
                }
                //寻优
                GAAlgo.Initialize();//产生第一代群体
                progressBar1.Value = 0;
                GAChromosome GAChr = new GAChromosome();
                bestFitness.Clear();
                while (GAAlgo.GenerationNum < Generations)//产生下一代群体
                {
                    GAAlgo.CreateNextGeneration();
                    GAChr = GAAlgo.GetBestChromosome();
                    bestFitness.Add(GAChr.Fitness);
                }
                progressBar1.Value = 100;
                //记录结果
                Parameter.x    = GAChr.ToArray();
                Parameter.opti = 100 / GAChr.Fitness;
                //显示结果
                label10.Text = (100 / GAChr.Fitness).ToString();
                //图像分析
                GAChartForm.chartControl1.Series.Clear();
                if (checkBox1.Checked)
                {
                    ChartSeries fitnessSeries = new ChartSeries("bestFitness");
                    fitnessSeries.SeriesIndexedModelImpl = new StringIndexedModel(fitnessSeries, (double[])bestFitness.ToArray(typeof(double)));
                    GAChartForm.chartControl1.Series.Add(fitnessSeries);
                }
                if (checkBox2.Checked)
                {
                    ChartSeries total_fitnessSeries = new ChartSeries("totalFitness");
                    total_fitnessSeries.SeriesIndexedModelImpl = new StringIndexedModel(total_fitnessSeries, (double[])GAAlgo.TotalFitness.ToArray(typeof(double)));
                    GAChartForm.chartControl1.Series.Add(total_fitnessSeries);
                }
                for (int i = 0; i < GAChartForm.chartControl1.Series.Count; i++)
                {
                    GAChartForm.chartControl1.Series[i].Type = ChartSeriesType.Line;
                }
            }
        }
Example #36
0
		/// <exception cref="ParseException">throw in overridden method to disallow
		/// </exception>
		protected internal virtual Query GetFieldQuery(System.String field, System.String queryText)
		{
			// Use the analyzer to get all the tokens, and then build a TermQuery,
			// PhraseQuery, or nothing based on the term count
			
			TokenStream source = analyzer.TokenStream(field, new System.IO.StringReader(queryText));
			System.Collections.ArrayList v = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
			Lucene.Net.Analysis.Token t;
			int positionCount = 0;
			bool severalTokensAtSamePosition = false;
			
			while (true)
			{
				try
				{
					t = source.Next();
				}
				catch (System.IO.IOException e)
				{
					t = null;
				}
				if (t == null)
					break;
				v.Add(t);
				if (t.GetPositionIncrement() != 0)
					positionCount += t.GetPositionIncrement();
				else
					severalTokensAtSamePosition = true;
			}
			try
			{
				source.Close();
			}
			catch (System.IO.IOException e)
			{
				// ignore
			}
			
			if (v.Count == 0)
				return null;
			else if (v.Count == 1)
			{
				t = (Lucene.Net.Analysis.Token) v[0];
				return new TermQuery(new Term(field, t.TermText()));
			}
			else
			{
				if (severalTokensAtSamePosition)
				{
					if (positionCount == 1)
					{
						// no phrase query:
						BooleanQuery q = new BooleanQuery(true);
						for (int i = 0; i < v.Count; i++)
						{
							t = (Lucene.Net.Analysis.Token) v[i];
							TermQuery currentQuery = new TermQuery(new Term(field, t.TermText()));
							q.Add(currentQuery, BooleanClause.Occur.SHOULD);
						}
						return q;
					}
					else
					{
						// phrase query:
						MultiPhraseQuery mpq = new MultiPhraseQuery();
						System.Collections.ArrayList multiTerms = new System.Collections.ArrayList();
						for (int i = 0; i < v.Count; i++)
						{
							t = (Lucene.Net.Analysis.Token) v[i];
							if (t.GetPositionIncrement() == 1 && multiTerms.Count > 0)
							{
								mpq.Add((Term[]) multiTerms.ToArray(typeof(Term)));
								multiTerms.Clear();
							}
							multiTerms.Add(new Term(field, t.TermText()));
						}
						mpq.Add((Term[]) multiTerms.ToArray(typeof(Term)));
						return mpq;
					}
				}
				else
				{
					PhraseQuery q = new PhraseQuery();
					q.SetSlop(phraseSlop);
					for (int i = 0; i < v.Count; i++)
					{
						q.Add(new Term(field, ((Lucene.Net.Analysis.Token) v[i]).TermText()));
					}
					return q;
				}
			}
		}
Example #37
0
        private static void Main(string[] args)
        {
            // Console.WriteLine(System.Windows.Automation.ControlType.Button.ToString());
            // Console.WriteLine(System.Windows.Automation.ControlType.Button.ProgrammaticName.ToString());
            // Console.WriteLine(System.Windows.Automation.ControlType.Button.GetType().Name);


// Dumping types for further investigation

//            Console.WriteLine("Dumping the types...");
//            dumpTypes(System.Environment.GetEnvironmentVariable("TEMP",
//                                                                EnvironmentVariableTarget.User) +
//                      @"\types.txt");
//            Console.WriteLine("...completed");
//                      return;

            System.Windows.Forms.Application.EnableVisualStyles();
            System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

            // the second command-line argument FormDelay
            if (args.Length > 1 && args[1] != null && args[1] != string.Empty)
            {
                try {
                    if ((Convert.ToInt32(args[0]) != 0) &&
                        (Convert.ToInt32(args[1]) != 0))
                    {
                        int sleepTime =
                            Convert.ToInt32(args[1]);
                        System.Threading.Thread.Sleep(sleepTime);
                    }
                } catch {
                    // Console.WriteLine("Wrong arguments!Use numbers:");
                    // Console.WriteLine("TetUIAutomation Forms SleepBefore");
                    return; // 1;
                }
            }

// if (Delay > 0) {
// System.Threading.Thread.Sleep(Delay);
// }
            // the first command-line argument FormType
            if (args.Length > 0 && args[0] != null && args[0] != "")
            {
                Forms formCode;
                try {
                    formCode = (Forms)(Convert.ToInt32(args[0]));
                } catch {
                    // Console.WriteLine("Wrong arguments!Use numbers:");
                    // Console.WriteLine("TetUIAutomation Forms SleepBefore");
                    return; // 2;
                }

                // System.Windows.Forms.Application.Run(new MainForm());

                #region reserved code
//                System.Windows.Automation.ControlType ctrlType = null;
//
//                // the third command-line argument ControlType
//                if (args.Length > 2 && args[2] != null && args[2] != "") {
//                    // string _controlType = String.Empty;
//                    //_controlType = args[2].ToUpper();
//                    ctrlType =
//                        UiaHelper.GetControlTypeByTypeName(args[2]);
//                }
//
//                int controlDelay = 0;
//
//                // the fourth command-line argument ControlDelay
//                if (args.Length > 3 && args[3] != null && args[3] != string.Empty) {
//                    try {
//                        controlDelay = System.Convert.ToInt32(args[3]);
//                    } catch { }
//                }
//
//                string controlName = string.Empty;
//
//                // the fifth command-line argument ControlName
//                if (args.Length > 4 && args[4] != null && args[4] != string.Empty) {
//                    try {
//                        controlName = args[4];
//                    } catch { }
//                }
//
//                string controlAutomationId = string.Empty;
//
//                // the sixth command-line argument ControlAutomationId
//                if (args.Length > 5 && args[5] != null && args[5] != string.Empty) {
//                    try {
//                        controlAutomationId = args[5];
//                    } catch { }
//                }
//
//                switch (formCode)
//                {
//                    case Forms.WinFormsEmpty:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsEmpty(ctrlType, controlName, controlAutomationId, controlDelay));
//                        // WinFormsEmpty frmWFE = new WinFormsEmpty();
//                        // frmWFE.ShowDialog();
//                        break;
//                    case Forms.WinFormsEmptyX2:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsEmpty(ctrlType, controlName, controlAutomationId, controlDelay));
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsEmpty(ctrlType, controlName, controlAutomationId, controlDelay));
//                        break;
//                    case Forms.WinFormsAnonymous:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsAnonymous(
//                                ctrlType, controlName, controlAutomationId, controlDelay));
//                        break;
//                    case Forms.WinFormsMinimized:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsMinimized(ctrlType, controlName, controlAutomationId, controlDelay));
//                        break;
//                    case Forms.WinFormsMaximized:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsMaximized(ctrlType, controlName, controlAutomationId, controlDelay));
//                        break;
//                    case Forms.WinFormsNoTaskBar:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsNoTaskBar(ctrlType, controlName, controlAutomationId, controlDelay));
//                        break;
//                    case Forms.WinFormsRich:
//                        System.Windows.Forms.Application.Run(
//                            new WinFormsRich(ctrlType, controlName, controlAutomationId, controlDelay));
//                        break;
//
//
//                    case Forms.WPFEmpty:
//                        WPFEmpty frmWPFE = new WPFEmpty();
//                        frmWPFE.ShowDialog();
//                        //Application.Run(new MainForm());
//                        break;
//                    case Forms.WPFEmptyX2:
//                        WPFEmpty frmWPFE1 = new WPFEmpty();
//                        frmWPFE1.ShowDialog();
//                        WPFEmpty frmWPFE2 = new WPFEmpty();
//                        frmWPFE2.ShowDialog();
//                        break;
//                    case Forms.WPFAnonymous:
//                        WPFAnonymous frmWPFA = new WPFAnonymous();
//                        frmWPFA.ShowDialog();
//                        break;
//                    case Forms.WPFMinimized:
//                        WPFMinimized frmWPFMi = new WPFMinimized();
//                        frmWPFMi.ShowDialog();
//                        break;
//                    case Forms.WPFMaximized:
//                        WPFMaximized frmWPFMa = new WPFMaximized();
//                        frmWPFMa.ShowDialog();
//                        break;
//                    case Forms.WPFCollapsed:
//                        WPFCollapsed frmWPFCo = new WPFCollapsed();
//                        frmWPFCo.ShowDialog();
//                        break;
//
//                }
//            }
                #endregion reserved code

                System.Windows.Automation.ControlType ctrlType = null;
                int             controlDelay        = 0;
                string          controlName         = string.Empty;
                string          controlAutomationId = string.Empty;
                ControlToForm[] controls            = null;

                if (args.Length > 2)
                {
                    //    ControlToForm controlToForm = new ControlToForm();
                    //    for (int i = 2; i < args.Length; i++) {
                    //        controlto
                    //    }

                    System.Collections.ArrayList arrList =
                        new System.Collections.ArrayList();

                    for (int i = 2; i < args.Length; i = i + 4)
                    {
                        ControlToForm controlToForm =
                            new ControlToForm();

                        //System.Windows.Automation.ControlType ctrlType = null;
                        ctrlType = null;

                        // the third command-line argument ControlType
                        if (args[i] != null && args[i] != "")
                        {
                            ctrlType =
                                UiaHelper.GetControlTypeByTypeName(args[i]);
                            controlToForm.ControlType = ctrlType;
                        }

                        //int controlDelay = 0;
                        controlDelay = 0;

                        // the fourth command-line argument ControlDelay
                        if (args[i + 1] != null && args[i + 1] != string.Empty)
                        {
                            try {
                                controlDelay = Convert.ToInt32(args[i + 1]);
                                controlToForm.ControlDelayEn = controlDelay;
                            } catch { }
                        }

                        //string controlName = string.Empty;
                        controlName = string.Empty;

                        // the fifth command-line argument ControlName
                        if (args[i + 2] != null && args[i + 2] != string.Empty)
                        {
                            try {
                                controlName = args[i + 2];
                                controlToForm.ControlName = controlName;
                            } catch { }
                        }

                        //string controlAutomationId = string.Empty;
                        controlAutomationId = string.Empty;

                        // the sixth command-line argument ControlAutomationId
                        if (args[i + 3] != null && args[i + 3] != string.Empty)
                        {
                            try {
                                controlAutomationId = args[i + 3];
                                controlToForm.ControlAutomationId = controlAutomationId;
                            } catch { }
                        }

                        arrList.Add(controlToForm);
                    } // for (int i = 2; i < args.Length; i = i + 4)

                    controls =
                        (ControlToForm[])arrList.ToArray(typeof(ControlToForm));
                }

                switch (formCode)
                {
                case Forms.WinFormsEmpty:
                    System.Windows.Forms.Application.Run(
                        new WinFormsEmpty(controls));
                    break;

                case Forms.WinFormsEmptyX2:
                    System.Windows.Forms.Application.Run(
                        new WinFormsEmpty(controls));
                    System.Windows.Forms.Application.Run(
                        new WinFormsEmpty(controls));
                    break;

                case Forms.WinFormsAnonymous:
                    System.Windows.Forms.Application.Run(
                        new WinFormsAnonymous(
                            ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsMinimized:
                    System.Windows.Forms.Application.Run(
                        new WinFormsMinimized(ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsMaximized:
                    System.Windows.Forms.Application.Run(
                        new WinFormsMaximized(ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsNoTaskBar:
                    System.Windows.Forms.Application.Run(
                        new WinFormsNoTaskBar(ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsTripled:
                    System.Windows.Forms.Application.Run(
                        new WinFormsTripled(controls));
                    break;

                case Forms.WinFormsThreeSet:
                    System.Windows.Forms.Application.Run(
                        new WinFormsOuter()); //(controls));
                    break;

                case Forms.WinFormsWithMenus:
                    System.Windows.Forms.Application.Run(
                        new WinFormsWithMenus());
                    break;

                case Forms.WinFormsRich:
                    System.Windows.Forms.Application.Run(
                        new WinFormsRich()); //ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsFull:
                    System.Windows.Forms.Application.Run(
                        new WinFormsFull()); //ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsWizard:
                    System.Windows.Forms.Application.Run(
                        new WinFormsWizard()); //ctrlType, controlName, controlAutomationId, controlDelay));
                    break;

                case Forms.WinFormsWithGrid:
                    System.Windows.Forms.Application.Run(
                        new WinFormsWithGrid());
                    break;

                case Forms.WinFormsWithLists:
                    System.Windows.Forms.Application.Run(
                        new WinFormsWithLists());
                    break;

                case Forms.WPFEmpty:
                    WPFEmpty frmWPFE = new WPFEmpty();
                    frmWPFE.ShowDialog();
                    //Application.Run(new MainForm());
                    break;

                case Forms.WPFEmptyX2:
                    WPFEmpty frmWPFE1 = new WPFEmpty();
                    frmWPFE1.ShowDialog();
                    WPFEmpty frmWPFE2 = new WPFEmpty();
                    frmWPFE2.ShowDialog();
                    break;

                case Forms.WPFAnonymous:
                    WPFAnonymous frmWPFA = new WPFAnonymous();
                    frmWPFA.ShowDialog();
                    break;

                case Forms.WPFMinimized:
                    WPFMinimized frmWPFMi = new WPFMinimized();
                    frmWPFMi.ShowDialog();
                    break;

                case Forms.WPFMaximized:
                    WPFMaximized frmWPFMa = new WPFMaximized();
                    frmWPFMa.ShowDialog();
                    break;

                case Forms.WPFCollapsed:
                    WPFCollapsed frmWPFCo = new WPFCollapsed();
                    frmWPFCo.ShowDialog();
                    break;

                case Forms.WPFFull:
                    WPFFull frmWPFFull = new WPFFull();
                    frmWPFFull.ShowDialog();
                    break;
//                case Forms.WPFWizard:
//                    WPFWizard frmWPFWizard = new WPFWizard();
//                    frmWPFWizard.ShowDialog();
//                    break;
                }

//            } // if (args.Length > 2)
//            else {
//                System.Windows.Forms.Application.Run(
//                    new WinFormsEmpty(ctrlType, 0));
//            }
            }


//            // the third command-line argument ControlType
//            if (args.Length > 2 && args[2] != null && args[2] != string.Empty)
//            {
//
//
//                FormControls controls;
//                try {
//                    controls = (FormControls)(System.Convert.ToInt32(args[2]));
//                } catch {
//                    // Console.WriteLine("Wrong arguments!Use numbers:");
//                    // Console.WriteLine("TetUIAutomation Forms SleepBefore");
//                    return; // 2;
//                }
//
//                System.Windows.Forms.Application.EnableVisualStyles();
//                System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
//                // System.Windows.Forms.Application.Run(new MainForm());
//
//
//                System.Windows.Automation.ControlType ctrlType = null;
//                if (args.Length > 2 && args[2] != null && args[2] != "") {
//                    // string _controlType = String.Empty;
//                    //_controlType = args[2].ToUpper();
//                    ctrlType =
//                        UiaHelper.GetControlTypeByTypeName(args[2]);
//
//
//                try {
//                    if ((System.Convert.ToInt32(args[0]) != 0) &&
//                        (System.Convert.ToInt32(args[1]) != 0))
//                    {
//                        int sleepTime =
//                            System.Convert.ToInt32(args[1]);
//                        System.Threading.Thread.Sleep(sleepTime);
//                    }
//                } catch {
//                    // Console.WriteLine("Wrong arguments!Use numbers:");
//                    // Console.WriteLine("TetUIAutomation Forms SleepBefore");
//                    return; // 1;
//                }
//            }
        }
Example #38
0
        /// <summary>
        /// Reads data from the provided data reader and returns
        /// an array of mapped objects.
        /// </summary>
        /// <param name="reader">The <see cref="System.Data.IDataReader"/> object to read data from the table.</param>
        /// <param name="startIndex">The index of the first record to map.</param>
        /// <param name="length">The number of records to map.</param>
        /// <param name="totalRecordCount">A reference parameter that returns the total number
        /// of records in the reader object if 0 was passed into the method; otherwise it returns -1.</param>
        /// <returns>An array of <see cref="PhoneCardRow"/> objects.</returns>
        protected virtual PhoneCardRow[] MapRecords(IDataReader reader,
                                                    int startIndex, int length, ref int totalRecordCount)
        {
            if (0 > startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
            }
            if (0 > length)
            {
                throw new ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
            }

            int service_idColumnIndex       = reader.GetOrdinal("service_id");
            int pinColumnIndex              = reader.GetOrdinal("pin");
            int retail_acct_idColumnIndex   = reader.GetOrdinal("retail_acct_id");
            int serial_numberColumnIndex    = reader.GetOrdinal("serial_number");
            int statusColumnIndex           = reader.GetOrdinal("status");
            int inventory_statusColumnIndex = reader.GetOrdinal("inventory_status");
            int date_loadedColumnIndex      = reader.GetOrdinal("date_loaded");
            int date_to_expireColumnIndex   = reader.GetOrdinal("date_to_expire");
            int date_activeColumnIndex      = reader.GetOrdinal("date_active");
            int date_first_usedColumnIndex  = reader.GetOrdinal("date_first_used");
            int date_last_usedColumnIndex   = reader.GetOrdinal("date_last_used");
            int date_deactivatedColumnIndex = reader.GetOrdinal("date_deactivated");
            int date_archivedColumnIndex    = reader.GetOrdinal("date_archived");

            System.Collections.ArrayList recordList = new System.Collections.ArrayList();
            int ri = -startIndex;

            while (reader.Read())
            {
                ri++;
                if (ri > 0 && ri <= length)
                {
                    PhoneCardRow record = new PhoneCardRow();
                    recordList.Add(record);

                    record.Service_id       = Convert.ToInt16(reader.GetValue(service_idColumnIndex));
                    record.Pin              = Convert.ToInt64(reader.GetValue(pinColumnIndex));
                    record.Retail_acct_id   = Convert.ToInt32(reader.GetValue(retail_acct_idColumnIndex));
                    record.Serial_number    = Convert.ToInt64(reader.GetValue(serial_numberColumnIndex));
                    record.Status           = Convert.ToByte(reader.GetValue(statusColumnIndex));
                    record.Inventory_status = Convert.ToByte(reader.GetValue(inventory_statusColumnIndex));
                    record.Date_loaded      = Convert.ToDateTime(reader.GetValue(date_loadedColumnIndex));
                    record.Date_to_expire   = Convert.ToDateTime(reader.GetValue(date_to_expireColumnIndex));
                    if (!reader.IsDBNull(date_activeColumnIndex))
                    {
                        record.Date_active = Convert.ToDateTime(reader.GetValue(date_activeColumnIndex));
                    }
                    if (!reader.IsDBNull(date_first_usedColumnIndex))
                    {
                        record.Date_first_used = Convert.ToDateTime(reader.GetValue(date_first_usedColumnIndex));
                    }
                    if (!reader.IsDBNull(date_last_usedColumnIndex))
                    {
                        record.Date_last_used = Convert.ToDateTime(reader.GetValue(date_last_usedColumnIndex));
                    }
                    if (!reader.IsDBNull(date_deactivatedColumnIndex))
                    {
                        record.Date_deactivated = Convert.ToDateTime(reader.GetValue(date_deactivatedColumnIndex));
                    }
                    if (!reader.IsDBNull(date_archivedColumnIndex))
                    {
                        record.Date_archived = Convert.ToDateTime(reader.GetValue(date_archivedColumnIndex));
                    }

                    if (ri == length && 0 != totalRecordCount)
                    {
                        break;
                    }
                }
            }

            totalRecordCount = 0 == totalRecordCount ? ri + startIndex : -1;
            return((PhoneCardRow[])(recordList.ToArray(typeof(PhoneCardRow))));
        }
        /// <summary>
        /// Reads data from the provided data reader and returns
        /// an array of mapped objects.
        /// </summary>
        /// <param name="reader">The <see cref="System.Data.IDataReader"/> object to read data from the table.</param>
        /// <param name="startIndex">The index of the first record to map.</param>
        /// <param name="length">The number of records to map.</param>
        /// <param name="totalRecordCount">A reference parameter that returns the total number
        /// of records in the reader object if 0 was passed into the method; otherwise it returns -1.</param>
        /// <returns>An array of <see cref="RetailRateHistoryRow"/> objects.</returns>
        protected virtual RetailRateHistoryRow[] MapRecords(IDataReader reader,
                                                            int startIndex, int length, ref int totalRecordCount)
        {
            if (0 > startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
            }
            if (0 > length)
            {
                throw new ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
            }

            int retail_route_idColumnIndex              = reader.GetOrdinal("retail_route_id");
            int date_onColumnIndex                      = reader.GetOrdinal("date_on");
            int date_offColumnIndex                     = reader.GetOrdinal("date_off");
            int rate_info_idColumnIndex                 = reader.GetOrdinal("rate_info_id");
            int connect_feeColumnIndex                  = reader.GetOrdinal("connect_fee");
            int disconnect_feeColumnIndex               = reader.GetOrdinal("disconnect_fee");
            int per_call_costColumnIndex                = reader.GetOrdinal("per_call_cost");
            int cost_increase_per_callColumnIndex       = reader.GetOrdinal("cost_increase_per_call");
            int cost_increase_per_call_startColumnIndex = reader.GetOrdinal("cost_increase_per_call_start");
            int cost_increase_per_call_stopColumnIndex  = reader.GetOrdinal("cost_increase_per_call_stop");
            int tax_first_incr_costColumnIndex          = reader.GetOrdinal("tax_first_incr_cost");
            int tax_add_incr_costColumnIndex            = reader.GetOrdinal("tax_add_incr_cost");
            int surcharge_delayColumnIndex              = reader.GetOrdinal("surcharge_delay");
            int rating_delayColumnIndex                 = reader.GetOrdinal("rating_delay");

            System.Collections.ArrayList recordList = new System.Collections.ArrayList();
            int ri = -startIndex;

            while (reader.Read())
            {
                ri++;
                if (ri > 0 && ri <= length)
                {
                    RetailRateHistoryRow record = new RetailRateHistoryRow();
                    recordList.Add(record);

                    record.Retail_route_id              = Convert.ToInt32(reader.GetValue(retail_route_idColumnIndex));
                    record.Date_on                      = Convert.ToDateTime(reader.GetValue(date_onColumnIndex));
                    record.Date_off                     = Convert.ToDateTime(reader.GetValue(date_offColumnIndex));
                    record.Rate_info_id                 = Convert.ToInt32(reader.GetValue(rate_info_idColumnIndex));
                    record.Connect_fee                  = Convert.ToDecimal(reader.GetValue(connect_feeColumnIndex));
                    record.Disconnect_fee               = Convert.ToDecimal(reader.GetValue(disconnect_feeColumnIndex));
                    record.Per_call_cost                = Convert.ToDecimal(reader.GetValue(per_call_costColumnIndex));
                    record.Cost_increase_per_call       = Convert.ToInt32(reader.GetValue(cost_increase_per_callColumnIndex));
                    record.Cost_increase_per_call_start = Convert.ToInt32(reader.GetValue(cost_increase_per_call_startColumnIndex));
                    record.Cost_increase_per_call_stop  = Convert.ToInt32(reader.GetValue(cost_increase_per_call_stopColumnIndex));
                    record.Tax_first_incr_cost          = Convert.ToDecimal(reader.GetValue(tax_first_incr_costColumnIndex));
                    record.Tax_add_incr_cost            = Convert.ToDecimal(reader.GetValue(tax_add_incr_costColumnIndex));
                    record.Surcharge_delay              = Convert.ToByte(reader.GetValue(surcharge_delayColumnIndex));
                    record.Rating_delay                 = Convert.ToByte(reader.GetValue(rating_delayColumnIndex));

                    if (ri == length && 0 != totalRecordCount)
                    {
                        break;
                    }
                }
            }

            totalRecordCount = 0 == totalRecordCount ? ri + startIndex : -1;
            return((RetailRateHistoryRow[])(recordList.ToArray(typeof(RetailRateHistoryRow))));
        }
        public virtual void  TestMissingTerms()
        {
            System.String    fieldName = "field1";
            MockRAMDirectory rd        = new MockRAMDirectory();
            IndexWriter      w         = new IndexWriter(rd, new KeywordAnalyzer(), MaxFieldLength.UNLIMITED);

            for (int i = 0; i < 100; i++)
            {
                Document doc  = new Document();
                int      term = i * 10; //terms are units of 10;
                doc.Add(new Field(fieldName, "" + term, Field.Store.YES, Field.Index.NOT_ANALYZED));
                w.AddDocument(doc);
            }
            w.Close();

            IndexReader   reader   = IndexReader.Open(rd, true);
            IndexSearcher searcher = new IndexSearcher(reader);
            int           numDocs  = reader.NumDocs();

            ScoreDoc[]        results;
            MatchAllDocsQuery q = new MatchAllDocsQuery();

            System.Collections.ArrayList terms = new System.Collections.ArrayList();
            terms.Add("5");
            results = searcher.Search(q, new FieldCacheTermsFilter(fieldName, (System.String[])terms.ToArray(typeof(System.String))), numDocs).ScoreDocs;
            Assert.AreEqual(0, results.Length, "Must match nothing");

            terms = new System.Collections.ArrayList();
            terms.Add("10");
            results = searcher.Search(q, new FieldCacheTermsFilter(fieldName, (System.String[])terms.ToArray(typeof(System.String))), numDocs).ScoreDocs;
            Assert.AreEqual(1, results.Length, "Must match 1");

            terms = new System.Collections.ArrayList();
            terms.Add("10");
            terms.Add("20");
            results = searcher.Search(q, new FieldCacheTermsFilter(fieldName, (System.String[])terms.ToArray(typeof(System.String))), numDocs).ScoreDocs;
            Assert.AreEqual(2, results.Length, "Must match 2");

            reader.Close();
            rd.Close();
        }
Example #41
0
        /// <summary>
        /// Returns an array of arguments to be sent to the Ghostscript API
        /// </summary>
        /// <param name="inputPath">Path to the source file</param>
        /// <param name="outputPath">Path to the output file</param>
        /// <param name="settings">API parameters</param>
        /// <returns>API arguments</returns>
        private static string[] GetArgs(string inputPath,
                                        string outputPath,
                                        GhostscriptSettings settings)
        {
            System.Collections.ArrayList args = new System.Collections.ArrayList(ARGS);

            if (settings.Device == Settings.GhostscriptDevices.UNDEFINED)
            {
                throw new ArgumentException("An output device must be defined for Ghostscript", "GhostscriptSettings.Device");
            }

            if (settings.Page.AllPages == false && (settings.Page.Start <= 0 && settings.Page.End < settings.Page.Start))
            {
                throw new ArgumentException("Pages to be printed must be defined.", "GhostscriptSettings.Pages");
            }

            if (settings.Resolution.IsEmpty)
            {
                throw new ArgumentException("An output resolution must be defined", "GhostscriptSettings.Resolution");
            }

            if (settings.Size.Native == Settings.GhostscriptPageSizes.UNDEFINED && settings.Size.Manual.IsEmpty)
            {
                throw new ArgumentException("Page size must be defined", "GhostscriptSettings.Size");
            }

            // Output device
            args.Add(String.Format("-sDEVICE={0}", settings.Device));

            // Pages to output
            if (settings.Page.AllPages)
            {
                args.Add("-dFirstPage=1");
            }
            else
            {
                args.Add(String.Format("-dFirstPage={0}", settings.Page.Start));
                if (settings.Page.End >= settings.Page.Start)
                {
                    args.Add(String.Format("-dLastPage={0}", settings.Page.End));
                }
            }

            // Page size
            if (settings.Size.Native == Settings.GhostscriptPageSizes.UNDEFINED)
            {
                args.Add(String.Format("-dDEVICEWIDTHPOINTS={0}", settings.Size.Manual.Width));
                args.Add(String.Format("-dDEVICEHEIGHTPOINTS={0}", settings.Size.Manual.Height));
            }
            else
            {
                args.Add(String.Format("-sPAPERSIZE={0}", settings.Size.Native.ToString()));
            }

            // Page resolution
            args.Add(String.Format("-dDEVICEXRESOLUTION={0}", settings.Resolution.Width));
            args.Add(String.Format("-dDEVICEYRESOLUTION={0}", settings.Resolution.Height));

            // Files
            args.Add(String.Format("-sOutputFile={0}", outputPath));
            args.Add(inputPath);

            return((string[])args.ToArray(typeof(string)));
        }
        /// <summary>
        /// Reads data from the provided data reader and returns
        /// an array of mapped objects.
        /// </summary>
        /// <param name="reader">The <see cref="System.Data.IDataReader"/> object to read data from the table.</param>
        /// <param name="startIndex">The index of the first record to map.</param>
        /// <param name="length">The number of records to map.</param>
        /// <param name="totalRecordCount">A reference parameter that returns the total number
        /// of records in the reader object if 0 was passed into the method; otherwise it returns -1.</param>
        /// <returns>An array of <see cref="lkpCandidateRow"/> objects.</returns>
        protected virtual lkpCandidateRow[] MapRecords(IDataReader reader,
                                                       int startIndex, int length, ref int totalRecordCount)
        {
            if (0 > startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
            }
            if (0 > length)
            {
                throw new ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
            }

            int cand_IDColumnIndex    = reader.GetOrdinal("Cand_ID");
            int cand_NoColumnIndex    = reader.GetOrdinal("Cand_No");
            int cand_NameColumnIndex  = reader.GetOrdinal("Cand_Name");
            int cand_FNameColumnIndex = reader.GetOrdinal("Cand_FName");
            int genderIDColumnIndex   = reader.GetOrdinal("GenderID");
            int prov_IDColumnIndex    = reader.GetOrdinal("Prov_ID");
            int isDeletedColumnIndex  = reader.GetOrdinal("IsDeleted");

            System.Collections.ArrayList recordList = new System.Collections.ArrayList();
            int ri = -startIndex;

            while (reader.Read())
            {
                ri++;
                if (ri > 0 && ri <= length)
                {
                    lkpCandidateRow record = new lkpCandidateRow();
                    recordList.Add(record);

                    record.Cand_ID = Convert.ToInt32(reader.GetValue(cand_IDColumnIndex));
                    if (!reader.IsDBNull(cand_NoColumnIndex))
                    {
                        record.Cand_No = Convert.ToString(reader.GetValue(cand_NoColumnIndex));
                    }
                    if (!reader.IsDBNull(cand_NameColumnIndex))
                    {
                        record.Cand_Name = Convert.ToString(reader.GetValue(cand_NameColumnIndex));
                    }
                    if (!reader.IsDBNull(cand_FNameColumnIndex))
                    {
                        record.Cand_FName = Convert.ToString(reader.GetValue(cand_FNameColumnIndex));
                    }
                    if (!reader.IsDBNull(genderIDColumnIndex))
                    {
                        record.GenderID = Convert.ToInt32(reader.GetValue(genderIDColumnIndex));
                    }
                    if (!reader.IsDBNull(prov_IDColumnIndex))
                    {
                        record.Prov_ID = Convert.ToInt32(reader.GetValue(prov_IDColumnIndex));
                    }
                    if (!reader.IsDBNull(isDeletedColumnIndex))
                    {
                        record.IsDeleted = Convert.ToBoolean(reader.GetValue(isDeletedColumnIndex));
                    }

                    if (ri == length && 0 != totalRecordCount)
                    {
                        break;
                    }
                }
            }

            totalRecordCount = 0 == totalRecordCount ? ri + startIndex : -1;
            return((lkpCandidateRow[])(recordList.ToArray(typeof(lkpCandidateRow))));
        }
 private static System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> GetUserLatestPostsFromResult(System.Collections.ArrayList result)
 {
     System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> list = new System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>();
     try
     {
         try
         {
             System.Collections.IEnumerator enumerator = result.GetEnumerator();
             while (enumerator.MoveNext())
             {
                 object objectValue = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(enumerator.Current);
                 System.Collections.Generic.Dictionary<string, string> dictionary = new System.Collections.Generic.Dictionary<string, string>();
                 dictionary.Add("id", "");
                 dictionary.Add("link", "");
                 dictionary.Add("thumbnail-image", "");
                 dictionary.Add("lowres-image", "");
                 dictionary.Add("highres-image", "");
                 dictionary.Add("lowres-video", "");
                 dictionary.Add("highres-video", "");
                 dictionary.Add("description", "");
                 dictionary.Add("description-notags", "");
                 dictionary.Add("tags", "");
                 dictionary.Add("latitude", "");
                 dictionary.Add("longitude", "");
                 dictionary.Add("location", "");
                 if (Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "id"
                 }, null, null, null)))
                 {
                     dictionary["id"] = Conversions.ToString(NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "id"
                     }, null));
                 }
                 if (Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "link"
                 }, null, null, null)))
                 {
                     dictionary["link"] = Conversions.ToString(NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "link"
                     }, null));
                 }
                 if (Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "videos"
                 }, null, null, null)))
                 {
                     dictionary.Add("video", "");
                     System.Collections.Generic.Dictionary<string, object> dictionary2 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "videos"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator2 = dictionary2.GetEnumerator();
                         while (enumerator2.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current = enumerator2.Current;
                             string key = current.Key;
                             if (Operators.CompareString(key, "low_bandwidth", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary3 = (System.Collections.Generic.Dictionary<string, object>)current.Value;
                                 dictionary["lowres-video"] = Conversions.ToString(dictionary3["url"]);
                             }
                             else if (Operators.CompareString(key, "standard_resolution", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary4 = (System.Collections.Generic.Dictionary<string, object>)current.Value;
                                 dictionary["highres-video"] = Conversions.ToString(dictionary4["url"]);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator2;
                         ((System.IDisposable)enumerator2).Dispose();
                     }
                 }
                 if (Conversions.ToBoolean((!Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "location"
                 }, null, null, null)) || !Conversions.ToBoolean(NewLateBinding.LateIndexGet(objectValue, new object[]
                 {
                         "location"
                 }, null) != null)) ? false : true))
                 {
                     System.Collections.Generic.Dictionary<string, object> dictionary5 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "location"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator3 = dictionary5.GetEnumerator();
                         while (enumerator3.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current2 = enumerator3.Current;
                             string key2 = current2.Key;
                             if (Operators.CompareString(key2, "latitude", false) == 0)
                             {
                                 dictionary["latitude"] = Conversions.ToString(current2.Value);
                             }
                             else if (Operators.CompareString(key2, "longitude", false) == 0)
                             {
                                 dictionary["longitude"] = Conversions.ToString(current2.Value);
                             }
                             else if (Operators.CompareString(key2, "name", false) == 0)
                             {
                                 dictionary["location"] = Conversions.ToString(current2.Value);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator3;
                         ((System.IDisposable)enumerator3).Dispose();
                     }
                 }
                 if (NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "images"
                 }, null, null, null) != null)
                 {
                     System.Collections.Generic.Dictionary<string, object> dictionary6 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "images"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator4 = dictionary6.GetEnumerator();
                         while (enumerator4.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current3 = enumerator4.Current;
                             string key3 = current3.Key;
                             if (Operators.CompareString(key3, "thumbnail", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary7 = (System.Collections.Generic.Dictionary<string, object>)current3.Value;
                                 dictionary["thumbnail-image"] = Conversions.ToString(dictionary7["url"]);
                             }
                             else if (Operators.CompareString(key3, "low_resolution", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary8 = (System.Collections.Generic.Dictionary<string, object>)current3.Value;
                                 dictionary["lowres-image"] = Conversions.ToString(dictionary8["url"]);
                             }
                             else if (Operators.CompareString(key3, "standard_resolution", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary9 = (System.Collections.Generic.Dictionary<string, object>)current3.Value;
                                 dictionary["highres-image"] = Conversions.ToString(dictionary9["url"]);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator4;
                         ((System.IDisposable)enumerator4).Dispose();
                     }
                 }
                 if (NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "caption"
                 }, null, null, null) != null)
                 {
                     System.Collections.Generic.Dictionary<string, object> dictionary10 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "caption"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator5 = dictionary10.GetEnumerator();
                         while (enumerator5.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current4 = enumerator5.Current;
                             string key4 = current4.Key;
                             if (Operators.CompareString(key4, "text", false) == 0)
                             {
                                 dictionary["description"] = Conversions.ToString(current4.Value);
                                 dictionary["description-notags"] = Conversions.ToString(current4.Value);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator5;
                         ((System.IDisposable)enumerator5).Dispose();
                     }
                 }
                 if (NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "tags"
                 }, null, null, null) != null)
                 {
                     System.Collections.ArrayList arrayList = (System.Collections.ArrayList)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "tags"
                     }, null);
                     bool flag = false;
                     try
                     {
                         System.Collections.Generic.IEnumerator<object> enumerator6 = (from f in arrayList.ToArray().ToList<object>()
                                                                                       orderby f.ToString().Length descending
                                                                                       select f).GetEnumerator();
                         while (enumerator6.MoveNext())
                         {
                             object objectValue2 = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(enumerator6.Current);
                             dictionary["tags"] = Conversions.ToString(Operators.AddObject(Operators.AddObject(dictionary["tags"] + "#", objectValue2), ","));
                             dictionary["description-notags"] = dictionary["description-notags"].Replace(Conversions.ToString(Operators.AddObject(" #", objectValue2)), "", System.StringComparison.OrdinalIgnoreCase);
                             flag = true;
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.IEnumerator<object> enumerator6;
                         if (enumerator6 != null)
                         {
                             enumerator6.Dispose();
                         }
                     }
                     if (flag)
                     {
                         dictionary["tags"] = dictionary["tags"].Substring(0, checked(dictionary["tags"].Length - 1));
                     }
                 }
                 list.Add(dictionary);
             }
         }
         finally
         {
             System.Collections.IEnumerator enumerator;
             if (enumerator is System.IDisposable)
             {
                 (enumerator as System.IDisposable).Dispose();
             }
         }
     }
     catch (System.Exception expr_743)
     {
         ProjectData.SetProjectError(expr_743);
         ProjectData.ClearProjectError();
     }
     return list;
 }
Example #44
0
        /// <summary>
        /// Reads data from the provided data reader and returns
        /// an array of mapped objects.
        /// </summary>
        /// <param name="reader">The <see cref="System.Data.SqlDataReader"/> object to read data from the table.</param>
        /// <param name="startIndex">The index of the first record to map.</param>
        /// <param name="length">The number of records to map.</param>
        /// <param name="totalRecordCount">A reference parameter that returns the total number
        /// of records in the reader object if 0 was passed into the method; otherwise it returns -1.</param>
        /// <returns>An array of <see cref="PatientInfoRow"/> objects.</returns>
        protected virtual PatientInfoRow[] MapRecords(SqlDataReader reader,
                                                      int startIndex, int length, ref int totalRecordCount)
        {
            if (0 > startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
            }
            if (0 > length)
            {
                throw new ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
            }

            int idColumnIndex                 = reader.GetOrdinal("Id");
            int nameColumnIndex               = reader.GetOrdinal("Name");
            int addressColumnIndex            = reader.GetOrdinal("Address");
            int dateOfBirthColumnIndex        = reader.GetOrdinal("DateOfBirth");
            int phoneColumnIndex              = reader.GetOrdinal("Phone");
            int emergencyContactColumnIndex   = reader.GetOrdinal("EmergencyContact");
            int dateOfRegistrationColumnIndex = reader.GetOrdinal("DateOfRegistration");

            System.Collections.ArrayList recordList = new System.Collections.ArrayList();
            int ri = -startIndex;

            while (reader.Read())
            {
                ri++;
                if (ri > 0 && ri <= length)
                {
                    PatientInfoRow record = new PatientInfoRow();
                    recordList.Add(record);

                    record.Id = Convert.ToInt32(reader.GetValue(idColumnIndex));
                    if (!reader.IsDBNull(nameColumnIndex))
                    {
                        record.Name = Convert.ToString(reader.GetValue(nameColumnIndex));
                    }
                    if (!reader.IsDBNull(addressColumnIndex))
                    {
                        record.Address = Convert.ToString(reader.GetValue(addressColumnIndex));
                    }
                    if (!reader.IsDBNull(dateOfBirthColumnIndex))
                    {
                        record.DateOfBirth = Convert.ToDateTime(reader.GetValue(dateOfBirthColumnIndex));
                    }
                    if (!reader.IsDBNull(phoneColumnIndex))
                    {
                        record.Phone = Convert.ToInt32(reader.GetValue(phoneColumnIndex));
                    }
                    if (!reader.IsDBNull(emergencyContactColumnIndex))
                    {
                        record.EmergencyContact = Convert.ToInt32(reader.GetValue(emergencyContactColumnIndex));
                    }
                    if (!reader.IsDBNull(dateOfRegistrationColumnIndex))
                    {
                        record.DateOfRegistration = Convert.ToDateTime(reader.GetValue(dateOfRegistrationColumnIndex));
                    }

                    if (ri == length && 0 != totalRecordCount)
                    {
                        break;
                    }
                }
            }

            totalRecordCount = 0 == totalRecordCount ? ri + startIndex : -1;
            return((PatientInfoRow[])(recordList.ToArray(typeof(PatientInfoRow))));
        }
Example #45
0
 public void RandNum()
 {
     // 存入亂數
     System.Collections.ArrayList rnd = MakeRand();
     ans = (int[])rnd.ToArray(typeof(int));
 }
Example #46
0
 /// <summary>Returns the set of clauses in this query. </summary>
 public virtual BooleanClause[] GetClauses()
 {
     return((BooleanClause[])clauses.ToArray(typeof(BooleanClause)));
 }
Example #47
0
        private void ReadContext_引数リスト角()
        {
            string word;

                #pragma warning disable 164
label_0:
                #pragma warning restore 164
            word = this.wreader.CurrentWord;
            {
                this.stack.Push(this.OpenMarker);
            }
                #pragma warning disable 164
label_1:
                #pragma warning restore 164
            word = this.wreader.CurrentWord;
            if ((word == ")"))
            {
                this.wreader.ReadNext();
                System.Collections.ArrayList list = new System.Collections.ArrayList();
                while (this.stack.Count > 0)
                {
                    object v = this.stack.Pop();
                    if (v == this.OpenMarker)
                    {
                        break;
                    }
                    list.Add(this.stack.Pop());
                }
                list.Reverse();
                this.stack.Push(list.ToArray());
                return;
            }
            else
            {
                this.ReadContext_E1();
            }
                #pragma warning disable 164
label_2:
                #pragma warning restore 164
            word = this.wreader.CurrentWord;
            if ((word == ")"))
            {
                this.wreader.ReadNext();
                System.Collections.ArrayList list = new System.Collections.ArrayList();
                while (this.stack.Count > 0)
                {
                    object v = this.stack.Pop();
                    if (v == this.OpenMarker)
                    {
                        break;
                    }
                    list.Add(this.stack.Pop());
                }
                list.Reverse();
                this.stack.Push(list.ToArray());
                return;
            }
            else if ((word == ","))
            {
                this.wreader.ReadNext();
            }
            else
            {
                this.wreader.LetterReader.SetError("解析中の不明なエラー", 0, null);
            }
                #pragma warning disable 164
label_3:
                #pragma warning restore 164
            word = this.wreader.CurrentWord;
            if ((word == ")") || (word == ","))
            {
                this.wreader.LetterReader.SetError("エラー: \"',' に続く引数がありません。\"", 0, null);
            }
            else
            {
                this.ReadContext_E1();
                goto label_2;
            }
        }
        /// <summary>
        /// Reads data from the provided data reader and returns
        /// an array of mapped objects.
        /// </summary>
        /// <param name="reader">The <see cref="System.Data.IDataReader"/> object to read data from the view.</param>
        /// <param name="startIndex">The index of the first record to map.</param>
        /// <param name="length">The number of records to map.</param>
        /// <param name="totalRecordCount">A reference parameter that returns the total number
        /// of records in the reader object if 0 was passed into the method; otherwise it returns -1.</param>
        /// <returns>An array of <see cref="IPAddressViewRow"/> objects.</returns>
        protected virtual IPAddressViewRow[] MapRecords(IDataReader reader,
                                                        int startIndex, int length, ref int totalRecordCount)
        {
            if (0 > startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", startIndex, "StartIndex cannot be less than zero.");
            }
            if (0 > length)
            {
                throw new ArgumentOutOfRangeException("length", length, "Length cannot be less than zero.");
            }

            int iP_addressColumnIndex                = reader.GetOrdinal("IP_address");
            int dot_IP_addressColumnIndex            = reader.GetOrdinal("dot_IP_address");
            int end_point_idColumnIndex              = reader.GetOrdinal("end_point_id");
            int aliasColumnIndex                     = reader.GetOrdinal("alias");
            int with_alias_authenticationColumnIndex = reader.GetOrdinal("with_alias_authentication");
            int statusColumnIndex                    = reader.GetOrdinal("status");
            int typeColumnIndex              = reader.GetOrdinal("type");
            int protocolColumnIndex          = reader.GetOrdinal("protocol");
            int portColumnIndex              = reader.GetOrdinal("port");
            int registrationColumnIndex      = reader.GetOrdinal("registration");
            int is_registeredColumnIndex     = reader.GetOrdinal("is_registered");
            int iP_address_rangeColumnIndex  = reader.GetOrdinal("IP_address_range");
            int max_callsColumnIndex         = reader.GetOrdinal("max_calls");
            int passwordColumnIndex          = reader.GetOrdinal("password");
            int prefix_in_type_idColumnIndex = reader.GetOrdinal("prefix_in_type_id");
            int prefix_type_descrColumnIndex = reader.GetOrdinal("prefix_type_descr");
            int prefix_lengthColumnIndex     = reader.GetOrdinal("prefix_length");
            int prefix_delimiterColumnIndex  = reader.GetOrdinal("prefix_delimiter");

            System.Collections.ArrayList recordList = new System.Collections.ArrayList();
            int ri = -startIndex;

            while (reader.Read())
            {
                ri++;
                if (ri > 0 && ri <= length)
                {
                    IPAddressViewRow record = new IPAddressViewRow();
                    recordList.Add(record);

                    record.IP_address = Convert.ToInt32(reader.GetValue(iP_addressColumnIndex));
                    if (!reader.IsDBNull(dot_IP_addressColumnIndex))
                    {
                        record.Dot_IP_address = Convert.ToString(reader.GetValue(dot_IP_addressColumnIndex));
                    }
                    record.End_point_id = Convert.ToInt16(reader.GetValue(end_point_idColumnIndex));
                    record.Alias        = Convert.ToString(reader.GetValue(aliasColumnIndex));
                    record.With_alias_authentication = Convert.ToByte(reader.GetValue(with_alias_authenticationColumnIndex));
                    record.Status            = Convert.ToByte(reader.GetValue(statusColumnIndex));
                    record.Type              = Convert.ToByte(reader.GetValue(typeColumnIndex));
                    record.Protocol          = Convert.ToByte(reader.GetValue(protocolColumnIndex));
                    record.Port              = Convert.ToInt32(reader.GetValue(portColumnIndex));
                    record.Registration      = Convert.ToByte(reader.GetValue(registrationColumnIndex));
                    record.Is_registered     = Convert.ToByte(reader.GetValue(is_registeredColumnIndex));
                    record.IP_address_range  = Convert.ToString(reader.GetValue(iP_address_rangeColumnIndex));
                    record.Max_calls         = Convert.ToInt32(reader.GetValue(max_callsColumnIndex));
                    record.Password          = Convert.ToString(reader.GetValue(passwordColumnIndex));
                    record.Prefix_in_type_id = Convert.ToInt16(reader.GetValue(prefix_in_type_idColumnIndex));
                    record.Prefix_type_descr = Convert.ToString(reader.GetValue(prefix_type_descrColumnIndex));
                    record.Prefix_length     = Convert.ToByte(reader.GetValue(prefix_lengthColumnIndex));
                    record.Prefix_delimiter  = Convert.ToByte(reader.GetValue(prefix_delimiterColumnIndex));

                    if (ri == length && 0 != totalRecordCount)
                    {
                        break;
                    }
                }
            }

            totalRecordCount = 0 == totalRecordCount ? ri + startIndex : -1;
            return((IPAddressViewRow[])(recordList.ToArray(typeof(IPAddressViewRow))));
        }
Example #49
0
        private void CommitEntry()
        {
            PropertyCollection properties = GetProperties(false);

            if (!Nflag)
            {
                System.Collections.ArrayList modList = new System.Collections.ArrayList();
                foreach (string attribute in properties.PropertyNames)
                {
                    LdapAttribute attr = null;
                    if (properties [attribute].Mbit)
                    {
                        switch (properties [attribute].Count)
                        {
                        case 0:
                            attr = new LdapAttribute(attribute, new string [0]);
                            modList.Add(new LdapModification(LdapModification.DELETE, attr));
                            break;

                        case 1:
                            string val = (string)properties [attribute].Value;
                            attr = new LdapAttribute(attribute, val);
                            modList.Add(new LdapModification(LdapModification.REPLACE, attr));
                            break;

                        default:
                            object [] vals     = (object [])properties [attribute].Value;
                            string [] aStrVals = new string [properties [attribute].Count];
                            Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count);
                            attr = new LdapAttribute(attribute, aStrVals);
                            modList.Add(new LdapModification(LdapModification.REPLACE, attr));
                            break;
                        }
                        properties [attribute].Mbit = false;
                    }
                }
                if (modList.Count > 0)
                {
                    LdapModification[] mods = new LdapModification[modList.Count];
                    Type mtype = typeof(LdapModification);
                    mods = (LdapModification[])modList.ToArray(mtype);
                    ModEntry(mods);
                }
            }
            else
            {
                LdapAttributeSet attributeSet = new LdapAttributeSet();
                foreach (string attribute in properties.PropertyNames)
                {
                    if (properties [attribute].Count == 1)
                    {
                        string val = (string)properties [attribute].Value;
                        attributeSet.Add(new LdapAttribute(attribute, val));
                    }
                    else
                    {
                        object[] vals     = (object [])properties [attribute].Value;
                        string[] aStrVals = new string [properties [attribute].Count];
                        Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count);
                        attributeSet.Add(new LdapAttribute(attribute, aStrVals));
                    }
                }
                LdapEntry newEntry = new LdapEntry(Fdn, attributeSet);
                conn.Add(newEntry);
                Nflag = false;
            }
        }
Example #50
0
        public static bool FindDeviceFromGuid(System.Guid myGuid, out string[] devicePathName)
        {
            // Purpose    : Uses SetupDi API functions to retrieve the device path name of an
            //            : attached device that belongs to an interface class.
            // Accepts    : myGuid - an interface class GUID.
            //            : devicePathName - a pointer to an array of strings that will contain
            //            : the device path names of attached devices.
            // Returns    : True if at least one device is found, False if not.

            System.Collections.ArrayList DevicePaths = new System.Collections.ArrayList();
            bool DeviceFound = false;

            try
            {
                IntPtr DeviceInfoSet =
                    setupapi.SetupDiGetClassDevs(
                        ref myGuid,
                        null,
                        IntPtr.Zero,
                        (int)(setupapi.DIGF.PRESENT | setupapi.DIGF.DEVICEINTERFACE));

                Debug.WriteLine(Debugging.ResultOfAPICall("SetupDiClassDevs"));

                // The cbSize element of the MyDeviceInterfaceData structure must be set to
                // the structure's size in bytes. The size is 28 bytes.
                setupapi.SP_DEVICE_INTERFACE_DATA MyDeviceInterfaceData = new setupapi.SP_DEVICE_INTERFACE_DATA();
                MyDeviceInterfaceData.cbSize = Marshal.SizeOf(MyDeviceInterfaceData);

                while (setupapi.SetupDiEnumDeviceInterfaces(
                           DeviceInfoSet,
                           0,
                           ref myGuid,
                           (uint)DevicePaths.Count,
                           ref MyDeviceInterfaceData))
                {
                    Debug.WriteLine(Debugging.ResultOfAPICall("SetupDiEnumDeviceInterfaces"));
                    uint BufferSize = 0;

                    bool Success = setupapi.SetupDiGetDeviceInterfaceDetail(
                        DeviceInfoSet,
                        ref MyDeviceInterfaceData,
                        IntPtr.Zero, 0, ref BufferSize, IntPtr.Zero);

                    // Store the structure's size.
                    byte[] TempPath = new byte[BufferSize + 4 + 2];
                    BitConverter.GetBytes((int)5).CopyTo(TempPath, 0);
                    // Call SetupDiGetDeviceInterfaceDetail again.
                    // This time, pass a pointer to DetailDataBuffer

                    Success = setupapi.SetupDiGetDeviceInterfaceDetail(
                        DeviceInfoSet,
                        ref MyDeviceInterfaceData,
                        TempPath,
                        BufferSize,
                        ref BufferSize,
                        IntPtr.Zero);
                    Debug.WriteLine(Debugging.ResultOfAPICall("SetupDiGetDeviceInterfaceDetail"));

                    char[] TempChar = new char[BufferSize];
                    Array.Copy(TempPath, 3, TempChar, 0, BufferSize);
                    string SingledevicePathName = new string(TempChar);
                    DevicePaths.Add(SingledevicePathName);
                    DeviceFound = true;
                }

                setupapi.SetupDiDestroyDeviceInfoList(DeviceInfoSet);
                Debug.WriteLine(Debugging.ResultOfAPICall("SetupDiDestroyDeviceInfoList"));
            }
            catch (Exception ex)
            {
                HandleException(ModuleName + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
            }

            devicePathName = (string[])DevicePaths.ToArray(typeof(string));

            return(DeviceFound);
        }
Example #51
0
		/// <exception cref="ParseException">throw in overridden method to disallow
		/// </exception>
		public /*protected internal*/ virtual Query GetFieldQuery(System.String field, System.String queryText)
		{
			// Use the analyzer to get all the tokens, and then build a TermQuery,
			// PhraseQuery, or nothing based on the term count
			
			TokenStream source;
			try
			{
				source = analyzer.ReusableTokenStream(field, new System.IO.StringReader(queryText));
				source.Reset();
			}
			catch (System.IO.IOException e)
			{
				source = analyzer.TokenStream(field, new System.IO.StringReader(queryText));
			}
			CachingTokenFilter buffer = new CachingTokenFilter(source);
			TermAttribute termAtt = null;
			PositionIncrementAttribute posIncrAtt = null;
			int numTokens = 0;
			
			bool success = false;
			try
			{
				buffer.Reset();
				success = true;
			}
			catch (System.IO.IOException e)
			{
				// success==false if we hit an exception
			}
			if (success)
			{
				if (buffer.HasAttribute(typeof(TermAttribute)))
				{
					termAtt = (TermAttribute) buffer.GetAttribute(typeof(TermAttribute));
				}
				if (buffer.HasAttribute(typeof(PositionIncrementAttribute)))
				{
					posIncrAtt = (PositionIncrementAttribute) buffer.GetAttribute(typeof(PositionIncrementAttribute));
				}
			}
			
			int positionCount = 0;
			bool severalTokensAtSamePosition = false;
			
			bool hasMoreTokens = false;
			if (termAtt != null)
			{
				try
				{
					hasMoreTokens = buffer.IncrementToken();
					while (hasMoreTokens)
					{
						numTokens++;
						int positionIncrement = (posIncrAtt != null)?posIncrAtt.GetPositionIncrement():1;
						if (positionIncrement != 0)
						{
							positionCount += positionIncrement;
						}
						else
						{
							severalTokensAtSamePosition = true;
						}
						hasMoreTokens = buffer.IncrementToken();
					}
				}
				catch (System.IO.IOException e)
				{
					// ignore
				}
			}
			try
			{
				// rewind the buffer stream
				buffer.Reset();
				
				// close original stream - all tokens buffered
				source.Close();
			}
			catch (System.IO.IOException e)
			{
				// ignore
			}
			
			if (numTokens == 0)
				return null;
			else if (numTokens == 1)
			{
				System.String term = null;
				try
				{
					bool hasNext = buffer.IncrementToken();
					System.Diagnostics.Debug.Assert(hasNext == true);
					term = termAtt.Term();
				}
				catch (System.IO.IOException e)
				{
					// safe to ignore, because we know the number of tokens
				}
				return NewTermQuery(new Term(field, term));
			}
			else
			{
				if (severalTokensAtSamePosition)
				{
					if (positionCount == 1)
					{
						// no phrase query:
						BooleanQuery q = NewBooleanQuery(true);
						for (int i = 0; i < numTokens; i++)
						{
							System.String term = null;
							try
							{
								bool hasNext = buffer.IncrementToken();
								System.Diagnostics.Debug.Assert(hasNext == true);
								term = termAtt.Term();
							}
							catch (System.IO.IOException e)
							{
								// safe to ignore, because we know the number of tokens
							}
							
							Query currentQuery = NewTermQuery(new Term(field, term));
							q.Add(currentQuery, BooleanClause.Occur.SHOULD);
						}
						return q;
					}
					else
					{
						// phrase query:
						MultiPhraseQuery mpq = NewMultiPhraseQuery();
						mpq.SetSlop(phraseSlop);
						System.Collections.ArrayList multiTerms = new System.Collections.ArrayList();
						int position = - 1;
						for (int i = 0; i < numTokens; i++)
						{
							System.String term = null;
							int positionIncrement = 1;
							try
							{
								bool hasNext = buffer.IncrementToken();
								System.Diagnostics.Debug.Assert(hasNext == true);
								term = termAtt.Term();
								if (posIncrAtt != null)
								{
									positionIncrement = posIncrAtt.GetPositionIncrement();
								}
							}
							catch (System.IO.IOException e)
							{
								// safe to ignore, because we know the number of tokens
							}
							
							if (positionIncrement > 0 && multiTerms.Count > 0)
							{
								if (enablePositionIncrements)
								{
                                    mpq.Add((Term[]) multiTerms.ToArray(typeof(Term)), position);
								}
								else
								{
                                    mpq.Add((Term[]) multiTerms.ToArray(typeof(Term)));
								}
								multiTerms.Clear();
							}
							position += positionIncrement;
							multiTerms.Add(new Term(field, term));
						}
						if (enablePositionIncrements)
						{
                            mpq.Add((Term[]) multiTerms.ToArray(typeof(Term)), position);
						}
						else
						{
                            mpq.Add((Term[]) multiTerms.ToArray(typeof(Term)));
						}
						return mpq;
					}
				}
				else
				{
					PhraseQuery pq = NewPhraseQuery();
					pq.SetSlop(phraseSlop);
					int position = - 1;
					
					
					for (int i = 0; i < numTokens; i++)
					{
						System.String term = null;
						int positionIncrement = 1;
						
						try
						{
							bool hasNext = buffer.IncrementToken();
							System.Diagnostics.Debug.Assert(hasNext == true);
							term = termAtt.Term();
							if (posIncrAtt != null)
							{
								positionIncrement = posIncrAtt.GetPositionIncrement();
							}
						}
						catch (System.IO.IOException e)
						{
							// safe to ignore, because we know the number of tokens
						}
						
						if (enablePositionIncrements)
						{
							position += positionIncrement;
							pq.Add(new Term(field, term), position);
						}
						else
						{
							pq.Add(new Term(field, term));
						}
					}
					return pq;
				}
			}
		}
Example #52
0
 /// <summary>Return the clauses whose spans are matched. </summary>
 public virtual SpanQuery[] GetClauses()
 {
     return((SpanQuery[])clauses.ToArray(typeof(SpanQuery[])));
 }
Example #53
0
 /// <summary> Convenience routine to make it easy to return the most interesting words in a document.
 /// More advanced users will call {@link #RetrieveTerms(java.io.Reader) retrieveTerms()} directly.
 /// </summary>
 /// <param name="r">the source document
 /// </param>
 /// <returns> the most interesting words in the document
 /// 
 /// </returns>
 /// <seealso cref="#RetrieveTerms(java.io.Reader)">
 /// </seealso>
 /// <seealso cref="#setMaxQueryTerms">
 /// </seealso>
 public System.String[] RetrieveInterestingTerms(System.IO.StreamReader r)
 {
     System.Collections.ArrayList al = new System.Collections.ArrayList(maxQueryTerms);
     PriorityQueue pq = RetrieveTerms(r);
     System.Object cur;
     int lim = maxQueryTerms; // have to be careful, retrieveTerms returns all words but that's probably not useful to our caller...
     // we just want to return the top words
     while (((cur = pq.Pop()) != null) && lim-- > 0)
     {
         System.Object[] ar = (System.Object[]) cur;
         al.Add(ar[0]); // the 1st entry is the interesting word
     }
     System.String[] res = new System.String[al.Count];
     // return (System.String[]) SupportClass.ICollectionSupport.ToArray(al, res);
     return (System.String[]) al.ToArray(typeof(System.String));
 }
 ///<summary>
 ///Copies the elements of the unit_nodeArrayList to a new unit_node array.
 ///</summary>
 ///<returns>An unit_node array containing copies of the elements of the unit_nodeArrayList.</returns>
 public unit_node[] ToArray()
 {
     return((unit_node[])(arr.ToArray(typeof(unit_node))));
 }
		private void  ProcessTerms(System.String[] queryTerms)
		{
			if (queryTerms != null)
			{
				System.Array.Sort(queryTerms);
				System.Collections.IDictionary tmpSet = new System.Collections.Hashtable(queryTerms.Length);
				//filter out duplicates
				System.Collections.ArrayList tmpList = new System.Collections.ArrayList(queryTerms.Length);
				System.Collections.ArrayList tmpFreqs = new System.Collections.ArrayList(queryTerms.Length);
				int j = 0;
				for (int i = 0; i < queryTerms.Length; i++)
				{
					System.String term = queryTerms[i];
                    System.Object tmpPosition = tmpSet[term];
					if (tmpPosition == null)
					{
						tmpSet[term] = (System.Int32) j++;
						tmpList.Add(term);
						tmpFreqs.Add(1);
					}
					else
					{
                        System.Int32 position = (System.Int32) tmpSet[term];
						System.Int32 integer = (System.Int32) tmpFreqs[position];
						tmpFreqs[position] = (System.Int32) (integer + 1);
					}
				}
                terms = (System.String[]) tmpList.ToArray(typeof(System.String));
				//termFreqs = (int[])tmpFreqs.toArray(termFreqs);
				termFreqs = new int[tmpFreqs.Count];
				int i2 = 0;
				for (System.Collections.IEnumerator iter = tmpFreqs.GetEnumerator(); iter.MoveNext(); )
				{
					System.Int32 integer = (System.Int32) iter.Current;
					termFreqs[i2++] = integer;
				}
			}
		}
Example #56
0
 private void OnLoad(object sender, EventArgs e)
 {
     SySal.OperaDb.OperaDbConnection conn = null;
     SySal.OperaDb.OperaDbDataReader rd1  = null;
     SySal.OperaDb.OperaDbDataReader rd3  = null;
     SySal.OperaDb.OperaDbDataReader rd4  = null;
     try
     {
         conn = SySal.OperaDb.OperaDbCredentials.CreateFromRecord().Connect();
         conn.Open();
         rd1 = new SySal.OperaDb.OperaDbCommand("select id, name from tb_machines where id_site = (select value from opera.lz_sitevars where name = 'ID_SITE') and isscanningserver > 0 order by name", conn).ExecuteReader();
         while (rd1.Read())
         {
             ListViewItem lvi = new ListViewItem(rd1.GetInt64(0).ToString());
             lvi.Tag = rd1.GetString(1) /*rd1.GetInt64(0)*/;
             lvi.SubItems.Add(rd1.GetString(1));
             lvMachines.Items.Add(lvi);
         }
         rd1.Close();
         rd3 = new SySal.OperaDb.OperaDbCommand("select value from opera.lz_sitevars where name = 'BM_AutoStartFile'", conn).ExecuteReader();
         if (rd3.Read())
         {
             m_AutoStartPath = rd3.GetString(0);
         }
         else
         {
             MessageBox.Show("AutoStart file path not set in LZ_SITEVARS.\r\nCannot continue.", "Infrastructure Setup Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             Close();
             return;
         }
         System.Collections.ArrayList pa = new System.Collections.ArrayList();
         rd4 = new SySal.OperaDb.OperaDbCommand("select id, z from tb_plates where id_eventbrick = " + BrickId + " order by z desc", conn).ExecuteReader();
         while (rd4.Read())
         {
             pa.Add(new PlateRecord(rd4.GetInt32(0), rd4.GetDouble(1)));
         }
         if (pa.Count == 0)
         {
             throw new Exception("No plates registered in your DB for this brick.\r\nPlease check and retry.");
         }
         Plates = (PlateRecord[])pa.ToArray(typeof(PlateRecord));
         int i;
         for (i = 0; i < Plates.Length && Plates[i].Id != VolStart.Plate; i++)
         {
             ;
         }
         cmbPlates.Items.Add(i + "/0");
         cmbPlates.Items.Add("0/" + (Plates.Length - 1 - i));
         cmbSkew.Items.Add(VolStart.Slope.X.ToString("F4", System.Globalization.CultureInfo.InvariantCulture) + "/" + VolStart.Slope.Y.ToString("F4", System.Globalization.CultureInfo.InvariantCulture));
         rd4.Close();
         cmbNotes.Items.Add("TotalScan on brick " + BrickId);
         cmbNotes.Items.Add("TotalScan on brick " + BrickId + " around vertex point");
         cmbNotes.Items.Add("TotalScan on brick " + BrickId + " around stopping point");
         cmbNotes.SelectedIndex = VolumeStartsFromTrack ? 2 : 1;
         RefreshProgramSettings(conn);
         cmbWidthHeight.SelectedIndex = 0;
         cmbPlates.SelectedIndex      = 0;
         cmbSkew.SelectedIndex        = 0;
         OnWidthHeightLeave(this, null);
         OnPlatesLeave(this, null);
         OnSkewLeave(this, null);
     }
     catch (Exception x)
     {
         MessageBox.Show(x.ToString(), "Initialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Close();
     }
     finally
     {
         if (rd1 != null)
         {
             rd1.Close();
         }
         if (rd3 != null)
         {
             rd3.Close();
         }
         if (rd4 != null)
         {
             rd3.Close();
         }
         if (conn != null)
         {
             conn.Close();
         }
     }
 }
		public virtual void  TestPhrasePrefix()
		{
			RAMDirectory indexStore = new RAMDirectory();
			IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
			Add("blueberry pie", writer);
			Add("blueberry strudel", writer);
			Add("blueberry pizza", writer);
			Add("blueberry chewing gum", writer);
			Add("bluebird pizza", writer);
			Add("bluebird foobar pizza", writer);
			Add("piccadilly circus", writer);
			writer.Optimize();
			writer.Close();
			
			IndexSearcher searcher = new IndexSearcher(indexStore);
			
			// search for "blueberry pi*":
			MultiPhraseQuery query1 = new MultiPhraseQuery();
			// search for "strawberry pi*":
			MultiPhraseQuery query2 = new MultiPhraseQuery();
			query1.Add(new Term("body", "blueberry"));
			query2.Add(new Term("body", "strawberry"));
			
			System.Collections.ArrayList termsWithPrefix = new System.Collections.ArrayList();
			IndexReader ir = IndexReader.Open(indexStore);
			
			// this TermEnum gives "piccadilly", "pie" and "pizza".
			System.String prefix = "pi";
			TermEnum te = ir.Terms(new Term("body", prefix));
			do 
			{
				if (te.Term().Text().StartsWith(prefix))
				{
					termsWithPrefix.Add(te.Term());
				}
			}
			while (te.Next());
			
			query1.Add((Term[]) termsWithPrefix.ToArray(typeof(Term)));
			Assert.AreEqual("body:\"blueberry (piccadilly pie pizza)\"", query1.ToString());
			query2.Add((Term[]) termsWithPrefix.ToArray(typeof(Term)));
			Assert.AreEqual("body:\"strawberry (piccadilly pie pizza)\"", query2.ToString());
			
			ScoreDoc[] result;
			result = searcher.Search(query1, null, 1000).scoreDocs;
			Assert.AreEqual(2, result.Length);
			result = searcher.Search(query2, null, 1000).scoreDocs;
			Assert.AreEqual(0, result.Length);
			
			// search for "blue* pizza":
			MultiPhraseQuery query3 = new MultiPhraseQuery();
			termsWithPrefix.Clear();
			prefix = "blue";
			te = ir.Terms(new Term("body", prefix));
			do 
			{
				if (te.Term().Text().StartsWith(prefix))
				{
					termsWithPrefix.Add(te.Term());
				}
			}
			while (te.Next());
			query3.Add((Term[]) termsWithPrefix.ToArray(typeof(Term)));
			query3.Add(new Term("body", "pizza"));
			
			result = searcher.Search(query3, null, 1000).scoreDocs;
			Assert.AreEqual(2, result.Length); // blueberry pizza, bluebird pizza
			Assert.AreEqual("body:\"(blueberry bluebird) pizza\"", query3.ToString());
			
			// test slop:
			query3.SetSlop(1);
			result = searcher.Search(query3, null, 1000).scoreDocs;
			Assert.AreEqual(3, result.Length); // blueberry pizza, bluebird pizza, bluebird foobar pizza
			
			MultiPhraseQuery query4 = new MultiPhraseQuery();
			try
			{
				query4.Add(new Term("field1", "foo"));
				query4.Add(new Term("field2", "foobar"));
				Assert.Fail();
			}
			catch (System.ArgumentException e)
			{
				// okay, all terms must belong to the same field
			}
			
			searcher.Close();
			indexStore.Close();
		}
Example #58
0
        /// <summary>
        /// 调用仪器的数据解析文件解析数据,然后将数据入库同时实时显示数据	xing.chen添加注释
        /// </summary>
        /// <param name="objDataAnalyzer">解析文件类对象</param>
        /// <param name="strData_Received">接收的数据</param>
        /// <param name="strInstrument_ID">仪器id</param>
        /// <param name="strInstrument_Name">仪器名</param>
        public void DigitalSerial_DataComing(com.digitalwave.iCare.middletier.LIS.infLISDataAnalysis objDataAnalyzer, string strData_Received, string strInstrument_ID, string strInstrument_Name)
        {
            try
            {
                if (objDataAnalyzer != null)
                {
                    string[] strIntactDataList = objDataAnalyzer.strGetIntactData(strData_Received);
                    if (strIntactDataList != null)
                    {
                        for (int j = 0; j < strIntactDataList.Length; j++)
                        {
                            string strIntactData = strIntactDataList[j];
                            System.Collections.ArrayList arlResult = null;

                            //xing.chen add test code
                            testLog.Log2File(@"D:\logInfo.txt", "Data Analysis", DateTime.Now.ToLongTimeString());
                            ////testLog.Log2File(@"D:\code\log.txt", strIntactData, DateTime.Now.ToLongTimeString());
                            //testLog.Log2File(@"D:\logInfo.txt", strIntactData, DateTime.Now.ToLongTimeString());

                            long lngRes = objDataAnalyzer.lngDataAnalysis(strIntactData, out arlResult);
//							int z=0;
//							while(z<arlResult.Count)
//							{
//								if(((clsLIS_Device_Test_ResultVO)arlResult[z]).intIsGraphResult == 1)
//								{
//									arlResult.RemoveAt(z);
//								}
//								else
//								{
//									z++;
//								}
//							}
                            com.digitalwave.iCare.ValueObject.clsLIS_Device_Test_ResultVO[] colDevice_Test_Results = (clsLIS_Device_Test_ResultVO[])arlResult.ToArray(typeof(com.digitalwave.iCare.ValueObject.clsLIS_Device_Test_ResultVO));
                            if (arlResult != null)
                            {
                                try
                                {
                                    //string str = arlResult.Count.ToString() + " 123";
                                    //testLog.Log2File(@"D:\logInfo.txt", str, DateTime.Now.ToLongTimeString());
                                    for (int i = 0; i < colDevice_Test_Results.Length; i++)
                                    {
                                        colDevice_Test_Results[i].strDevice_ID = strInstrument_ID;
                                    }

                                    com.digitalwave.iCare.middletier.LIS.clsLIS_Svc objLIS_Svc = (clsLIS_Svc)com.digitalwave.iCare.common.clsObjectGenerator.objCreatorObjectByType(typeof(com.digitalwave.iCare.middletier.LIS.clsLIS_Svc));
                                    lngRes = 0;
                                    System.Collections.ArrayList arlOut = null;

                                    //xing.chen add test code

                                    testLog.Log2File(@"D:\logInfo.txt", "Data insert database", DateTime.Now.ToLongTimeString());

                                    lngRes = objLIS_Svc.lngAddLabResult(arlResult, out arlOut);
                                    if (lngRes > 0)
                                    {
                                        arlResult = arlOut;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    string srr = ex.Message;
                                }
                                #region 显示实时信息
                                if (lngRes > 0)
                                {
                                    //xing.chen add test code
                                    testLog.Log2File(@"D:\logInfo.txt", "Data Show", DateTime.Now.ToLongTimeString());

                                    colDevice_Test_Results = (clsLIS_Device_Test_ResultVO[])arlResult.ToArray(typeof(com.digitalwave.iCare.ValueObject.clsLIS_Device_Test_ResultVO));

                                    clsDeviceSampleDataKey objKey = new clsDeviceSampleDataKey();
                                    objKey.intResultBeginIndex = colDevice_Test_Results[0].intIndex;
                                    objKey.intResultEndIndex   = colDevice_Test_Results[colDevice_Test_Results.Length - 1].intIndex;
                                    objKey.strDeviceID         = strInstrument_ID;
                                    objKey.strDeviceName       = strInstrument_Name;
                                    objKey.strDeviceSampleID   = colDevice_Test_Results[0].strDevice_Sample_ID;
                                    objKey.strCheckDate        = colDevice_Test_Results[0].strCheck_Date;
                                    m_objViewer.m_mthShowMessage(objKey, colDevice_Test_Results);
                                }
                                #endregion
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
            private string[] CleanLine (string[] lines, LineSettings lineSettings)
            {
                System.Collections.ArrayList ret = new System.Collections.ArrayList();

                for (int i = 0; i < lines.Length; i++)
                {
                    //	CleanLine(lines[i]);
                    string x = FFACE.ChatTools.CleanLine(lines[i], lineSettings);
                    if (x == ".")
                        continue;
                    ret.Add(x);
                }
                string[] returnList = (string[])ret.ToArray(typeof(string));
                return returnList;
            }
Example #60
0
        protected virtual void ProcessImages(string json)
        {
            Dictionary <string, object> jsonDict = Helper.ToJsonDict(json);

            if (jsonDict != null)
            {
                //poster
                System.Collections.ArrayList posters = (System.Collections.ArrayList)jsonDict["posters"];
                if (posters != null && posters.Count > 0 && (Kernel.Instance.ConfigData.RefreshItemImages || !HasLocalImage()))
                {
                    string tmdbImageUrl = Kernel.Instance.ConfigData.TmdbImageUrl + Kernel.Instance.ConfigData.FetchedPosterSize;
                    //posters should be in order of rating.  get first one for our language
                    foreach (Dictionary <string, object> poster in posters)
                    {
                        if ((string)poster["iso_639_1"] == Kernel.Instance.ConfigData.PreferredMetaDataLanguage)
                        {
                            Logger.ReportVerbose("MovieDbProvider - using poster for language " + Kernel.Instance.ConfigData.PreferredMetaDataLanguage);
                            Item.PrimaryImagePath = ProcessImage(tmdbImageUrl + poster["file_path"].ToString(), "folder");
                            break;
                        }
                    }

                    if (Item.PrimaryImagePath == null && (Kernel.Instance.ConfigData.RefreshItemImages || !HasLocalImage()))
                    {
                        //couldn't find one for our specific country - just take the first one with null country
                        Logger.ReportVerbose("MovieDbProvider - no specific language poster using highest rated English one.");
                        string posterPath = "";
                        try
                        {
                            posterPath = ((Dictionary <string, object>)posters.ToArray().Where(p => (string)((Dictionary <string, object>)p)["iso_639_1"] == "en").First())["file_path"].ToString();
                        } catch
                        {
                            //fall back to first one
                            try
                            {
                                posterPath = ((Dictionary <string, object>)posters[0])["file_path"].ToString();
                            }
                            catch (Exception e)
                            {
                                //give up
                                Logger.ReportException("Unable to find poster.", e);
                            }
                        }
                        if (!String.IsNullOrEmpty(posterPath))
                        {
                            Item.PrimaryImagePath = ProcessImage(tmdbImageUrl + posterPath, "folder");
                        }
                    }
                }

                //backdrops
                System.Collections.ArrayList backdrops = (System.Collections.ArrayList)jsonDict["backdrops"];
                if (backdrops != null && backdrops.Count > 0)
                {
                    if (Item.BackdropImagePaths == null)
                    {
                        Item.BackdropImagePaths = new List <string>();
                    }
                    string tmdbImageUrl = Kernel.Instance.ConfigData.TmdbImageUrl + Kernel.Instance.ConfigData.FetchedBackdropSize;
                    //posters should be in order of rating.  get first n ones
                    int numToFetch = Math.Min(Kernel.Instance.ConfigData.MaxBackdrops, backdrops.Count);
                    for (int i = 0; i < numToFetch; i++)
                    {
                        string bdNum = i == 0 ? "" : i.ToString();
                        Item.BackdropImagePaths.Add(ProcessImage(tmdbImageUrl + ((Dictionary <string, object>)backdrops[i])["file_path"].ToString(), "backdrop" + bdNum));
                    }
                }
            }
            else
            {
                Logger.ReportInfo("MovieDbProvider - No images defined for " + Item.Name);
            }
        }