NextToken() public method

Returns the next token from the token list
public NextToken ( ) : string
return string
        /// <summary> Reads given "property file" and sets system properties accordingly.  In the property file,
        /// there should be one property per line.  A line should consist of 1) the fully qualified property name,
        /// 2) one or more tabs, and 3) the value (everything after the first group of tabs and before any subsequent
        /// groups will be considered "the value").
        /// Lines in the file are consdidered comments if they begin with "%".
        /// </summary>
        public static void  loadProperties(System.String propertyFileName)
        {
            //open stream from given property file
            System.IO.StreamReader in_Renamed = null;
            in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).CurrentEncoding);

            System.String          line, key, value_Renamed, delim = "\t";
            SupportClass.Tokenizer tok;
            while ((line = in_Renamed.ReadLine()) != null)
            {
                //ignore comments
                if (!line.StartsWith("%"))
                {
                    key = null; value_Renamed = null;

                    //get property key and value
                    tok = new SupportClass.Tokenizer(line, delim, false);
                    if (tok.HasMoreTokens())
                    {
                        key = tok.NextToken();
                    }
                    if (tok.HasMoreTokens())
                    {
                        value_Renamed = tok.NextToken();
                    }
                }
            }
            in_Renamed.Close();
        }
Example #2
0
        /// <summary> Select the theory and basis set from the first archive line.
        ///
        /// </summary>
        /// <param name="line">Description of the Parameter
        /// </param>
        /// <returns> Description of the Return Value
        /// </returns>
        private System.String parseLevelOfTheory(System.String line)
        {
            System.Text.StringBuilder summary = new System.Text.StringBuilder();
            summary.Append(line);
            try
            {
                do
                {
                    line = input.ReadLine().Trim();
                    summary.Append(line);
                }while (!(line.IndexOf("@") >= 0));
            }
            catch (System.Exception exc)
            {
                //logger.debug("syntax problem while parsing summary of g98 section: ");
                //logger.debug(exc);
            }
            //logger.debug("parseLoT(): " + summary.ToString());
            SupportClass.Tokenizer st1 = new SupportClass.Tokenizer(summary.ToString(), "\\");

            // Must contain at least 6 tokens
            if (st1.Count < 6)
            {
                return(null);
            }

            // Skip first four tokens
            for (int i = 0; i < 4; ++i)
            {
                st1.NextToken();
            }

            return(st1.NextToken() + "/" + st1.NextToken());
        }
Example #3
0
        /// <summary> Extracts selected fields from a message.
        ///
        /// </summary>
        /// <param name="theMessageText">an unparsed message from which to get fields
        /// </param>
        /// <param name="thePathSpecs">Terser-like paths to fields in the message.  See documentation
        /// for Terser.  These paths are identical except that they start with the segment
        /// name (search flags and group names are to be omitted as they are not relevant
        /// with unparsed ER7 messages).
        /// </param>
        /// <returns> field values corresponding to the given paths
        /// </returns>
        /// <throws>  HL7Exception </throws>
        public static System.String[] getFields(System.String theMessageText, System.String[] thePathSpecs)
        {
            NuGenDatumPath[] paths = new NuGenDatumPath[thePathSpecs.Length];
            for (int i = 0; i < thePathSpecs.Length; i++)
            {
                SupportClass.Tokenizer tok     = new SupportClass.Tokenizer(thePathSpecs[i], "-", false);
                System.String          segSpec = tok.NextToken();
                tok = new SupportClass.Tokenizer(segSpec, "()", false);
                System.String segName = tok.NextToken();
                if (segName.Length != 3)
                {
                    throw new NuGenHL7Exception("In field path, " + segName + " is not a valid segment name");
                }
                int segRep = 0;
                if (tok.HasMoreTokens())
                {
                    System.String rep = tok.NextToken();
                    try
                    {
                        segRep = System.Int32.Parse(rep);
                    }
                    catch (System.FormatException e)
                    {
                        throw new NuGenHL7Exception("In field path, segment rep" + rep + " is not valid", e);
                    }
                }

                int[] indices = Terser.getIndices(thePathSpecs[i]);
                paths[i] = new NuGenDatumPath();
                paths[i].add(segName).add(segRep);
                paths[i].add(indices[0]).add(indices[1]).add(indices[2]).add(indices[3]);
            }
            return(getFields(theMessageText, paths));
        }
		/// <summary> Reads given "property file" and sets system properties accordingly.  In the property file,
		/// there should be one property per line.  A line should consist of 1) the fully qualified property name,
		/// 2) one or more tabs, and 3) the value (everything after the first group of tabs and before any subsequent
		/// groups will be considered "the value").
		/// Lines in the file are consdidered comments if they begin with "%".
		/// </summary>
		public static void  loadProperties(System.String propertyFileName)
		{
			
			//open stream from given property file
			System.IO.StreamReader in_Renamed = null;
			in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).CurrentEncoding);
			
			System.String line, key, value_Renamed, delim = "\t";
			SupportClass.Tokenizer tok;
			while ((line = in_Renamed.ReadLine()) != null)
			{
				//ignore comments
				if (!line.StartsWith("%"))
				{
					key = null; value_Renamed = null;
					
					//get property key and value
					tok = new SupportClass.Tokenizer(line, delim, false);
					if (tok.HasMoreTokens())
						key = tok.NextToken();
					if (tok.HasMoreTokens())
						value_Renamed = tok.NextToken();
				}
			}
			in_Renamed.Close();
		}
		/// <summary> Extracts selected fields from a message.  
		/// 
		/// </summary>
		/// <param name="theMessageText">an unparsed message from which to get fields 
		/// </param>
		/// <param name="thePathSpecs">Terser-like paths to fields in the message.  See documentation
		/// for Terser.  These paths are identical except that they start with the segment
		/// name (search flags and group names are to be omitted as they are not relevant 
		/// with unparsed ER7 messages).  
		/// </param>
		/// <returns> field values corresponding to the given paths
		/// </returns>
		/// <throws>  HL7Exception </throws>
		public static System.String[] getFields(System.String theMessageText, System.String[] thePathSpecs)
		{
			NuGenDatumPath[] paths = new NuGenDatumPath[thePathSpecs.Length];
			for (int i = 0; i < thePathSpecs.Length; i++)
			{
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePathSpecs[i], "-", false);
				System.String segSpec = tok.NextToken();
				tok = new SupportClass.Tokenizer(segSpec, "()", false);
				System.String segName = tok.NextToken();
				if (segName.Length != 3)
				{
					throw new NuGenHL7Exception("In field path, " + segName + " is not a valid segment name");
				}
				int segRep = 0;
				if (tok.HasMoreTokens())
				{
					System.String rep = tok.NextToken();
					try
					{
						segRep = System.Int32.Parse(rep);
					}
					catch (System.FormatException e)
					{
						throw new NuGenHL7Exception("In field path, segment rep" + rep + " is not valid", e);
					}
				}
				
				int[] indices = Terser.getIndices(thePathSpecs[i]);
				paths[i] = new NuGenDatumPath();
				paths[i].add(segName).add(segRep);
				paths[i].add(indices[0]).add(indices[1]).add(indices[2]).add(indices[3]);
			}
			return getFields(theMessageText, paths);
		}
Example #6
0
        private static RootRef parseGuide(System.String theSpec)
        {
            SupportClass.Tokenizer lines = new SupportClass.Tokenizer(theSpec, "\r", false);
            RootRef result = new RootRef();

            System.Collections.ArrayList ancestry = new System.Collections.ArrayList();
            ancestry.Add(result);
            System.Collections.IDictionary successors = new System.Collections.Hashtable();

            StructRef previous = result;

            while (lines.HasMoreTokens())
            {
                System.String          line    = lines.NextToken();
                SupportClass.Tokenizer parts   = new SupportClass.Tokenizer(line, "\t ", false);
                System.String          segName = parts.NextToken();
                System.String          path    = parts.HasMoreTokens()?parts.NextToken():"";
                parts = new SupportClass.Tokenizer(path, ":", false);
                path  = parts.HasMoreTokens()?parts.NextToken():null;

                int[] fields = getFieldList(parts.HasMoreTokens()?parts.NextToken():"");

                if (segName.Equals("}"))
                {
                    StructRef parent = (StructRef)SupportClass.StackSupport.Pop(ancestry);
                    if (parent.ChildName != null && parent.RelativePath.IndexOf('*') >= 0)
                    {
                        //repeating group
                        previous.setSuccessor(parent.ChildName, parent);
                    }
                }
                else
                {
                    bool      isSegment   = !(segName.Equals("{"));
                    StructRef ref_Renamed = new StructRef((StructRef)ancestry[ancestry.Count - 1], path, isSegment, fields);
                    if (isSegment)
                    {
                        previous.setSuccessor(segName, ref_Renamed);
                        if (path.IndexOf('*') >= 0)
                        {
                            ref_Renamed.setSuccessor(segName, ref_Renamed);
                        }
                        setGroupSuccessors(successors, segName);
                    }
                    else
                    {
                        successors[previous] = ref_Renamed;
                    }
                    if (!isSegment)
                    {
                        ancestry.Add(ref_Renamed);
                    }
                    previous = ref_Renamed;
                }
            }

            return(result);
        }
Example #7
0
    // read in a problem (in svmlight format)

    private void  read_problem()
    {
        /* UPGRADE_TODO: Expected value of parameters of constructor
         * 'java.io.BufferedReader.BufferedReader' are different in the equivalent in .NET.
         * 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092"'
         */
        System.IO.StreamReader       fp = new System.IO.StreamReader(input_file_name);
        System.Collections.ArrayList vy = new System.Collections.ArrayList(10);
        System.Collections.ArrayList vx = new System.Collections.ArrayList(10);
        int max_index = 0;

        while (true)
        {
            System.String line = fp.ReadLine();
            if ((System.Object)line == null)
            {
                break;
            }

            SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");

            vy.Add(st.NextToken());
            int        m = st.Count / 2;
            svm_node[] x = new svm_node[m];
            for (int j = 0; j < m; j++)
            {
                x[j]               = new svm_node();
                x[j].index         = atoi(st.NextToken());
                x[j].value_Renamed = atof(st.NextToken());
            }
            if (m > 0)
            {
                max_index = System.Math.Max(max_index, x[m - 1].index);
            }
            vx.Add(x);
        }

        prob   = new svm_problem();
        prob.l = vy.Count;
        prob.x = new svm_node[prob.l][];
        for (int i = 0; i < prob.l; i++)
        {
            prob.x[i] = (svm_node[])vx[i];
        }
        prob.y = new double[prob.l];
        for (int i = 0; i < prob.l; i++)
        {
            prob.y[i] = atof((System.String)vy[i]);
        }

        if (param.gamma == 0)
        {
            param.gamma = 1.0 / max_index;
        }

        fp.Close();
    }
Example #8
0
 public override void characterData(CMLStack xpath, char[] ch, int start, int length)
 {
     System.String s = new System.String(ch, start, length).Trim();
     //logger.debug("Start PMP chardata (" + CurrentElement + ") :" + s);
     //logger.debug(" ElTitle: " + elementTitle);
     if (xpath.ToString().EndsWith("string/") && BUILTIN.Equals("spacegroup"))
     {
         System.String sg = "P1";
         // standardize space group names (see Crystal.java)
         if ("P 21 21 21 (1)".Equals(s))
         {
             sg = "P 2_1 2_1 2_1";
         }
         cdo.setObjectProperty("Crystal", "spacegroup", sg);
     }
     else
     {
         if (xpath.ToString().EndsWith("floatArray/") && (elementTitle.Equals("a") || elementTitle.Equals("b") || elementTitle.Equals("c")))
         {
             System.String axis = elementTitle + "-axis";
             cdo.startObject(axis);
             try
             {
                 SupportClass.Tokenizer st = new SupportClass.Tokenizer(s);
                 //logger.debug("Tokens: " + st.Count);
                 if (st.Count > 2)
                 {
                     System.String token = st.NextToken();
                     //logger.debug("FloatArray (Token): " + token);
                     cdo.setObjectProperty(axis, "x", token);
                     token = st.NextToken();
                     //logger.debug("FloatArray (Token): " + token);
                     cdo.setObjectProperty(axis, "y", token);
                     token = st.NextToken();
                     //logger.debug("FloatArray (Token): " + token);
                     cdo.setObjectProperty(axis, "z", token);
                 }
                 else
                 {
                     //logger.debug("PMP Convention error: incorrect number of cell axis fractions!\n");
                 }
             }
             catch (System.Exception e)
             {
                 //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                 //logger.debug("PMP Convention error: " + e.ToString());
             }
             cdo.endObject(axis);
         }
         else
         {
             base.characterData(xpath, ch, start, length);
         }
     }
     //logger.debug("End PMP chardata");
 }
Example #9
0
        /// <summary> <p>A convenience method for binding applications to an <code>ApplicationRouter</code>
        /// Information about bindings is read from a file at a specified URL.  Each line in the
        /// file should have the following format (entries TAB delimited):</p>
        ///
        /// <p>message_type &#009; trigger_event &#009; processing_id &#009; version_id &#009; app_class</p>
        ///
        /// <p>Note that the first four fields can be the wildcard "*", which means any.</p>
        ///
        /// <p>For example, if you write an Application called org.yourorganiztion.ADTProcessor
        /// that processes several types of ADT messages, and another called
        /// org.yourorganization.ResultProcessor that processes result messages, you might have a
        /// file that looks like this: </p>
        ///
        /// <p>ADT &#009; * &#009; * &#009; * &#009; org.yourorganization.ADTProcessor<br>
        /// ORU &#009; R01 &#009; * &#009; * &#009; org.yourorganization.ResultProcessor</p>
        ///
        /// <p>Each class listed in this file must implement either Genetibase.NuGenHL7.app.Application or
        /// Genetibase.NuGenHL7.protocol.ReceivingApplication, and must have a zero-argument constructor.</p>
        ///
        /// </summary>
        /// <param name="theRouter">the <code>ApplicationRouter</code> on which to make the binding
        /// </param>
        /// <param name="theSource">a URL pointing to the bindings file
        /// </param>
        public static void  loadApplications(NuGenApplicationRouter theRouter, System.Uri theSource)
        {
            if (theSource == null)
            {
                throw new NuGenHL7Exception("Can't load application bindings: the given URL is null");
            }

            System.IO.StreamReader in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).CurrentEncoding);
            System.String          line       = null;
            while ((line = in_Renamed.ReadLine()) != null)
            {
                //parse application registration information
                SupportClass.Tokenizer tok = new SupportClass.Tokenizer(line, "\t", false);
                System.String          type = null, event_Renamed = null, procId = null, verId = null, className = null;

                if (tok.HasMoreTokens())
                {
                    //skip blank lines
                    try
                    {
                        type          = tok.NextToken();
                        event_Renamed = tok.NextToken();
                        procId        = tok.NextToken();
                        verId         = tok.NextToken();
                        className     = tok.NextToken();
                    }
                    catch (System.ArgumentOutOfRangeException)
                    {
                        throw new NuGenHL7Exception("Can't register applications from " + theSource.ToString() + ". The line '" + line + "' is not of the form: message_type [tab] trigger_event " + "[tab] processing ID [tab] version ID [tab] application_class. " + "*** NOTE TWO NEW FIELDS AS OF HAPI 0.5 ****. ", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                    }

                    System.Type               appClass  = System.Type.GetType(className);      //may throw ClassNotFoundException
                    System.Object             appObject = System.Activator.CreateInstance(appClass);
                    NuGenReceivingApplication app       = null;
                    if (appObject is NuGenReceivingApplication)
                    {
                        app = (NuGenReceivingApplication)appObject;
                    }
                    else if (appObject is Application)
                    {
                        app = new NuGenAppWrapper((Application)appObject);
                    }
                    else
                    {
                        throw new NuGenHL7Exception("The specified class, " + appClass.FullName + ", doesn't implement Application or ReceivingApplication.", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                    }

                    Genetibase.NuGenHL7.protocol.AppRoutingData rd = new NuGenAppRoutingDataImpl(type, event_Renamed, procId, verId);
                    theRouter.bindApplication(rd, app);
                }
            }
        }
Example #10
0
 public static System.String nextToken(SupportClass.Tokenizer st)
 {
     System.String t = st.NextToken().Trim();
     if (t.Equals("\t"))
     {
         t = "";
     }
     if (st.HasMoreTokens())
     {
         st.NextToken();
     }
     return(t);
 }
		/// <param name="theScope">must be in the form type^event (ie message type and trigger event separated
		/// by a carat)
		/// </param>
		public override bool appliesToScope(System.String theScope)
		{			
			if (!Regex.IsMatch(theScope, ".*\\^.*"))
			{
				throw new System.ArgumentException("arg theScope must be of the form type^event");
			}
			
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(theScope, delim, false);
			System.String itemType = tok.NextToken();
			System.String itemEvent = tok.NextToken();

            throw new Exception("This method is invalid");
			
			//return applies;
		}
Example #12
0
        /// <param name="theScope">must be in the form type^event (ie message type and trigger event separated
        /// by a carat)
        /// </param>
        public override bool appliesToScope(System.String theScope)
        {
            if (!Regex.IsMatch(theScope, ".*\\^.*"))
            {
                throw new System.ArgumentException("arg theScope must be of the form type^event");
            }

            SupportClass.Tokenizer tok       = new SupportClass.Tokenizer(theScope, delim, false);
            System.String          itemType  = tok.NextToken();
            System.String          itemEvent = tok.NextToken();

            throw new Exception("This method is invalid");

            //return applies;
        }
        // private functions

        /// <summary> Reads a ChemFile object from input.
        ///
        /// </summary>
        /// <returns> ChemFile with the content read from the input
        /// </returns>
        private IChemFile readChemFile(IChemFile cf)
        {
            // have to do stuff here
            try
            {
                System.String line = input.ReadLine();
                while (line != null)
                {
                    if (line.StartsWith("INChI="))
                    {
                        // ok, the fun starts
                        cf = cf.Builder.newChemFile();
                        // ok, we need to parse things like:
                        // INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H
                        //UPGRADE_NOTE: Final was removed from the declaration of 'INChI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String          INChI     = line.Substring(6);
                        SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(INChI, "/");
                        // ok, we expect 4 tokens
                        //UPGRADE_NOTE: Final was removed from the declaration of 'version '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String version = tokenizer.NextToken();                  // 1.12Beta
                        //UPGRADE_NOTE: Final was removed from the declaration of 'formula '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String formula = tokenizer.NextToken();                  // C6H6
                        //UPGRADE_NOTE: Final was removed from the declaration of 'connections '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String connections = tokenizer.NextToken().Substring(1); // 1-2-4-6-5-3-1
                        //UPGRADE_NOTE: Final was removed from the declaration of 'hydrogens '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String hydrogens = tokenizer.NextToken().Substring(1);   // 1-6H

                        IAtomContainer parsedContent = inchiTool.processFormula(cf.Builder.newAtomContainer(), formula);
                        inchiTool.processConnections(connections, parsedContent, -1);

                        ISetOfMolecules moleculeSet = cf.Builder.newSetOfMolecules();
                        moleculeSet.addMolecule(cf.Builder.newMolecule(parsedContent));
                        IChemModel model = cf.Builder.newChemModel();
                        model.SetOfMolecules = moleculeSet;
                        IChemSequence sequence = cf.Builder.newChemSequence();
                        sequence.addChemModel(model);
                        cf.addChemSequence(sequence);
                    }
                    line = input.ReadLine();
                }
            }
            catch (System.Exception exception)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                throw new CDKException("Error while reading INChI file: " + exception.Message, exception);
            }
            return(cf);
        }
Example #14
0
        /// <summary>  Description of the Method
        ///
        /// </summary>
        /// <param name="smiles">                     Description of the Parameter
        /// </param>
        /// <returns>                             Description of the Return Value
        /// </returns>
        /// <exception cref="InvalidSmilesException"> Description of the Exception
        /// </exception>
        public virtual Reaction parseReactionSmiles(System.String smiles)
        {
            SupportClass.Tokenizer tokenizer      = new SupportClass.Tokenizer(smiles, ">");
            System.String          reactantSmiles = tokenizer.NextToken();
            System.String          agentSmiles    = "";
            System.String          productSmiles  = tokenizer.NextToken();
            if (tokenizer.HasMoreTokens())
            {
                agentSmiles   = productSmiles;
                productSmiles = tokenizer.NextToken();
            }

            Reaction reaction = new Reaction();

            // add reactants
            IMolecule       reactantContainer = parseSmiles(reactantSmiles);
            ISetOfMolecules reactantSet       = ConnectivityChecker.partitionIntoMolecules(reactantContainer);

            IMolecule[] reactants = reactantSet.Molecules;
            for (int i = 0; i < reactants.Length; i++)
            {
                reaction.addReactant(reactants[i]);
            }

            // add reactants
            if (agentSmiles.Length > 0)
            {
                IMolecule       agentContainer = parseSmiles(agentSmiles);
                ISetOfMolecules agentSet       = ConnectivityChecker.partitionIntoMolecules(agentContainer);
                IMolecule[]     agents         = agentSet.Molecules;
                for (int i = 0; i < agents.Length; i++)
                {
                    reaction.addAgent(agents[i]);
                }
            }

            // add products
            IMolecule       productContainer = parseSmiles(productSmiles);
            ISetOfMolecules productSet       = ConnectivityChecker.partitionIntoMolecules(productContainer);

            IMolecule[] products = productSet.Molecules;
            for (int i = 0; i < products.Length; i++)
            {
                reaction.addProduct(products[i]);
            }

            return(reaction);
        }
		} //end method
		
		/// <summary> Checks a code for an exact match, and using certain sequences where some 
		/// characters are wildcards (e.g. HL7nnnn).  If the pattern contains one of 
		/// " or ", " OR ", or "," each operand is checked.
		/// </summary>
		private bool checkCode(System.String code, System.String pattern)
		{
			bool match = false;
			//mod by Neal acharya - Do full match on with the pattern.  If code matches pattern then return true
			//else parse pattern to look for wildcard characters
			if (code.Equals(pattern))
			{
				match = true;
			}
			//end if 
			else
			{
				if (pattern.IndexOf(' ') >= 0 || pattern.IndexOf(',') >= 0)
				{
					SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pattern, ", ", false);
					while (tok.HasMoreTokens() && !match)
					{
						System.String t = tok.NextToken();
						if (!t.ToUpper().Equals("or".ToUpper()))
							match = checkCode(code, t);
					} //end while
				}
				//end if
				else
				{
					if (code.Equals(pattern))
					{
						match = true;
					}
				} //end else
			} //end else 
			return match;
		} //end method
Example #16
0
        /// <summary>recursively tokenize "guts" (a segment, or part of one) into tokens,
        /// according to separators (aka delimiters) which are different at each level
        /// of recursion, and to a recursive depth which is discovered through "handler"
        /// via handler.delim(int) and handler.specDepth()  As tokens are found, they
        /// are reported to handler via handler.putDatum(), which presumably stashes them
        /// away somewhere.  We tell the handler about the location in the message via
        /// putDatum()'s key argument, which is a List of Integers representing the
        /// position in the parse tree (size() == depth of recursion).
        /// TODO: say more.
        /// </summary>
        protected internal static void  parseSegmentGuts(NuGenER7.Handler handler, System.String guts, System.Collections.ArrayList nodeKey)
        {
            char thisDepthsDelim = handler.delim(nodeKey.Count - 1);

            //nodeKey.add(new Integer(0)); // will change nodeKey back before function exits

            SupportClass.Tokenizer gutsTokenizer = new SupportClass.Tokenizer(guts, System.Convert.ToString(thisDepthsDelim), true);
            while (gutsTokenizer.HasMoreTokens())
            {
                System.String gutsToken = gutsTokenizer.NextToken();

                if (gutsToken[0] == thisDepthsDelim)
                {
                    // gutsToken is all delims -- skipping over as many fields or
                    // components or whatevers as there are characters in the token:
                    int oldvalue = ((System.Int32)nodeKey[nodeKey.Count - 1]);
                    nodeKey[nodeKey.Count - 1] = (System.Int32)(oldvalue + gutsToken.Length);
                }
                else
                {
                    if (nodeKey.Count < handler.specDepth())
                    {
                        nodeKey.Add(0);
                        parseSegmentGuts(handler, gutsToken, nodeKey);
                        SupportClass.SetCapacity(nodeKey, nodeKey.Count - 1);
                    }
                    else
                    {
                        handler.putDatum(nodeKey, gutsToken);
                    }
                }
            }
            //nodeKey.setSize(nodeKey.size()-1); // undoing add done at top of this func
        }
Example #17
0
        /// <summary>Parses message and dumps contents to props, with keys in the
        /// ZYX[a]-b[c]-d-e style.
        /// </summary>
        public static bool parseMessage(System.Collections.Specialized.NameValueCollection props, System.Collections.ArrayList msgMask, System.String message)
        {
            bool ok = false;

            if (message != null)
            {
                if (props == null)
                {
                    props = new System.Collections.Specialized.NameValueCollection();
                }

                SupportClass.Tokenizer messageTokenizer = new SupportClass.Tokenizer(message, segmentSeparators);
                if (messageTokenizer.HasMoreTokens())
                {
                    System.String           firstSegment  = messageTokenizer.NextToken();
                    NuGenEncodingCharacters encodingChars = new NuGenEncodingCharacters('0', "0000");
                    if (parseMSHSegmentWhole(props, msgMask, encodingChars, firstSegment))
                    {
                        ok = true;
                        System.Collections.SortedList segmentId2nextRepIdx = new System.Collections.SortedList();
                        segmentId2nextRepIdx[new System.Text.StringBuilder("MSH").ToString()] = 1;
                        // in case we find another MSH segment, heh.
                        while (messageTokenizer.HasMoreTokens())
                        {
                            parseSegmentWhole(props, segmentId2nextRepIdx, msgMask, encodingChars, messageTokenizer.NextToken());
                        }
                    }
                }
            }
            return(ok);
        }
Example #18
0
        /// <summary> Creates the given directory if it does not exist.</summary>
        public static System.IO.FileInfo makeDirectory(System.String directory)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(directory, "\\/", false);

            System.IO.FileInfo currDir = null;
            while (tok.HasMoreTokens())
            {
                System.String thisDirName = tok.NextToken();

                currDir = new System.IO.FileInfo(currDir.FullName + "\\" + thisDirName);                 //if currDir null, defaults to 1 arg call

                bool tmpBool;
                if (System.IO.File.Exists(currDir.FullName))
                {
                    tmpBool = true;
                }
                else
                {
                    tmpBool = System.IO.Directory.Exists(currDir.FullName);
                }
                if (!tmpBool)
                {
                    //create
                    System.IO.Directory.CreateDirectory(currDir.FullName);
                    ;
                }
                else if (System.IO.File.Exists(currDir.FullName))
                {
                    throw new System.IO.IOException("Can't create directory " + thisDirName + " - file with same name exists.");
                }
            }

            return(currDir);
        }
Example #19
0
        private static int[] getFieldList(System.String theSpec)
        {
            SupportClass.Tokenizer   tok       = new SupportClass.Tokenizer(theSpec, ",", false);
            System.Collections.IList fieldList = new System.Collections.ArrayList(30);
            while (tok.HasMoreTokens())
            {
                System.String token = tok.NextToken();
                int           index = token.IndexOf('-');
                if (index >= 0)
                {
                    //it's a range
                    int start = System.Int32.Parse(token.Substring(0, (index) - (0)));
                    int end   = System.Int32.Parse(token.Substring(index + 1));
                    for (int i = start; i <= end; i++)
                    {
                        fieldList.Add((System.Int32)i);
                    }
                }
                else
                {
                    fieldList.Add(System.Int32.Parse(token));
                }
            }

            int[] result = new int[fieldList.Count];
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = ((System.Int32)fieldList[i]);
            }

            return(result);
        }
Example #20
0
        /// <summary> Returns the query portion of the URL, broken up into individual key/value
        /// pairs. Does NOT unescape the keys and values.
        /// </summary>
        public virtual LinkedHashMap getParameterMap()
        {
            LinkedHashMap map;

            SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(Query, "?&");             //$NON-NLS-1$
            // multiply by 2 to create a sufficiently large HashMap
            map = new LinkedHashMap(tokens.Count * 2);

            while (tokens.HasMoreTokens())
            {
                String nameValuePair = tokens.NextToken();
                String name          = nameValuePair;
                String value         = "";         //$NON-NLS-1$
                int    equalsIndex   = nameValuePair.IndexOf('=');
                if (equalsIndex != -1)
                {
                    name = nameValuePair.Substring(0, (equalsIndex) - (0));
                    if (name.Length > 0)
                    {
                        value = nameValuePair.Substring(equalsIndex + 1);
                    }
                }
                map.Add(name, value);
            }

            return(map);
        }
Example #21
0
        /// <summary> Returns a String representing the encoding of the given message, if
        /// the encoding is recognized.  For example if the given message appears
        /// to be encoded using HL7 2.x XML rules then "XML" would be returned.
        /// If the encoding is not recognized then null is returned.  That this
        /// method returns a specific encoding does not guarantee that the
        /// message is correctly encoded (e.g. well formed XML) - just that
        /// it is not encoded using any other encoding than the one returned.
        /// </summary>
        public override string GetEncoding(string message)
        {
            string encoding = null;

            // quit if the string is too short
            if (message.Length < 4)
            {
                return(null);
            }

            // see if it looks like this message is | encoded ...
            var ok = true;

            // string should start with "MSH"
            if (!message.StartsWith("MSH"))
            {
                return(null);
            }

            // 4th character of each segment should be field delimiter
            var fourthChar = message[3];
            var st         = new SupportClass.Tokenizer(message, Convert.ToString(SegDelim), false);

            while (st.HasMoreTokens())
            {
                var x = st.NextToken();
                if (x.Length > 0)
                {
                    if (char.IsWhiteSpace(x[0]))
                    {
                        x = StripLeadingWhitespace(x);
                    }

                    if (x.Length >= 4 && x[3] != fourthChar)
                    {
                        return(null);
                    }
                }
            }

            // should be at least 11 field delimiters (because MSH-12 is required)
            var nextFieldDelimLoc = 0;

            for (var i = 0; i < 11; i++)
            {
                nextFieldDelimLoc = message.IndexOf((char)fourthChar, nextFieldDelimLoc + 1);
                if (nextFieldDelimLoc < 0)
                {
                    return(null);
                }
            }

            if (ok)
            {
                encoding = "VB";
            }

            return(encoding);
        }
Example #22
0
        /// <summary> <p>Gets the string value of the field specified.  See the class docs for syntax
        /// of the location spec.  </p>
        /// <p>If a repetition is omitted for a repeating segment or field, the first rep is used.
        /// If the component or subcomponent is not specified for a composite field, the first
        /// component is used (this allows one to write code that will work with later versions of
        /// the HL7 standard).
        /// </summary>
        public virtual System.String get_Renamed(System.String spec)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "-", false);
            Segment segment            = getSegment(tok.NextToken());

            int[] ind = getIndices(spec);
            return(get_Renamed(segment, ind[0], ind[1], ind[2], ind[3]));
        }
Example #23
0
        /// <summary> <p>Gets the string value of the field specified.  See the class docs for syntax
        /// of the location spec.  </p>
        /// <p>If a repetition is omitted for a repeating segment or field, the first rep is used.
        /// If the component or subcomponent is not specified for a composite field, the first
        /// component is used (this allows one to write code that will work with later versions of
        /// the HL7 standard).
        /// </summary>
        public virtual String Get(String spec)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "-", false);
            ISegment segment           = getSegment(tok.NextToken());

            int[] ind = getIndices(spec);
            return(Get(segment, ind[0], ind[1], ind[2], ind[3]));
        }
Example #24
0
        /// <summary> Sets the string value of the field specified.  See class docs for location spec syntax.</summary>
        public virtual void  set_Renamed(System.String spec, System.String value_Renamed)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "-", false);
            Segment segment            = getSegment(tok.NextToken());

            int[] ind = getIndices(spec);

            set_Renamed(segment, ind[0], ind[1], ind[2], ind[3], value_Renamed);
        }
Example #25
0
        /// <summary>
        /// Gets the string value of the field specified. See the class docs for syntax
        /// of the location spec.
        /// <para>
        /// If a repetition is omitted for a repeating segment or field, the first rep is used.
        /// If the component or subcomponent is not specified for a composite field, the first
        /// component is used (this allows one to write code that will work with later versions of
        /// the HL7 standard).
        /// </para>
        /// </summary>
        public virtual string Get(string spec)
        {
            var tok     = new SupportClass.Tokenizer(spec, "-", false);
            var segment = GetSegment(tok.NextToken());

            var ind = GetIndices(spec);

            return(Get(segment, ind[0], ind[1], ind[2], ind[3]));
        }
Example #26
0
 private void addDictRefedAnnotation(IChemObject object_Renamed, System.String type, System.String values)
 {
     SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(values, ",");
     while (tokenizer.HasMoreTokens())
     {
         System.String token = tokenizer.NextToken();
         object_Renamed.setProperty(new DictRef("macie:" + type, token), token);
         //logger.debug("Added dict ref ", token, " to ", object_Renamed.GetType().FullName);
     }
 }
Example #27
0
        /// <summary>
        /// Given a Terser path, returns an array containing field num, field rep,
        /// component, and subcomponent.
        /// </summary>
        public static int[] GetIndices(string spec)
        {
            var tok = new SupportClass.Tokenizer(spec, "-", false);

            tok.NextToken(); // skip over segment
            if (!tok.HasMoreTokens())
            {
                throw new HL7Exception("Must specify field in spec " + spec, ErrorCode.APPLICATION_INTERNAL_ERROR);
            }

            int[] ret = null;
            try
            {
                var fieldSpec = new SupportClass.Tokenizer(tok.NextToken(), "()", false);
                var fieldNum  = int.Parse(fieldSpec.NextToken());
                var fieldRep  = 0;
                if (fieldSpec.HasMoreTokens())
                {
                    fieldRep = int.Parse(fieldSpec.NextToken());
                }

                var component = 1;
                if (tok.HasMoreTokens())
                {
                    component = int.Parse(tok.NextToken());
                }

                var subcomponent = 1;
                if (tok.HasMoreTokens())
                {
                    subcomponent = int.Parse(tok.NextToken());
                }

                var result = new int[] { fieldNum, fieldRep, component, subcomponent };
                ret = result;
            }
            catch (FormatException)
            {
                throw new HL7Exception("Invalid integer in spec " + spec, ErrorCode.APPLICATION_INTERNAL_ERROR);
            }

            return(ret);
        }
Example #28
0
        ///
        ///	 <summary> * add - adds a number list to the already existing number list
        ///	 *  </summary>
        ///	 * <param name="s"> the given string
        ///	 *  </param>
        ///	 * <exception cref="FormatException"> - if the String has not a valid format </exception>
        ///
        public virtual void Add(string s)
        {
            //StringTokenizer sToken = new StringTokenizer(s, JDFConstants.BLANK);
            SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(s, JDFConstants.BLANK);

            while (sToken.HasMoreTokens())
            {
                string t = sToken.NextToken().Trim();
                m_numList.Add(t);
            }
        }
Example #29
0
        /// <summary> Returns the segment specified in the given segment_path_spec. </summary>
        public virtual ISegment GetSegment(string segSpec)
        {
            ISegment seg = null;

            if (segSpec.Substring(0, 1 - 0).Equals("/"))
            {
                Finder.Reset();
            }

            var tok    = new SupportClass.Tokenizer(segSpec, "/", false);
            var finder = Finder;

            while (tok.HasMoreTokens())
            {
                var pathSpec = tok.NextToken();
                var ps       = ParsePathSpec(pathSpec);
                if (tok.HasMoreTokens())
                {
                    ps.IsGroup = true;
                }
                else
                {
                    ps.IsGroup = false;
                }

                if (ps.IsGroup)
                {
                    IGroup g = null;
                    if (ps.Find)
                    {
                        g = finder.FindGroup(ps.Pattern, ps.Rep);
                    }
                    else
                    {
                        g = finder.GetGroup(ps.Pattern, ps.Rep);
                    }

                    finder = new SegmentFinder(g);
                }
                else
                {
                    if (ps.Find)
                    {
                        seg = finder.FindSegment(ps.Pattern, ps.Rep);
                    }
                    else
                    {
                        seg = finder.GetSegment(ps.Pattern, ps.Rep);
                    }
                }
            }

            return(seg);
        }
        /// <summary> Create a string array from a string separated by delim
        /// *
        /// </summary>
        /// <param name="line">the line to split
        /// </param>
        /// <param name="delim">the delimter to split by
        /// </param>
        /// <returns>a string array of the split fields
        ///
        /// </returns>
        public static String[] split(String line, String delim)
        {
            ArrayList list = new ArrayList();

            SupportClass.Tokenizer t = new SupportClass.Tokenizer(line, delim);
            while (t.HasMoreTokens())
            {
                list.Add(t.NextToken());
            }
            return((String[])list.ToArray(typeof(String)));
        }
Example #31
0
        public static string[] Split(string line, string delim)
        {
            ArrayList arrayList = new ArrayList();

            SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line, delim);
            while (tokenizer.HasMoreTokens())
            {
                arrayList.Add(tokenizer.NextToken());
            }
            return((string[])arrayList.ToArray(typeof(string)));
        }
Example #32
0
        /// <summary>Gets path information from a path spec. </summary>
        private PathSpec ParsePathSpec(string spec)
        {
            var ps = new PathSpec(this);

            if (spec.StartsWith("."))
            {
                ps.Find = true;
                spec    = spec.Substring(1);
            }
            else
            {
                ps.Find = false;
            }

            if (spec.Length == 0)
            {
                throw new HL7Exception("Invalid path (some path element is either empty or contains only a dot)");
            }

            var tok = new SupportClass.Tokenizer(spec, "()", false);

            ps.Pattern = tok.NextToken();
            if (tok.HasMoreTokens())
            {
                var repString = tok.NextToken();
                try
                {
                    ps.Rep = int.Parse(repString);
                }
                catch (FormatException)
                {
                    throw new HL7Exception(repString + " is not a valid rep #", ErrorCode.APPLICATION_INTERNAL_ERROR);
                }
            }
            else
            {
                ps.Rep = 0;
            }

            return(ps);
        }
Example #33
0
        /// <summary>
        /// Given a Terser path, returns an array containing field num, field rep, component, and
        /// subcomponent.
        /// </summary>
        ///
        /// <exception cref="HL7Exception"> Thrown when a HL 7 error condition occurs. </exception>
        ///
        /// <param name="spec"> The specifier. </param>
        ///
        /// <returns>   An array of int. </returns>

        public static int[] getIndices(System.String spec)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "-", false);
            tok.NextToken(); //skip over segment
            if (!tok.HasMoreTokens())
            {
                throw new HL7Exception("Must specify field in spec " + spec, HL7Exception.APPLICATION_INTERNAL_ERROR);
            }

            int[] ret = null;
            try
            {
                SupportClass.Tokenizer fieldSpec = new SupportClass.Tokenizer(tok.NextToken(), "()", false);
                int fieldNum = System.Int32.Parse(fieldSpec.NextToken());
                int fieldRep = 0;
                if (fieldSpec.HasMoreTokens())
                {
                    fieldRep = System.Int32.Parse(fieldSpec.NextToken());
                }

                int component = 1;
                if (tok.HasMoreTokens())
                {
                    component = System.Int32.Parse(tok.NextToken());
                }

                int subcomponent = 1;
                if (tok.HasMoreTokens())
                {
                    subcomponent = System.Int32.Parse(tok.NextToken());
                }
                int[] result = { fieldNum, fieldRep, component, subcomponent };
                ret = result;
            }
            catch (System.FormatException)
            {
                throw new HL7Exception("Invalid integer in spec " + spec, HL7Exception.APPLICATION_INTERNAL_ERROR);
            }

            return(ret);
        }
Example #34
0
        /// <summary> Returns the segment specified in the given segment_path_spec. </summary>
        public virtual ISegment getSegment(String segSpec)
        {
            ISegment seg = null;

            if (segSpec.Substring(0, (1) - (0)).Equals("/"))
            {
                Finder.reset();
            }

            SupportClass.Tokenizer tok    = new SupportClass.Tokenizer(segSpec, "/", false);
            SegmentFinder          finder = Finder;

            while (tok.HasMoreTokens())
            {
                String   pathSpec = tok.NextToken();
                PathSpec ps       = parsePathSpec(pathSpec);
                if (tok.HasMoreTokens())
                {
                    ps.isGroup = true;
                }
                else
                {
                    ps.isGroup = false;
                }

                if (ps.isGroup)
                {
                    IGroup g = null;
                    if (ps.find)
                    {
                        g = finder.findGroup(ps.pattern, ps.rep);
                    }
                    else
                    {
                        g = finder.getGroup(ps.pattern, ps.rep);
                    }
                    finder = new SegmentFinder(g);
                }
                else
                {
                    if (ps.find)
                    {
                        seg = finder.findSegment(ps.pattern, ps.rep);
                    }
                    else
                    {
                        seg = finder.getSegment(ps.pattern, ps.rep);
                    }
                }
            }

            return(seg);
        }
Example #35
0
		public FileExtFilter(System.String descroot, System.String suffixes)
		{
			//UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'"
			exts = new List<String>();
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(suffixes, ";");
			while (tok.HasMoreTokens())
				exts.Add(tok.NextToken());
			
			descr = descroot + " (";
			for (int n = 0; n < exts.Count; n++)
				descr = descr + (n > 0?" ":"") + "*" + exts[n];
			descr = descr + ")";
		}
Example #36
0
	/// <summary>
	/// Load a properties file from the templatePath defined in the
	/// generator. As the templatePath can contains multiple paths,
	/// it will cycle through them to find the file. The first file
	/// that can be successfully loaded is considered. (kind of
	/// like the java classpath), it is done to clone the Velocity
	/// process of loading templates.
	/// </summary>
	/// <param name="propertiesFile">the properties file to load. It must be
	/// a relative pathname.
	/// </param>
	/// <returns>a properties instance loaded with the properties from
	/// the file. If no file can be found it returns an empty instance.
	/// </returns>
	protected internal virtual ExtendedProperties loadFromTemplatePath(System.String propertiesFile) {
	    ExtendedProperties properties = new ExtendedProperties();
	    System.String templatePath = Generator.Instance.TemplatePath;

	    // We might have something like the following:
	    //
	    // #set ($dbprops = $properties.load("$generator.templatePath/path/props")
	    //
	    // as we have in Torque but we want people to start using
	    //
	    // #set ($dbprops = $properties.load("path/props")
	    //
	    // so that everything works from the filesystem or from
	    // a JAR. So the actual Generator.getTemplatePath()
	    // is not deprecated but it's use in templates
	    // should be.
	    SupportClass.Tokenizer st = new SupportClass.Tokenizer(templatePath, ",");
	    while (st.HasMoreTokens()) {
		System.String templateDir = st.NextToken();
		try {
		    // If the properties file is being pulled from the
		    // file system and someone is using the method whereby
		    // the properties file is assumed to be in the template
		    // path and they are simply using:
		    //
		    // #set ($dbprops = $properties.load("props") (1)
		    //
		    // than we have to tack on the templatePath in order
		    // for the properties file to be found. We want (1)
		    // to work whether the generation is being run from
		    // the file system or from a JAR file.
		    System.String fullPath = propertiesFile;

		    // FIXME probably not that clever since there could be
		    // a mix of file separators and the test will fail :-(
		    if (!fullPath.StartsWith(templateDir)) {
			fullPath = templateDir + "\\" + propertiesFile;
		    }

		    properties.Load(new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read));
		    // first pick wins, we don't need to go further since
		    // we found a valid file.
		    break;
		} catch (System.Exception) {
		    // do nothing
		}
	    }
	    return properties;
	}
		/// <summary> Encodes the given message and compares it to the given string.  Any differences
		/// are noted in the file [hapi.home]/parse_check.txt.  Ignores extra field delimiters.
		/// </summary>
		public static void  checkParse(System.String originalMessageText, Message parsedMessage, Parser parser)
		{
			System.String newMessageText = parser.encode(parsedMessage);
			
			
			if (!originalMessageText.Equals(newMessageText))
			{
				//check each segment
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(originalMessageText, "\r");
				System.Collections.ArrayList one = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						one.Add(seg);
				}
				tok = new SupportClass.Tokenizer(newMessageText, "\r");
				System.Collections.ArrayList two = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						two.Add(stripExtraDelimiters(seg, seg[3]));
				}
				
				if (one.Count != two.Count)
				{
				}
				else
				{
					//check each segment
					for (int i = 0; i < one.Count; i++)
					{
						System.String origSeg = (System.String) one[i];
						System.String newSeg = (System.String) two[i];
						if (!origSeg.Equals(newSeg))
						{
						}
					}
				}
			}
			else
			{
			}
			
		}
Example #38
0
		/// <summary> Constructs a new 'IntegerSpec' for the specified number of tiles and
		/// components, the allowed specifications type and the ParameterList
		/// instance. This constructor is normally called at encoder side and parse
		/// arguments of specified option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">The allowed specifications type
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		/// <param name="optName">The name of the option to process
		/// 
		/// </param>
		public IntegerSpec(int nt, int nc, byte type, ParameterList pl, System.String optName):base(nt, nc, type)
		{
			
			System.Int32 value_Renamed;
			System.String param = pl.getParameter(optName);
			
			if (param == null)
			{
				// No parameter specified
				param = pl.DefaultParameterList.getParameter(optName);
				try
				{
					setDefault((System.Object) System.Int32.Parse(param));
				}
				catch (System.FormatException)
				{
					throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					default: 
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + word);
						}
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					param = pl.DefaultParameterList.getParameter(optName);
					try
					{
						setDefault((System.Object) System.Int32.Parse(param));
					}
					catch (System.FormatException)
					{
						throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
					}
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Example #39
0
		/// <summary> Constructs a new 'AnWTFilterSpec' for the specified number of
		/// components and tiles.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="qts">Quantization specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public AnWTFilterSpec(int nt, int nc, byte type, QuantTypeSpec qts, ParameterList pl):base(nt, nc, type)
		{
			
			// Check parameters
			pl.checkList(AnWTFilter.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(AnWTFilter.ParameterInfo));
			
			System.String param = pl.getParameter("Ffilters");
			bool isFilterSpecified = true;
			
			// No parameter specified
			if (param == null)
			{
				isFilterSpecified = false;
				
				// If lossless compression, uses the reversible filters in each
				// tile-components 
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault(parseFilters(REV_FILTER_STR));
					return ;
				}
				
				// If no filter is specified through the command-line, use
				// REV_FILTER_STR or NON_REV_FILTER_STR according to the
				// quantization type
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						switch (qts.getSpecValType(t, c))
						{
							
							case SPEC_DEF: 
								if (getDefault() == null)
								{
									if (pl.getBooleanParameter("lossless"))
										setDefault(parseFilters(REV_FILTER_STR));
									if (((System.String) qts.getDefault()).Equals("reversible"))
									{
										setDefault(parseFilters(REV_FILTER_STR));
									}
									else
									{
										setDefault(parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_DEF;
								break;
							
							case SPEC_COMP_DEF: 
								if (!isCompSpecified(c))
								{
									if (((System.String) qts.getCompDef(c)).Equals("reversible"))
									{
										setCompDef(c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setCompDef(c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_COMP_DEF;
								break;
							
							case SPEC_TILE_DEF: 
								if (!isTileSpecified(t))
								{
									if (((System.String) qts.getTileDef(t)).Equals("reversible"))
									{
										setTileDef(t, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileDef(t, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_DEF;
								break;
							
							case SPEC_TILE_COMP: 
								if (!isTileCompSpecified(t, c))
								{
									if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
									{
										setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_COMP;
								break;
							
							default: 
								throw new System.ArgumentException("Unsupported " + "specification " + "type");
							
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			AnWTFilter[][] filter;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't': 
					// Tiles specification
					case 'T':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c': 
					// Components specification
					case 'C':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					case 'w': 
					// WT filters specification
					case 'W':  // WT filters specification
						if (pl.getBooleanParameter("lossless") && word.ToUpper().Equals("w9x7".ToUpper()))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "wavelet transform with" + " '-lossless' option");
						}
						
						filter = parseFilters(word);
						if (curSpecType == SPEC_DEF)
						{
							setDefault(filter);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, filter);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, filter);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, filter);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Bad construction for " + "parameter: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					if (((System.String) qts.getDefault()).Equals("reversible"))
						setDefault(parseFilters(REV_FILTER_STR));
					else
						setDefault(parseFilters(NON_REV_FILTER_STR));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
			
			// Check consistency between filter and quantization type
			// specification
			for (int t = nt - 1; t >= 0; t--)
			{
				for (int c = nc - 1; c >= 0; c--)
				{
					// Reversible quantization
					if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
					{
						// If filter is reversible, it is OK
						if (isReversible(t, c))
							continue;
						
						// If no filter has been defined, use reversible filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
						}
						else
						{
							// Non reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line.");
						}
					}
					else
					{
						// No reversible quantization
						// No reversible filter -> OK
						if (!isReversible(t, c))
							continue;
						
						// If no filter has been specified, use non-reversible
						// filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
						}
						else
						{
							// Reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line");
						}
					}
				}
			}
		}
		/// <summary> Returns a String representing the encoding of the given message, if
		/// the encoding is recognized.  For example if the given message appears
		/// to be encoded using HL7 2.x XML rules then "XML" would be returned.
		/// If the encoding is not recognized then null is returned.  That this
		/// method returns a specific encoding does not guarantee that the
		/// message is correctly encoded (e.g. well formed XML) - just that
		/// it is not encoded using any other encoding than the one returned.
		/// </summary>
		public override System.String getEncoding(System.String message)
		{
			System.String encoding = null;
			
			//quit if the string is too short
			if (message.Length < 4)
				return null;
			
			//see if it looks like this message is | encoded ...
			bool ok = true;
			
			//string should start with "MSH"
			if (!message.StartsWith("MSH"))
				return null;
			
			//4th character of each segment should be field delimiter
			char fourthChar = message[3];
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(message, System.Convert.ToString(segDelim), false);
			while (st.HasMoreTokens())
			{
				System.String x = st.NextToken();
				if (x.Length > 0)
				{
					if (System.Char.IsWhiteSpace(x[0]))
						x = stripLeadingWhitespace(x);
					if (x.Length >= 4 && x[3] != fourthChar)
						return null;
				}
			}
			
			//should be at least 11 field delimiters (because MSH-12 is required)
			int nextFieldDelimLoc = 0;
			for (int i = 0; i < 11; i++)
			{
				nextFieldDelimLoc = message.IndexOf((System.Char) fourthChar, nextFieldDelimLoc + 1);
				if (nextFieldDelimLoc < 0)
					return null;
			}
			
			if (ok)
				encoding = "VB";
			
			return encoding;
		}
		/// <summary> Locates the member via a dotted name starting at the given id.
		/// It will traverse any and all proto chains if necc. to find the name.
		/// </summary>
		internal virtual Value locate(int startingId, String dottedName, bool traverseProto)
		{
			if (dottedName == null) return null;
			// first rip apart the dottedName
			SupportClass.Tokenizer names = new SupportClass.Tokenizer(dottedName, "."); //$NON-NLS-1$
			Value val = Session.getValue(startingId);
            while (names.HasMoreTokens() && val != null)
            {
                val = locateForNamed(val.Id, names.NextToken(), traverseProto).getValue();
            }
			return val;
		}
Example #42
0
		/// <summary> Constructs a new 'GuardBitsSpec' for the specified number of components
		/// and tiles and the arguments of "-Qguard_bits" option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public GuardBitsSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qguard_bits");
			if (param == null)
			{
				throw new System.ArgumentException("Qguard_bits option not " + "specified");
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			System.Int32 value_Renamed; // value of the guard bits
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					default:  // Step size value
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Bad parameter for " + "-Qguard_bits option" + " : " + word);
						}
						
						if ((float) value_Renamed <= 0.0f)
						{
							throw new System.ArgumentException("Guard bits value " + "must be positive : " + value_Renamed);
						}
						
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					setDefault((System.Object) System.Int32.Parse(pl.DefaultParameterList.getParameter("Qguard_bits")));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Example #43
0
        /// <summary> Creates a new ProgressionSpec object for the specified number of tiles,
        /// components and the ParameterList instance.
        /// 
        /// </summary>
        /// <param name="nt">The number of tiles
        /// 
        /// </param>
        /// <param name="nc">The number of components
        /// 
        /// </param>
        /// <param name="nl">The number of layer
        /// 
        /// </param>
        /// <param name="dls">The number of decomposition levels specifications
        /// 
        /// </param>
        /// <param name="type">the type of the specification module. The ProgressionSpec
        /// class should only be used only with the type ModuleSpec.SPEC_TYPE_TILE.
        /// 
        /// </param>
        /// <param name="pl">The ParameterList instance
        /// 
        /// </param>
        public ProgressionSpec(int nt, int nc, int nl, IntegerSpec dls, byte type, ParameterList pl)
            : base(nt, nc, type)
        {
            System.String param = pl.getParameter("Aptype");
            Progression[] prog;
            int mode = - 1;

            if (param == null)
            {
                // No parameter specified
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }

                if (mode == - 1)
                {
                    System.String errMsg = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg);
                }
                prog = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return ;
            }

            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            byte curSpecType = SPEC_DEF; // Specification type of the
            // current parameter
            bool[] tileSpec = null; // Tiles concerned by the specification
            System.String word = null; // current word
            System.String errMsg2 = null; // Error message
            bool needInteger = false; // True if an integer value is expected
            int intType = 0; // Type of read integer value (0=index of first
            // resolution level, 1= index of first component, 2=index of first
            // layer not included, 3= index of first resolution level not
            // included, 4= index of  first component not included
            System.Collections.Generic.List<Progression> progression = new List<Progression>(10);
            int tmp = 0;
            Progression curProg = null;

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {

                    case 't':
                        // If progression were previously found, store them
                        if (progression.Count > 0)
                        {
                            // Ensure that all information has been taken
                            curProg.ce = nc;
                            curProg.lye = nl;
                            curProg.re = dls.Max + 1;
                            prog = new Progression[progression.Count];
                            progression.CopyTo(prog);
                            if (curSpecType == SPEC_DEF)
                            {
                                setDefault(prog);
                            }
                            else if (curSpecType == SPEC_TILE_DEF)
                            {
                                for (int i = tileSpec.Length - 1; i >= 0; i--)
                                    if (tileSpec[i])
                                    {
                                        setTileDef(i, prog);
                                    }
                            }
                        }
                        progression.Clear();
                        intType = - 1;
                        needInteger = false;

                        // Tiles specification
                        tileSpec = parseIdx(word, nTiles);
                        curSpecType = SPEC_TILE_DEF;
                        break;

                    default:
                        // Here, words is either a Integer (progression bound index)
                        // or a String (progression order type). This is determined by
                        // the value of needInteger.
                        if (needInteger)
                        {
                            // Progression bound info
                            try
                            {
                                tmp = (System.Int32.Parse(word));
                            }
                            catch (System.FormatException e)
                            {
                                // Progression has missing parameters
                                throw new System.ArgumentException("Progression " + "order" + " specification " + "has missing " + "parameters: " + param);
                            }

                            switch (intType)
                            {

                                case 0:  // cs
                                    if (tmp < 0 || tmp > (dls.Max + 1))
                                        throw new System.ArgumentException("Invalid res_start " + "in '-Aptype'" + " option: " + tmp);
                                    curProg.rs = tmp; break;

                                case 1:  // rs
                                    if (tmp < 0 || tmp > nc)
                                    {
                                        throw new System.ArgumentException("Invalid comp_start " + "in '-Aptype' " + "option: " + tmp);
                                    }
                                    curProg.cs = tmp; break;

                                case 2:  // lye
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid layer_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > nl)
                                    {
                                        tmp = nl;
                                    }
                                    curProg.lye = tmp; break;

                                case 3:  // ce
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid res_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > (dls.Max + 1))
                                    {
                                        tmp = dls.Max + 1;
                                    }
                                    curProg.re = tmp; break;

                                case 4:  // re
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid comp_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > nc)
                                    {
                                        tmp = nc;
                                    }
                                    curProg.ce = tmp; break;
                                }

                            if (intType < 4)
                            {
                                intType++;
                                needInteger = true;
                                break;
                            }
                            else if (intType == 4)
                            {
                                intType = 0;
                                needInteger = false;
                                break;
                            }
                            else
                            {
                                throw new System.InvalidOperationException("Error in usage of 'Aptype' " + "option: " + param);
                            }
                        }

                        if (!needInteger)
                        {
                            // Progression type info
                            mode = checkProgMode(word);
                            if (mode == - 1)
                            {
                                errMsg2 = "Unknown progression type : '" + word + "'";
                                throw new System.ArgumentException(errMsg2);
                            }
                            needInteger = true;
                            intType = 0;
                            if (progression.Count == 0)
                            {
                                curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                            }
                            else
                            {
                                curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                            }
                            progression.Add(curProg);
                        }
                        break;

                } // switch
            } // while

            if (progression.Count == 0)
            {
                // No progression defined
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }
                if (mode == - 1)
                {
                    errMsg2 = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg2);
                }
                prog = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return ;
            }

            // Ensure that all information has been taken
            curProg.ce = nc;
            curProg.lye = nl;
            curProg.re = dls.Max + 1;

            // Store found progression
            prog = new Progression[progression.Count];
            progression.CopyTo(prog);

            if (curSpecType == SPEC_DEF)
            {
                setDefault(prog);
            }
            else if (curSpecType == SPEC_TILE_DEF)
            {
                for (int i = tileSpec.Length - 1; i >= 0; i--)
                    if (tileSpec[i])
                    {
                        setTileDef(i, prog);
                    }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, they
                // receive the default progressiveness.
                if (ndefspec != 0)
                {
                    if (pl.getParameter("Rroi") == null)
                    {
                        mode = checkProgMode("res");
                    }
                    else
                    {
                        mode = checkProgMode("layer");
                    }
                    if (mode == - 1)
                    {
                        errMsg2 = "Unknown progression type : '" + param + "'";
                        throw new System.ArgumentException(errMsg2);
                    }
                    prog = new Progression[1];
                    prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                    setDefault(prog);
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {

                        case SPEC_TILE_DEF:
                            for (int c = nc - 1; c >= 0; c--)
                            {
                                if (specValType[0][c] == SPEC_TILE_DEF)
                                    specValType[0][c] = SPEC_DEF;
                            }
                            tileDef[0] = null;
                            break;

                        case SPEC_COMP_DEF:
                            for (int t = nt - 1; t >= 0; t--)
                            {
                                if (specValType[t][0] == SPEC_COMP_DEF)
                                    specValType[t][0] = SPEC_DEF;
                            }
                            compDef[0] = null;
                            break;

                        case SPEC_TILE_COMP:
                            specValType[0][0] = SPEC_DEF;
                            tileCompVal["t0c0"] = null;
                            break;
                        }
                }
            }
        }
Example #44
0
        /// <summary> RFC 2254 filter helper method. Will Parse a filter component.</summary>
        private Asn1Tagged parseFilterComp()
        {
            Asn1Tagged tag = null;
            int filterComp = ft.OpOrAttr;

            switch (filterComp)
            {

                case AND:
                case OR:
                    tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilterList(), false);
                    break;

                case NOT:
                    tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilter(), true);
                    break;

                default:
                    int filterType = ft.FilterType;
                    System.String value_Renamed = ft.Value;

                    switch (filterType)
                    {

                        case GREATER_OR_EQUAL:
                        case LESS_OR_EQUAL:
                        case APPROX_MATCH:
                            tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterType), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
                            break;

                        case EQUALITY_MATCH:
                            if (value_Renamed.Equals("*"))
                            {
                                // present
                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(ft.Attr), false);
                            }
                            else if (value_Renamed.IndexOf((System.Char) '*') != - 1)
                            {
                                // substrings parse:
                                //    [initial], *any*, [final] into an Asn1SequenceOf
                                SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*", true);
            //								SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*");//, true);
                                Asn1SequenceOf seq = new Asn1SequenceOf(5);
                                int tokCnt = sub.Count;
                                int cnt = 0;

                                System.String lastTok = new System.Text.StringBuilder("").ToString();

                                while (sub.HasMoreTokens())
                                {
                                    System.String subTok = sub.NextToken();
                                    cnt++;
                                    if (subTok.Equals("*"))
                                    {
                                        // if previous token was '*', and since the current
                                        // token is a '*', we need to insert 'any'
                                        if (lastTok.Equals(subTok))
                                        {
                                            // '**'
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString("")), false));
                                        }
                                    }
                                    else
                                    {
                                        // value (RfcLdapString)
                                        if (cnt == 1)
                                        {
                                            // initial
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, INITIAL), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                        else if (cnt < tokCnt)
                                        {
                                            // any
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                        else
                                        {
                                            // final
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, FINAL), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                    }
                                    lastTok = subTok;
                                }

                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(ft.Attr), seq), false);
                            }
                            else
                            {
                                // simple
                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EQUALITY_MATCH), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
                            }
                            break;

                        case EXTENSIBLE_MATCH:
                            System.String type = null, matchingRule = null;
                            bool dnAttributes = false;
            //							SupportClass.Tokenizer st = new StringTokenizer(ft.Attr, ":", true);
                            SupportClass.Tokenizer st = new SupportClass.Tokenizer(ft.Attr, ":");//, true);

                            bool first = true;
                            while (st.HasMoreTokens())
                            {
                                System.String s = st.NextToken().Trim();
                                if (first && !s.Equals(":"))
                                {
                                    type = s;
                                }
                                // dn must be lower case to be considered dn of the Entry.
                                else if (s.Equals("dn"))
                                {
                                    dnAttributes = true;
                                }
                                else if (!s.Equals(":"))
                                {
                                    matchingRule = s;
                                }
                                first = false;
                            }

                            tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((System.Object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((System.Object) type == null)?null:new RfcAttributeDescription(type), new RfcAssertionValue(unescapeString(value_Renamed)), (dnAttributes == false)?null:new Asn1Boolean(true)), false);
                            break;
                        }
                    break;

            }
            return tag;
        }
Example #45
0
    private static ArrayList[] predict(System.IO.StreamReader input, System.IO.StreamWriter output, svm_model model, int predict_probability)
    {
        //int correct = 0;
        //int total = 0;
        //double error = 0;
        //double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
        ArrayList[] arrResult = new ArrayList[2];//Mảng thứ 1 chứa kết quả thực sự, mảng thứ 2 chứa kết quả dự đoán
        arrResult[0] = new ArrayList();
        arrResult[1] = new ArrayList();

        int svm_type = svm.svm_get_svm_type(model);
        int nr_class = svm.svm_get_nr_class(model);
        int[] labels = new int[nr_class];
        double[] prob_estimates = null;

        if (predict_probability == 1)
        {
            if (svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
            {
                System.Console.Out.Write("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + svm.svm_get_svr_probability(model) + "\n");
            }
            else
            {
                svm.svm_get_labels(model, labels);
                prob_estimates = new double[nr_class];
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("labels");
                for (int j = 0; j < nr_class; j++)
                {
                    //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                    output.Write(" " + labels[j]);
                }
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("\n");
            }
        }
        #region [Thêm] Lấy thông tin tiền xử lý từ dòng đầu của file test
        System.String strPreprocess = input.ReadLine();
        #endregion

        while (true)
        {
            System.String line = input.ReadLine();
            if ((System.Object)line == null)
                break;

            SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");

            double target = atof(st.NextToken());
            int m = st.Count / 2;
            svm_node[] x = new svm_node[m];
            for (int j = 0; j < m; j++)
            {
                x[j] = new svm_node();
                x[j].index = atoi(st.NextToken());
                x[j].value_Renamed = atof(st.NextToken());
            }

            double v;
            if (predict_probability == 1 && (svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.NU_SVC))
            {
                v = svm.svm_predict_probability(model, x, prob_estimates);
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write(v + " ");
                for (int j = 0; j < nr_class; j++)
                {
                    //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                    output.Write(prob_estimates[j] + " ");
                }
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("\n");
            }
            else
            {
                v = svm.svm_predict(model, x);
                #region [Thêm] Chuyển về dữ liệu nguyên thủy dựa vào cách tiền xử lý
                string[] strItems = strPreprocess.Split(' ');
                double dblMin;
                double dblMax;
                double dblDiff;
                switch (strItems[0])
                {
                    case "ScaleByMinMax":
                        dblMin = Convert.ToDouble(strItems[1]);
                        dblMax = Convert.ToDouble(strItems[2]);
                        dblDiff = dblMax - dblMin;
                        v = v * dblDiff + dblMin;
                        target = target * dblDiff + dblMin;
                        break;
                    default:
                        break;
                }
                #endregion
                arrResult[0].Add(target);
                arrResult[1].Add(v);
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write(target + " " + v + "\n");
            }
            //#region [Thêm] Chuyển về dữ liệu nguyên thủy dựa vào cách tiền xử lý
            //string[] strItems = strPreprocess.Split(' ');
            //switch (strItems[0])
            //{
            //    case "Scale(0,1)":
            //        double dblMin = Convert.ToDouble(strItems[1]);
            //        double dblMax = Convert.ToDouble(strItems[2]);
            //        double dblDiff = dblMax - dblMin;
            //        v = (v - 0.15) * dblDiff / 0.7 + dblMin;
            //        target = (target - 0.15) * dblDiff / 0.7 + dblMin;
            //        break;
            //    default:
            //        break;
            //}
            //#endregion
            //arrResult[0].Add(target);
            //arrResult[1].Add(v);
            //if (v == target)
            //    ++correct;
            //error += (v - target) * (v - target);
            //sumv += v;
            //sumy += target;
            //sumvv += v * v;
            //sumyy += target * target;
            //sumvy += v * target;
            //++total;
        }
        return arrResult;
        //System.Console.Out.Write("Accuracy = " + (double) correct / total * 100 + "% (" + correct + "/" + total + ") (classification)\n");
        //System.Console.Out.Write("Mean squared error = " + error / total + " (regression)\n");
        //System.Console.Out.Write("Squared correlation coefficient = " + ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) / ((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n");
    }
Example #46
0
		/// <summary> Extracts the subtypes from the specified attribute name.
		/// 
		/// For example, if the attribute name is cn;lang-ja;phonetic,
		/// this method returns an array containing lang-ja and phonetic.
		/// 
		/// </summary>
		/// <param name="attrName">  Name of the attribute from which to extract
		/// the subtypes.
		/// 
		/// </param>
		/// <returns> An array subtypes or null if the attribute has none.
		/// 
		/// @throws IllegalArgumentException if attrName is null
		/// </returns>
		public static System.String[] getSubtypes(System.String attrName)
		{
			if ((System.Object) attrName == null)
			{
				throw new System.ArgumentException("Attribute name cannot be null");
			}
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";");
			System.String[] subTypes = null;
			int cnt = st.Count;
			if (cnt > 0)
			{
				st.NextToken(); // skip over basename
				subTypes = new System.String[cnt - 1];
				int i = 0;
				while (st.HasMoreTokens())
				{
					subTypes[i++] = st.NextToken();
				}
			}
			return subTypes;
		}
Example #47
0
		/// <summary> Creates a new PGX file reader from the specified File object.
		/// 
		/// </summary>
		/// <param name="in">The input file as File object.
		/// 
		/// </param>
		/// <exception cref="IOException">If an I/O error occurs.
		/// 
		/// </exception>
		public ImgReaderPGX(System.IO.FileInfo in_Renamed)
		{
			System.String header;
			
			// Check if specified file exists
			bool tmpBool;
			if (System.IO.File.Exists(in_Renamed.FullName))
				tmpBool = true;
			else
				tmpBool = System.IO.Directory.Exists(in_Renamed.FullName);
			if (!tmpBool)
			{
				throw new System.ArgumentException("PGX file " + in_Renamed.Name + " does not exist");
			}
			
			//Opens the given file
			this.in_Renamed = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(in_Renamed, "r");
			try
			{
                System.IO.StreamReader in_reader = new System.IO.StreamReader(this.in_Renamed);
				//UPGRADE_ISSUE: Method 'java.io.RandomAccessFile.readLine' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioRandomAccessFilereadLine'"
				header = in_reader.ReadLine();
			}
			catch (System.IO.IOException)
			{
				throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
			}
			if (header == null)
			{
				throw new System.IO.IOException(in_Renamed.Name + " is an empty file");
			}
			offset = (header.Length + 1);
			
			//Get informations from header
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(header);
			try
			{
				int nTokens = st.Count;
				
				// Magic Number
				if (!(st.NextToken()).Equals("PG"))
					throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				
				// Endianess
				System.String tmp = st.NextToken();
				if (tmp.Equals("LM"))
					byteOrder = CSJ2K.j2k.io.EndianType_Fields.LITTLE_ENDIAN;
				else if (tmp.Equals("ML"))
					byteOrder = CSJ2K.j2k.io.EndianType_Fields.BIG_ENDIAN;
				else
					throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				
				// Unsigned/signed if present in the header
				if (nTokens == 6)
				{
					tmp = st.NextToken();
					if (tmp.Equals("+"))
						isSigned = false;
					else if (tmp.Equals("-"))
						isSigned = true;
					else
						throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				}
				
				// bit-depth, width, height
				try
				{
					bitDepth = (System.Int32.Parse(st.NextToken()));
					// bitDepth must be between 1 and 31
					if ((bitDepth <= 0) || (bitDepth > 31))
						throw new System.IO.IOException(in_Renamed.Name + " is not a valid PGX file");
					
					w = (System.Int32.Parse(st.NextToken()));
					h = (System.Int32.Parse(st.NextToken()));
				}
				catch (System.FormatException)
				{
					throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
				}
			}
			catch (System.ArgumentOutOfRangeException)
			{
				throw new System.IO.IOException(in_Renamed.Name + " is not a PGX file");
			}
			
			// Number of component
			nc = 1;
			
			// Number of bytes per data
			if (bitDepth <= 8)
				packBytes = 1;
			else if (bitDepth <= 16)
				packBytes = 2;
			// <= 31
			else
				packBytes = 4;
		}
Example #48
0
		//*************************************************************************
		// connect methods
		//*************************************************************************
		
		/// <summary> 
		/// Connects to the specified host and port.
		/// 
		/// If this LdapConnection object represents an open connection, the
		/// connection is closed first before the new connection is opened.
		/// At this point, there is no authentication, and any operations are
		/// conducted as an anonymous client.
		/// 
		///  When more than one host name is specified, each host is contacted
		/// in turn until a connection can be established.
		/// 
		/// </summary>
		/// <param name="host">A host name or a dotted string representing the IP address
		/// of a host running an Ldap server. It may also
		/// contain a list of host names, space-delimited. Each host
		/// name can include a trailing colon and port number.
		/// 
		/// </param>
		/// <param name="port">The TCP or UDP port number to connect to or contact.
		/// The default Ldap port is 389. The port parameter is
		/// ignored for any host hame which includes a colon and
		/// port number.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// 
		/// </exception>
		public virtual void  Connect(System.String host, int port)
		{
			// connect doesn't affect other clones
			// If not a clone, destroys old connection.
			// Step through the space-delimited list
			SupportClass.Tokenizer hostList = new SupportClass.Tokenizer(host, " ");
			System.String address = null;
			
			int specifiedPort;
			int colonIndex; //after the colon is the port
			while (hostList.HasMoreTokens())
			{
				try
				{
					specifiedPort = port;
					address = hostList.NextToken();
					colonIndex = address.IndexOf((System.Char) ':');
					if (colonIndex != - 1 && colonIndex + 1 != address.Length)
					{
						//parse Port out of address
						try
						{
							specifiedPort = System.Int32.Parse(address.Substring(colonIndex + 1));
							address = address.Substring(0, (colonIndex) - (0));
						}
						catch (System.Exception e)
						{
							throw new System.ArgumentException(ExceptionMessages.INVALID_ADDRESS);
						}
					}
					// This may return a different conn object
					// Disassociate this clone with the underlying connection.
					conn = conn.destroyClone(true);
					conn.connect(address, specifiedPort);
					break;
				}
				catch (LdapException LE)
				{
					if (!hostList.HasMoreTokens())
						throw LE;
				}
			}
			return ;
		}
Example #49
0
		/// <summary> Creates a ForwardWT object with the specified filters, and with other
		/// options specified in the parameter list 'pl'.
		/// 
		/// </summary>
		/// <param name="src">The source of data to be transformed
		/// 
		/// </param>
		/// <param name="pl">The parameter list (or options).
		/// 
		/// </param>
		/// <param name="kers">The encoder specifications.
		/// 
		/// </param>
		/// <returns> A new ForwardWT object with the specified filters and options
		/// from 'pl'.
		/// 
		/// </returns>
		/// <exception cref="IllegalArgumentException">If mandatory parameters are missing 
		/// or if invalid values are given.
		/// 
		/// </exception>
		public static ForwardWT createInstance(BlkImgDataSrc src, ParameterList pl, EncoderSpecs encSpec)
		{
            int deflev; // defdec removed
			//System.String decompstr;
			//System.String wtstr;
			//System.String pstr;
			//SupportClass.StreamTokenizerSupport stok;
			//SupportClass.Tokenizer strtok;
			//int prefx, prefy; // Partitioning reference point coordinates
			
			// Check parameters
			pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
			
			deflev = ((System.Int32) encSpec.dls.getDefault());
			
			// Code-block partition origin
			System.String str = "";
			if (pl.getParameter("Wcboff") == null)
			{
				throw new System.ApplicationException("You must specify an argument to the '-Wcboff' " + "option. See usage with the '-u' option");
			}
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(pl.getParameter("Wcboff"));
			if (stk.Count != 2)
			{
				throw new System.ArgumentException("'-Wcboff' option needs two" + " arguments. See usage with " + "the '-u' option.");
			}
			int cb0x = 0;
			str = stk.NextToken();
			try
			{
				cb0x = (System.Int32.Parse(str));
			}
			catch (System.FormatException)
			{
				throw new System.ArgumentException("Bad first parameter for the " + "'-Wcboff' option: " + str);
			}
			if (cb0x < 0 || cb0x > 1)
			{
				throw new System.ArgumentException("Invalid horizontal " + "code-block partition origin.");
			}
			int cb0y = 0;
			str = stk.NextToken();
			try
			{
				cb0y = (System.Int32.Parse(str));
			}
			catch (System.FormatException)
			{
				throw new System.ArgumentException("Bad second parameter for the " + "'-Wcboff' option: " + str);
			}
			if (cb0y < 0 || cb0y > 1)
			{
				throw new System.ArgumentException("Invalid vertical " + "code-block partition origin.");
			}
			if (cb0x != 0 || cb0y != 0)
			{
				FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-blocks partition origin is " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may be not supported by all JPEG 2000 " + "decoders.");
			}
			
			return new ForwWTFull(src, encSpec, cb0x, cb0y);
		}
Example #50
0
		/// <summary> Constructs a new 'ForwCompTransfSpec' for the specified number of
		/// components and tiles, the wavelet filters type and the parameter of the
		/// option 'Mct'. This constructor is called by the encoder. It also checks
		/// that the arguments belong to the recognized arguments list.
		/// 
		/// <p>This constructor chose the component transformation type depending
		/// on the wavelet filters : RCT with w5x3 filter and ICT with w9x7
		/// filter. Note: All filters must use the same data type.</p>
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="wfs">The wavelet filter specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public ForwCompTransfSpec(int nt, int nc, byte type, AnWTFilterSpec wfs, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Mct");
			
			if (param == null)
			{
				// The option has not been specified
				
				// If less than three component, do not use any component
				// transformation 
				if (nc < 3)
				{
					setDefault("none");
					return ;
				}
				// If the compression is lossless, uses RCT
				else if (pl.getBooleanParameter("lossless"))
				{
					setDefault("rct");
					return ;
				}
				else
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three first components use the same filters
					bool reject = false;
					for (int c = 1; c < 3; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setDefault("none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setDefault("ict");
						}
						else
						{
							setDefault("rct");
						}
					}
				}
				
				// Each tile receives a component transform specification
				// according the type of wavelet filters that are used by the
				// three first components
				for (int t = 0; t < nt; t++)
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the
			// specification
			//System.Boolean value_Renamed;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						throw new System.ArgumentException("Component specific " + " parameters" + " not allowed with " + "'-Mct' option");
					
					default: 
						if (word.Equals("off"))
						{
							if (curSpecType == SPEC_DEF)
							{
								setDefault("none");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
									if (tileSpec[i])
									{
										setTileDef(i, "none");
									}
							}
						}
						else if (word.Equals("on"))
						{
							if (nc < 3)
							{
								throw new System.ArgumentException("Cannot use component" + " transformation on a " + "image with less than " + "three components");
							}
							
							if (curSpecType == SPEC_DEF)
							{
								// Set arbitrarily the default
								// value to RCT (later will be found the suitable
								// component transform for each tile)
								setDefault("rct");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
								{
									if (tileSpec[i])
									{
										if (getFilterType(i, wfs) == CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3)
										{
											setTileDef(i, "rct");
										}
										else
										{
											setTileDef(i, "ict");
										}
									}
								}
							}
						}
						else
						{
							throw new System.ArgumentException("Default parameter of " + "option Mct not" + " recognized: " + param);
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				// If not, set arbitrarily the default value to 'none' but
				// specifies explicitely a default value for each tile depending
				// on the wavelet transform that is used
				setDefault("none");
				
				for (int t = 0; t < nt; t++)
				{
					if (isTileSpecified(t))
					{
						continue;
					}
					
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
			}
			
			// Check validity of component transformation of each tile compared to
			// the filter used.
			for (int t = nt - 1; t >= 0; t--)
			{
				
				if (((System.String) getTileDef(t)).Equals("none"))
				{
					// No comp. transf is used. No check is needed
					continue;
				}
				else if (((System.String) getTileDef(t)).Equals("rct"))
				{
					// Tile is using Reversible component transform
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // OK
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // Must use ICT
							if (isTileSpecified(t))
							{
								// User has requested RCT -> Error
								throw new System.ArgumentException("Cannot use RCT " + "with 9x7 filter " + "in tile " + t);
							}
							else
							{
								// Specify ICT for this tile
								setTileDef(t, "ict");
							}
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
				else
				{
					// ICT
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // Must use RCT
							if (isTileSpecified(t))
							{
								// User has requested ICT -> Error
								throw new System.ArgumentException("Cannot use ICT " + "with filter 5x3 " + "in tile " + t);
							}
							else
							{
								setTileDef(t, "rct");
							}
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // OK
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
			}
		}
Example #51
0
		/// <summary> Constructs a new 'QuantTypeSpec' for the specified number of components
		/// and tiles and the arguments of "-Qtype" option. This constructor is
		/// called by the encoder.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public QuantTypeSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qtype");
			if (param == null)
			{
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault("reversible");
				}
				else
				{
					setDefault("expounded");
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecValType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						
						if (curSpecValType == SPEC_COMP_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						
						if (curSpecValType == SPEC_TILE_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_COMP_DEF;
						}
						break;
					
					case 'r': 
					// reversible specification
					case 'd': 
					// derived quantization step size specification
					case 'e':  // expounded quantization step size specification
						if (!word.ToUpper().Equals("reversible".ToUpper()) && !word.ToUpper().Equals("derived".ToUpper()) && !word.ToUpper().Equals("expounded".ToUpper()))
						{
							throw new System.ArgumentException("Unknown parameter " + "for " + "'-Qtype' option: " + word);
						}
						
						if (pl.getBooleanParameter("lossless") && (word.ToUpper().Equals("derived".ToUpper()) || word.ToUpper().Equals("expounded".ToUpper())))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "quantization with " + "'-lossless' option");
						}
						
						if (curSpecValType == SPEC_DEF)
						{
							// Default specification
							setDefault(word);
						}
						else if (curSpecValType == SPEC_TILE_DEF)
						{
							// Tile default specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								if (tileSpec[i])
								{
									setTileDef(i, word);
								}
							}
						}
						else if (curSpecValType == SPEC_COMP_DEF)
						{
							// Component default specification 
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, word);
								}
						}
						else
						{
							// Tile-component specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, word);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecValType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Unknown parameter for " + "'-Qtype' option: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, the
				// quantization type is 'reversible' (if '-lossless' is specified)
				// or 'expounded' (if not). 
				if (ndefspec != 0)
				{
					if (pl.getBooleanParameter("lossless"))
					{
						setDefault("reversible");
					}
					else
					{
						setDefault("expounded");
					}
				}
				else
				{
					// All tile-component have been specified, takes arbitrarily
					// the first tile-component value as default and modifies the
					// specification type of all tile-component sharing this
					// value.
					setDefault(getTileCompVal(0, 0));
					
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
		/// <param name="theMessage">an HL7 message from which data are to be queried 
		/// </param>
		/// <param name="theQuery">the query (see class docs for syntax)
		/// </param>
		/// <returns> data from the message that are selected by the query 
		/// </returns>
		public static NuGenMessageQuery.Result query(Message theMessage, System.String theQuery)
		{
			System.Collections.Specialized.NameValueCollection clauses = getClauses(theQuery);
			
			//parse select clause
			SupportClass.Tokenizer select = new SupportClass.Tokenizer(clauses.Get("select"), ", ", false);
			System.Collections.ArrayList fieldPaths = new System.Collections.ArrayList(10);
			System.Collections.Hashtable names = new System.Collections.Hashtable(10);
			while (select.HasMoreTokens())
			{
				System.String token = select.NextToken();
				if (token.Equals("as"))
				{
					if (!select.HasMoreTokens())
					{
						throw new System.ArgumentException("Keyword 'as' must be followed by a field label");
					}
					names[select.NextToken()] = (System.Int32) (fieldPaths.Count - 1);
				}
				else
				{
					fieldPaths.Add(token);
				}
			}
			
			//parse loop clause 
			SupportClass.Tokenizer loop = new SupportClass.Tokenizer(clauses["loop"] == null?"":clauses["loop"], ",", false);
			System.Collections.ArrayList loopPoints = new System.Collections.ArrayList(10);
			System.Collections.Hashtable loopPointNames = new System.Collections.Hashtable(10);
			while (loop.HasMoreTokens())
			{
				System.String pointDecl = loop.NextToken();
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pointDecl, "=", false);
				System.String name = tok.NextToken().Trim();
				System.String path = tok.NextToken().Trim();
				loopPoints.Add(path);
				loopPointNames[name] = (System.Int32) (loopPoints.Count - 1);
			}
			
			//parse where clause 
			//TODO: this will do for now but it should really be evaluated like an expression 
			//rather than a list  
			SupportClass.Tokenizer where = new SupportClass.Tokenizer(clauses["where"] == null?"":clauses["where"], ",", false);
			System.Collections.ArrayList filters = new System.Collections.ArrayList();
			while (where.HasMoreTokens())
			{
				filters.Add(where.NextToken());
			}
			System.String[] filterPaths = new System.String[filters.Count];
			System.String[] filterPatterns = new System.String[filters.Count];
			bool[] exactFlags = new bool[filters.Count];
			
			for (int i = 0; i < filters.Count; i++)
			{
				exactFlags[i] = true;
				System.String filter = (System.String) filters[i];
				System.String[] parts = splitFromEnd(filter, "=");
				if (parts[1] != null)
				{
					parts[1] = parts[1].Substring(1);
				}
				else
				{
					exactFlags[i] = false;
					parts = splitFromEnd(filter, "like");
					parts[1] = parts[1].Substring(4);
				}
				filterPaths[i] = parts[0].Trim();
				parts[1] = parts[1].Trim();
				filterPatterns[i] = parts[1].Substring(1, (parts[1].Length - 1) - (1));
			}

            String[] retVal1 = new String[loopPoints.Count];
            loopPoints.CopyTo(retVal1);

            String[] retVal2 = new String[fieldPaths.Count];
            fieldPaths.CopyTo(retVal2);

			return new ResultImpl(theMessage, retVal1, loopPointNames, retVal2, names, filterPaths, filterPatterns, exactFlags);
		}
Example #53
0
	// read in a problem (in svmlight format)
	
	private void  read_problem()
	{
		/* UPGRADE_TODO: Expected value of parameters of constructor
		 * 'java.io.BufferedReader.BufferedReader' are different in the equivalent in .NET.
		 * 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092"'
		 */
		System.IO.StreamReader fp = new System.IO.StreamReader(input_file_name);
		System.Collections.ArrayList vy = new System.Collections.ArrayList(10);
		System.Collections.ArrayList vx = new System.Collections.ArrayList(10);
		int max_index = 0;
		
		while (true)
		{
			System.String line = fp.ReadLine();
			if ((System.Object) line == null)
				break;
			
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");
			
			vy.Add(st.NextToken());
			int m = st.Count / 2;
			svm_node[] x = new svm_node[m];
			for (int j = 0; j < m; j++)
			{
				x[j] = new svm_node();
				x[j].index = atoi(st.NextToken());
				x[j].value_Renamed = atof(st.NextToken());
			}
			if (m > 0)
				max_index = System.Math.Max(max_index, x[m - 1].index);
			vx.Add(x);
		}
		
		prob = new svm_problem();
		prob.l = vy.Count;
		prob.x = new svm_node[prob.l][];
		for (int i = 0; i < prob.l; i++)
			prob.x[i] = (svm_node[]) vx[i];
		prob.y = new double[prob.l];
		for (int i = 0; i < prob.l; i++)
			prob.y[i] = atof((System.String) vy[i]);
		
		if (param.gamma == 0)
			param.gamma = 1.0 / max_index;
		
		fp.Close();
	}
			//extracts LP# of label between first '{' and first '}', or -1 if there isn't one
			private int getLoopPointReference(System.String thePath)
			{
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePath, "{}", false);
				if (thePath.IndexOf('{') >= 0 && tok.HasMoreTokens())
				{
					System.String ref_Renamed = tok.NextToken();
					return ((System.Int32) myLoopPointNames[ref_Renamed]);
				}
				else
				{
					return - 1;
				}
			}
Example #55
0
        public static svm_model svm_load_model(System.String model_file_name)
        {
            //UPGRADE_TODO: The differences in the expected value  of parameters for constructor 'java.io.BufferedReader.BufferedReader'  may cause compilation errors.  'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092_3"'
            //UPGRADE_WARNING: At least one expression was used more than once in the target code. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1181_3"'
            //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_3"'
            /*Original System.IO.StreamReader fp = new System.IO.StreamReader(new System.IO.StreamReader(model_file_name, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(model_file_name, System.Text.Encoding.Default).CurrentEncoding);*/
            System.IO.StreamReader fp = new System.IO.StreamReader(new System.IO.FileStream(model_file_name, System.IO.FileMode.Open));

            // read parameters

            svm_model model = new svm_model();
            svm_parameter param = new svm_parameter();
            model.param = param;
            model.rho = null;
            model.probA = null;
            model.probB = null;
            model.label = null;
            model.nSV = null;

            while (true)
            {
                System.String cmd = fp.ReadLine();
                System.String arg = cmd.Substring(cmd.IndexOf((System.Char) ' ') + 1);

                if (cmd.StartsWith("svm_type"))
                {
                    int i;
                    for (i = 0; i < svm_type_table.Length; i++)
                    {
                        if (arg.IndexOf(svm_type_table[i]) != - 1)
                        {
                            param.svm_type = i;
                            break;
                        }
                    }
                    if (i == svm_type_table.Length)
                    {
                        System.Console.Error.Write("unknown svm type.\n");
                        return null;
                    }
                }
                else if (cmd.StartsWith("kernel_type"))
                {
                    int i;
                    for (i = 0; i < kernel_type_table.Length; i++)
                    {
                        if (arg.IndexOf(kernel_type_table[i]) != - 1)
                        {
                            param.kernel_type = i;
                            break;
                        }
                    }
                    if (i == kernel_type_table.Length)
                    {
                        System.Console.Error.Write("unknown kernel function.\n");
                        return null;
                    }
                }
                else if (cmd.StartsWith("degree"))
                    param.degree = atof(arg);
                else if (cmd.StartsWith("gamma"))
                    param.gamma = atof(arg);
                else if (cmd.StartsWith("coef0"))
                    param.coef0 = atof(arg);
                else if (cmd.StartsWith("nr_class"))
                    model.nr_class = atoi(arg);
                else if (cmd.StartsWith("total_sv"))
                    model.l = atoi(arg);
                else if (cmd.StartsWith("rho"))
                {
                    int n = model.nr_class * (model.nr_class - 1) / 2;
                    model.rho = new double[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.rho[i] = atof(st.NextToken());
                }
                else if (cmd.StartsWith("label"))
                {
                    int n = model.nr_class;
                    model.label = new int[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.label[i] = atoi(st.NextToken());
                }
                else if (cmd.StartsWith("probA"))
                {
                    int n = model.nr_class * (model.nr_class - 1) / 2;
                    model.probA = new double[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.probA[i] = atof(st.NextToken());
                }
                else if (cmd.StartsWith("probB"))
                {
                    int n = model.nr_class * (model.nr_class - 1) / 2;
                    model.probB = new double[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.probB[i] = atof(st.NextToken());
                }
                else if (cmd.StartsWith("nr_sv"))
                {
                    int n = model.nr_class;
                    model.nSV = new int[n];
                    SupportClass.Tokenizer st = new SupportClass.Tokenizer(arg);
                    for (int i = 0; i < n; i++)
                        model.nSV[i] = atoi(st.NextToken());
                }
                else if (cmd.StartsWith("SV"))
                {
                    break;
                }
                else
                {
                    System.Console.Error.Write("unknown text in model file\n");
                    return null;
                }
            }

            // read sv_coef and SV

            int m = model.nr_class - 1;
            int l = model.l;
            model.sv_coef = new double[m][];
            for (int i = 0; i < m; i++)
            {
                model.sv_coef[i] = new double[l];
            }
            model.SV = new svm_node[l][];

            for (int i = 0; i < l; i++)
            {
                System.String line = fp.ReadLine();
                SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");

                for (int k = 0; k < m; k++)
                    model.sv_coef[k][i] = atof(st.NextToken());
                int n = st.Count / 2;
                model.SV[i] = new svm_node[n];
                for (int j = 0; j < n; j++)
                {
                    model.SV[i][j] = new svm_node();
                    model.SV[i][j].index = atoi(st.NextToken());
                    model.SV[i][j].value = atof(st.NextToken());
                }
            }

            fp.Close();
            return model;
        }
Example #56
0
        /// <summary> Write COM marker segment(s) to the codestream.
        /// 
        /// <p>This marker is currently written in main header and indicates the
        /// JJ2000 encoder's version that has created the codestream.</p>
        /// 
        /// </summary>
        private void writeCOM()
        {
            // JJ2000 COM marker segment
            if (enJJ2KMarkSeg)
            {
                System.String str = "Created by: CSJ2K version " + JJ2KInfo.version;
                int markSegLen; // the marker segment length

                // COM marker
                hbuf.Write((System.Int16) CSJ2K.j2k.codestream.Markers.COM);

                // Calculate length: Lcom(2) + Rcom (2) + string's length;
                markSegLen = 2 + 2 + str.Length;
                hbuf.Write((System.Int16) markSegLen);

                // Rcom
                hbuf.Write((System.Int16) 1); // General use (IS 8859-15:1999(Latin) values)

                byte[] chars = System.Text.Encoding.UTF8.GetBytes(str);
                for (int i = 0; i < chars.Length; i++)
                {
                    hbuf.Write((byte) chars[i]);
                }
            }
            // other COM marker segments
            if (otherCOMMarkSeg != null)
            {
                SupportClass.Tokenizer stk = new SupportClass.Tokenizer(otherCOMMarkSeg, "#");
                while (stk.HasMoreTokens())
                {
                    System.String str = stk.NextToken();
                    int markSegLen; // the marker segment length

                    // COM marker
                    hbuf.Write((System.Int16) CSJ2K.j2k.codestream.Markers.COM);

                    // Calculate length: Lcom(2) + Rcom (2) + string's length;
                    markSegLen = 2 + 2 + str.Length;
                    hbuf.Write((System.Int16) markSegLen);

                    // Rcom
                    hbuf.Write((System.Int16) 1); // General use (IS 8859-15:1999(Latin)
                    // values)

                    byte[] chars = System.Text.Encoding.UTF8.GetBytes(str);
                    for (int i = 0; i < chars.Length; i++)
                    {
                        hbuf.Write((byte) chars[i]);
                    }
                }
            }
        }
	private static void  predict(System.IO.StreamReader input, System.IO.BinaryWriter output, svm_model model, int predict_probability)
	{
		int correct = 0;
		int total = 0;
		double error = 0;
		double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
		
		int svm_type = svm.svm_get_svm_type(model);
		int nr_class = svm.svm_get_nr_class(model);
		int[] labels = new int[nr_class];
		double[] prob_estimates = null;
		
		if (predict_probability == 1)
		{
			if (svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
			{
				System.Console.Out.Write("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + svm.svm_get_svr_probability(model) + "\n");
			}
			else
			{
				svm.svm_get_labels(model, labels);
				prob_estimates = new double[nr_class];
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("labels");
				for (int j = 0; j < nr_class; j++)
				{
					//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
					output.Write(" " + labels[j]);
				}
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("\n");
			}
		}
		while (true)
		{
			System.String line = input.ReadLine();
			if ((System.Object) line == null)
				break;
			
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");
			
			double target = atof(st.NextToken());
			int m = st.Count / 2;
			svm_node[] x = new svm_node[m];
			for (int j = 0; j < m; j++)
			{
				x[j] = new svm_node();
				x[j].index = atoi(st.NextToken());
				x[j].value_Renamed = atof(st.NextToken());
			}
			
			double v;
			if (predict_probability == 1 && (svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.NU_SVC))
			{
				v = svm.svm_predict_probability(model, x, prob_estimates);
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write(v + " ");
				for (int j = 0; j < nr_class; j++)
				{
					//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
					output.Write(prob_estimates[j] + " ");
				}
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write("\n");
			}
			else
			{
				v = svm.svm_predict(model, x);
				//UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
				output.Write(v + "\n");
			}
			
			if (v == target)
				++correct;
			error += (v - target) * (v - target);
			sumv += v;
			sumy += target;
			sumvv += v * v;
			sumyy += target * target;
			sumvy += v * target;
			++total;
		}
		System.Console.Out.Write("Accuracy = " + (double) correct / total * 100 + "% (" + correct + "/" + total + ") (classification)\n");
		System.Console.Out.Write("Mean squared error = " + error / total + " (regression)\n");
		System.Console.Out.Write("Squared correlation coefficient = " + ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) / ((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n");
	}
		/// <summary> Splits the given composite string into an array of components using the given
		/// delimiter.
		/// </summary>
		public static System.String[] split(System.String composite, System.String delim)
		{
			System.Collections.ArrayList components = new System.Collections.ArrayList();
			
			//defend against evil nulls
			if (composite == null)
				composite = "";
			if (delim == null)
				delim = "";
			
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(composite, delim, true);
			bool previousTokenWasDelim = true;
			while (tok.HasMoreTokens())
			{
				System.String thisTok = tok.NextToken();
				if (thisTok.Equals(delim))
				{
					if (previousTokenWasDelim)
						components.Add(null);
					previousTokenWasDelim = true;
				}
				else
				{
					components.Add(thisTok);
					previousTokenWasDelim = false;
				}
			}
			
			System.String[] ret = new System.String[components.Count];
			for (int i = 0; i < components.Count; i++)
			{
				ret[i] = ((System.String) components[i]);
			}
			
			return ret;
		}
Example #59
0
		/// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles
		/// and components and the ParameterList instance.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl):base(nt, nc, type)
		{
			
			this.dls = dls;
			
			// The precinct sizes are stored in a 2 elements vector array, the
			// first element containing a vector for the precincts width for each
			// resolution level and the second element containing a vector for the
			// precincts height for each resolution level. The precincts sizes are
			// specified from the highest resolution level to the lowest one
			// (i.e. 0).  If there are less elements than the number of
			// decomposition levels, the last element is used for all remaining
			// resolution levels (i.e. if the precincts sizes are specified only
			// for resolutions levels 5, 4 and 3, then the precincts size for
			// resolution levels 2, 1 and 0 will be the same as the size used for
			// resolution level 3).
			
			// Boolean used to know if we were previously reading a precinct's 
			// size or if we were reading something else.
			bool wasReadingPrecinctSize = false;
			
			System.String param = pl.getParameter(optName);
			
			// Set precinct sizes to default i.e. 2^15 =
			// Markers.PRECINCT_PARTITION_DEF_SIZE
			System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2];
			tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
			tmpv[0].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
			tmpv[1].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			setDefault(tmpv);
			
			if (param == null)
			{
				// No precinct size specified in the command line so we do not try 
				// to parse it.
				return ;
			}
			
			// Precinct partition is used : parse arguments
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
            int ci, ti; //i, xIdx removed
			
			bool endOfParamList = false;
			System.String word = null; // current word
			System.Int32 w, h;
			System.String errMsg = null;
			
			while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList)
			{
				
				System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy
				
				// We do not read the next token if we were reading a precinct's
				// size argument as we have already read the next token into word.
				if (!wasReadingPrecinctSize)
				{
					word = stk.NextToken();
				}
				
				wasReadingPrecinctSize = false;
				
				switch (word[0])
				{
					
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					
					default: 
						if (!System.Char.IsDigit(word[0]))
						{
							errMsg = "Bad construction for parameter: " + word;
							throw new System.ArgumentException(errMsg);
						}
						
						// Initialises Vector objects
						v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
						v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
						
						while (true)
						{
							
							// Now get the precinct dimensions
							try
							{
								// Get precinct width
								w = System.Int32.Parse(word);
								
								// Get next word in argument list
								try
								{
									word = stk.NextToken();
								}
								catch (System.ArgumentOutOfRangeException)
								{
									errMsg = "'" + optName + "' option : could not " + "parse the precinct's width";
									throw new System.ArgumentException(errMsg);
								}
								// Get precinct height
								h = System.Int32.Parse(word);
								if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h)))
								{
									errMsg = "Precinct dimensions must be powers of 2";
									throw new System.ArgumentException(errMsg);
								}
							}
							catch (System.FormatException)
							{
								errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed.";
								throw new System.ArgumentException(errMsg);
							}
							// Store packet's dimensions in Vector arrays
							v[0].Add(w);
							v[1].Add(h);
							
							// Try to get the next token
							if (stk.HasMoreTokens())
							{
								word = stk.NextToken();
								if (!System.Char.IsDigit(word[0]))
								{
									// The next token does not start with a digit so
									// it is not a precinct's size argument. We set
									// the wasReadingPrecinctSize booleen such that we
									// know that we don't have to read another token
									// and check for the end of the parameters list.
									wasReadingPrecinctSize = true;
									
									if (curSpecType == SPEC_DEF)
									{
										setDefault(v);
									}
									else if (curSpecType == SPEC_TILE_DEF)
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											if (tileSpec[ti])
											{
												setTileDef(ti, v);
											}
										}
									}
									else if (curSpecType == SPEC_COMP_DEF)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (compSpec[ci])
											{
												setCompDef(ci, v);
											}
										}
									}
									else
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											for (ci = compSpec.Length - 1; ci >= 0; ci--)
											{
												if (tileSpec[ti] && compSpec[ci])
												{
													setTileCompVal(ti, ci, v);
												}
											}
										}
									}
									// Re-initialize
									curSpecType = SPEC_DEF;
									tileSpec = null;
									compSpec = null;
									
									// Go back to 'normal' parsing
									break;
								}
								else
								{
									// Next token starts with a digit so read it
								}
							}
							else
							{
								// We have reached the end of the parameters list so
								// we store the last precinct's sizes and we stop
								if (curSpecType == SPEC_DEF)
								{
									setDefault(v);
								}
								else if (curSpecType == SPEC_TILE_DEF)
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										if (tileSpec[ti])
										{
											setTileDef(ti, v);
										}
									}
								}
								else if (curSpecType == SPEC_COMP_DEF)
								{
									for (ci = compSpec.Length - 1; ci >= 0; ci--)
									{
										if (compSpec[ci])
										{
											setCompDef(ci, v);
										}
									}
								}
								else
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (tileSpec[ti] && compSpec[ci])
											{
												setTileCompVal(ti, ci, v);
											}
										}
									}
								}
								endOfParamList = true;
								break;
							}
						} // while (true)
						break;
					
				} // switch
			} // while
		}
		/// <summary> Returns the query portion of the URL, broken up into individual key/value
		/// pairs. Does NOT unescape the keys and values.
		/// </summary>
		public virtual LinkedHashMap getParameterMap()
		{
            LinkedHashMap map;
			
			SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(Query, "?&"); //$NON-NLS-1$
			// multiply by 2 to create a sufficiently large HashMap
			map = new LinkedHashMap(tokens.Count * 2);
			
			while (tokens.HasMoreTokens())
			{
				String nameValuePair = tokens.NextToken();
				String name = nameValuePair;
				String value = ""; //$NON-NLS-1$
				int equalsIndex = nameValuePair.IndexOf('=');
				if (equalsIndex != - 1)
				{
					name = nameValuePair.Substring(0, (equalsIndex) - (0));
					if (name.Length > 0)
					{
						value = nameValuePair.Substring(equalsIndex + 1);
					}
				}
				map.Add(name, value);
			}
			
			return map;
		}