public void StringIsTokenizedWithSpecifiedDelimiters() { const string toTokenize = "First,Second,Third"; StringTokenizer tokenizer = new StringTokenizer(toTokenize, ","); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("First", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Second", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Third", tokenizer.NextToken()); Assert.IsFalse(tokenizer.HasMoreTokens()); }
public void RepeatedStringIsTokenizedCorrectly() { const string toTokenize = "First\tFirstly\tThird"; StringTokenizer tokenizer = new StringTokenizer(toTokenize); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("First", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Firstly", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Third", tokenizer.NextToken()); Assert.IsFalse(tokenizer.HasMoreTokens()); }
public void ChangingDelimitersIsHandledCorrectly() { const string toTokenize = "First,more\tSecond,Third"; StringTokenizer tokenizer = new StringTokenizer(toTokenize); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("First,more", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Second", tokenizer.NextToken(",")); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Third", tokenizer.NextToken()); Assert.IsFalse(tokenizer.HasMoreTokens()); }
public void StringIsTokenizedWithDefaultDelimiters() { const string toTokenize = "First\tSecond\tThird"; StringTokenizer tokenizer = new StringTokenizer(toTokenize); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("First", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Second", tokenizer.NextToken()); Assert.IsTrue(tokenizer.HasMoreTokens()); Assert.AreEqual("Third", tokenizer.NextToken()); Assert.IsFalse(tokenizer.HasMoreTokens()); }
internal NameServiceClient(int lport, IPAddress laddr) { this._lport = lport; this.laddr = laddr ?? Config.GetLocalHost() ?? Extensions.GetLocalAddresses()?.FirstOrDefault(); if (this.laddr == null) throw new ArgumentNullException("IPAddress NOT found. if exec on localhost, set vallue to [jcifs.smb.client.laddr]"); try { Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255")); } catch (Exception ex) { } _sndBuf = new byte[SndBufSize]; _rcvBuf = new byte[RcvBufSize]; if (string.IsNullOrEmpty(Ro)) { if (NbtAddress.GetWinsAddress() == null) { _resolveOrder = new int[2]; _resolveOrder[0] = ResolverLmhosts; _resolveOrder[1] = ResolverBcast; } else { _resolveOrder = new int[3]; _resolveOrder[0] = ResolverLmhosts; _resolveOrder[1] = ResolverWins; _resolveOrder[2] = ResolverBcast; } } else { int[] tmp = new int[3]; StringTokenizer st = new StringTokenizer(Ro, ","); int i = 0; while (st.HasMoreTokens()) { string s = st.NextToken().Trim(); if (Runtime.EqualsIgnoreCase(s, "LMHOSTS")) { tmp[i++] = ResolverLmhosts; } else { if (Runtime.EqualsIgnoreCase(s, "WINS")) { if (NbtAddress.GetWinsAddress() == null) { if (_log.Level > 1) { _log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"); } continue; } tmp[i++] = ResolverWins; } else { if (Runtime.EqualsIgnoreCase(s, "BCAST")) { tmp[i++] = ResolverBcast; } else { if (Runtime.EqualsIgnoreCase(s, "DNS")) { } else { // skip if (_log.Level > 1) { _log.WriteLine("unknown resolver method: " + s); } } } } } } _resolveOrder = new int[i]; Array.Copy(tmp, 0, _resolveOrder, 0, i); } }
internal void MergeField(String name, AcroFields.Item item) { Dictionary <string, object> map = fieldTree; StringTokenizer tk = new StringTokenizer(name, "."); if (!tk.HasMoreTokens()) { return; } while (true) { String s = tk.NextToken(); Object obj; map.TryGetValue(s, out obj); if (tk.HasMoreTokens()) { if (obj == null) { obj = new Dictionary <string, object>(); map[s] = obj; map = (Dictionary <string, object>)obj; continue; } else if (obj is Dictionary <string, object> ) { map = (Dictionary <string, object>)obj; } else { return; } } else { if (obj is Dictionary <string, object> ) { return; } PdfDictionary merged = item.GetMerged(0); if (obj == null) { PdfDictionary field = new PdfDictionary(); if (PdfName.SIG.Equals(merged.Get(PdfName.FT))) { hasSignature = true; } foreach (PdfName key in merged.Keys) { if (fieldKeys.ContainsKey(key)) { field.Put(key, merged.Get(key)); } } List <object> list = new List <object>(); list.Add(field); CreateWidgets(list, item); map[s] = list; } else { List <object> list = (List <object>)obj; PdfDictionary field = (PdfDictionary)list[0]; PdfName type1 = (PdfName)field.Get(PdfName.FT); PdfName type2 = (PdfName)merged.Get(PdfName.FT); if (type1 == null || !type1.Equals(type2)) { return; } int flag1 = 0; PdfObject f1 = field.Get(PdfName.FF); if (f1 != null && f1.IsNumber()) { flag1 = ((PdfNumber)f1).IntValue; } int flag2 = 0; PdfObject f2 = merged.Get(PdfName.FF); if (f2 != null && f2.IsNumber()) { flag2 = ((PdfNumber)f2).IntValue; } if (type1.Equals(PdfName.BTN)) { if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0) { return; } if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0) { return; } } else if (type1.Equals(PdfName.CH)) { if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0) { return; } } CreateWidgets(list, item); } return; } } }
/// <summary> /// Gives you a BaseColor based on a name. /// </summary> /// <param name="name">a name such as black, violet, cornflowerblue or #RGB or #RRGGBB or RGB or RRGGBB or rgb(R,G,B)</param> /// <returns>the corresponding BaseColor object. Never returns null. @throws IllegalArgumentException if the String isn't a know representation of a color.</returns> public static BaseColor GetRGBColor(String name) { int[] color = { 0, 0, 0, 255 }; String colorName = name.ToLower(); bool colorStrWithoutHash = MissingHashColorFormat(colorName); if (colorName.StartsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { // lop off the # to unify hex parsing. colorName = colorName.Substring(1); } if (colorName.Length == 3) { String red = colorName.Substring(0, 1); color[0] = int.Parse(red + red, NumberStyles.HexNumber); String green = colorName.Substring(1, 1); color[1] = int.Parse(green + green, NumberStyles.HexNumber); String blue = colorName.Substring(2); color[2] = int.Parse(blue + blue, NumberStyles.HexNumber); return(new BaseColor(color[0], color[1], color[2], color[3])); } if (colorName.Length == 6) { color[0] = int.Parse(colorName.Substring(0, 2), NumberStyles.HexNumber); color[1] = int.Parse(colorName.Substring(2, 2), NumberStyles.HexNumber); color[2] = int.Parse(colorName.Substring(4), NumberStyles.HexNumber); return(new BaseColor(color[0], color[1], color[2], color[3])); } throw new FormatException( MessageLocalization .GetComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } if (colorName.StartsWith("rgb(")) { String delim = "rgb(), \t\r\n\f"; StringTokenizer tok = new StringTokenizer(colorName, delim); for (int k = 0; k < 3; ++k) { if (tok.HasMoreTokens()) { color[k] = GetRGBChannelValue(tok.NextToken()); color[k] = Math.Max(0, color[k]); color[k] = Math.Min(255, color[k]); } } return(new BaseColor(color[0], color[1], color[2], color[3])); } if (colorName.StartsWith("rgba(")) { const String delim = "rgba(), \t\r\n\f"; StringTokenizer tok = new StringTokenizer(colorName, delim); for (int k = 0; k < 3; ++k) { if (tok.HasMoreTokens()) { color[k] = GetRGBChannelValue(tok.NextToken()); color[k] = Math.Max(0, color[k]); color[k] = Math.Min(255, color[k]); } } if (tok.HasMoreTokens()) { color[3] = (int)(255 * float.Parse(tok.NextToken()) + 0.5); } return(new BaseColor(color[0], color[1], color[2], color[3])); } if (!NAMES.ContainsKey(colorName)) { throw new FormatException( MessageLocalization.GetComposedMessage("color.not.found", new String[] { colorName })); } color = NAMES[colorName]; return(new BaseColor(color[0], color[1], color[2], color[3])); }
/// <summary>The main method, which is essentially the same as in CRFClassifier.</summary> /// <remarks>The main method, which is essentially the same as in CRFClassifier. See the class documentation.</remarks> /// <exception cref="System.Exception"/> public static void Main(string[] args) { StringUtils.LogInvocationString(log, args); Properties props = StringUtils.ArgsToProperties(args); CRFBiasedClassifier <CoreLabel> crf = new CRFBiasedClassifier <CoreLabel>(props); string testFile = crf.flags.testFile; string loadPath = crf.flags.loadClassifier; if (loadPath != null) { crf.LoadClassifierNoExceptions(loadPath, props); } else { if (crf.flags.loadJarClassifier != null) { // legacy support of old option crf.LoadClassifierNoExceptions(crf.flags.loadJarClassifier, props); } else { crf.LoadDefaultClassifier(); } } if (crf.flags.classBias != null) { StringTokenizer biases = new StringTokenizer(crf.flags.classBias, ","); while (biases.HasMoreTokens()) { StringTokenizer bias = new StringTokenizer(biases.NextToken(), ":"); string cname = bias.NextToken(); double w = double.Parse(bias.NextToken()); crf.SetBiasWeight(cname, w); log.Info("Setting bias for class " + cname + " to " + w); } } if (testFile != null) { IDocumentReaderAndWriter <CoreLabel> readerAndWriter = crf.MakeReaderAndWriter(); if (crf.flags.printFirstOrderProbs) { crf.PrintFirstOrderProbs(testFile, readerAndWriter); } else { if (crf.flags.printProbs) { crf.PrintProbs(testFile, readerAndWriter); } else { if (crf.flags.useKBest) { int k = crf.flags.kBest; crf.ClassifyAndWriteAnswersKBest(testFile, k, readerAndWriter); } else { crf.ClassifyAndWriteAnswers(testFile, readerAndWriter, true); } } } } }
/// <summary> /// Create Field Value Object /// </summary> /// <param name="ctx">context</param> /// <param name="WindowNo">window number</param> /// <param name="TabNo">tab number</param> /// <param name="AD_Window_ID">window Id</param> /// <param name="AD_Tab_ID">Tab Id</param> /// <param name="readOnly">is readonly</param> /// <param name="dr">datarow</param> /// <returns>object of this Class</returns> public static GridFieldVO Create(Ctx ctx, int windowNo, int tabNo, int AD_Window_ID, int AD_Tab_ID, bool readOnly, IDataReader dr) { GridFieldVO vo = new GridFieldVO(ctx, windowNo, tabNo, AD_Window_ID, AD_Tab_ID, readOnly); String columnName = "ColumnName"; try { vo.ColumnName = dr["ColumnName"].ToString(); if (vo.ColumnName == null || columnName.Trim().Length == 0) { return(null); } // VLogger.Get().Fine(vo.ColumnName); //ResultSetMetaData rsmd = dr.getMetaData(); for (int i = 0; i < dr.FieldCount; i++) { columnName = dr.GetName(i).ToUpper();// rsmd.getColumnName(i); if (columnName.Equals("NAME")) { vo.Header = dr[i].ToString(); } else if (columnName.Equals("AD_REFERENCE_ID")) { vo.displayType = Utility.Util.GetValueOfInt(dr[i]);// Utility.Util.GetValueOfInt(dr[i]) } else if (columnName.Equals("AD_COLUMN_ID")) { vo.AD_Column_ID = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("AD_INFOWINDOW_ID")) { vo.AD_InfoWindow_ID = Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("AD_TABLE_ID")) { vo.AD_Table_ID = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("DISPLAYLENGTH")) { vo.DisplayLength = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("ISSAMELINE")) { vo.IsSameLine = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISDISPLAYED")) { vo.IsDisplayedf = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("MRISDISPLAYED")) { vo.IsDisplayedMR = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("DISPLAYLOGIC")) { vo.DisplayLogic = dr[i].ToString(); } else if (columnName.Equals("DEFAULTVALUE")) { vo.DefaultValue = dr[i].ToString(); } else if (columnName.Equals("ISMANDATORYUI")) { vo.IsMandatoryUI = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISREADONLY")) { vo.IsReadOnly = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISUPDATEABLE")) { vo.IsUpdateable = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISALWAYSUPDATEABLE")) { vo.IsAlwaysUpdateable = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISHEADING")) { vo.IsHeading = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISFIELDONLY")) { vo.IsFieldOnly = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISENCRYPTEDFIELD")) { vo.IsEncryptedField = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISENCRYPTEDCOLUMN")) { vo.IsEncryptedColumn = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISSELECTIONCOLUMN")) { vo.IsSelectionColumn = "Y".Equals(dr[i].ToString()); } //else if (columnName.Equals("ISINCLUDEDCOLUMN")) // vo.IsIncludedColumn = "Y".Equals(dr[i].ToString()); else if (columnName.Equals("SELECTIONSEQNO")) { vo.SelectionSeqNo = Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("SORTNO")) { vo.SortNo = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("FIELDLENGTH")) { vo.FieldLength = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("VFORMAT")) { vo.VFormat = dr[i].ToString(); } else if (columnName.Equals("VALUEMIN")) { vo.ValueMin = dr[i].ToString(); } else if (columnName.Equals("VALUEMAX")) { vo.ValueMax = dr[i].ToString(); } else if (columnName.Equals("FIELDGROUP")) { vo.FieldGroup = Env.TrimModulePrefix(dr[i].ToString()); } else if (columnName.Equals("ISKEY")) { vo.IsKey = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("ISPARENT")) { vo.IsParent = "Y".Equals(dr[i].ToString()); } else if (columnName.Equals("DESCRIPTION")) { vo.Description = dr[i].ToString(); } else if (columnName.Equals("HELP")) { vo.Help = dr[i].ToString(); } else if (columnName.Equals("CALLOUT")) { vo.Callout = dr[i].ToString(); if (!string.IsNullOrEmpty(vo.Callout)) { Tuple <string, string, string> tpl = null; StringTokenizer st = new StringTokenizer(vo.Callout, ";,", false); StringBuilder callouts = new StringBuilder(); bool hasModulePrefix = Env.HasModulePrefix(vo.ColumnName, out tpl); while (st.HasMoreTokens()) // for each callout { string prefix = ""; String cmd = st.NextToken().Trim(); if (hasModulePrefix) { prefix = vo.ColumnName.Substring(0, vo.ColumnName.IndexOf('_')); } else { String className = cmd.Substring(0, cmd.LastIndexOf(".")); className = className.Remove(0, className.LastIndexOf(".") + 1); if (Env.HasModulePrefix(className, out tpl)) { prefix = className.Substring(0, className.IndexOf('_')); } } if (callouts.Length > 0) { if (prefix.Length > 0) { callouts.Append(";").Append(cmd.Replace("ViennaAdvantage", prefix)); } else { callouts.Append(";").Append(cmd); } } else { if (prefix.Length > 0) { callouts.Append(cmd.Replace("ViennaAdvantage", prefix)); } else { callouts.Append(";").Append(cmd); } } } vo.Callout = callouts.ToString(); } } else if (columnName.Equals("AD_PROCESS_ID")) { vo.AD_Process_ID = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("AD_FORM_ID")) { vo.AD_Form_ID = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("READONLYLOGIC")) { vo.ReadOnlyLogic = dr[i].ToString(); } else if (columnName.Equals("MANDATORYLOGIC")) { vo.mandatoryLogic = dr[i].ToString(); } else if (columnName.Equals("OBSCURETYPE")) { vo.ObscureType = dr[i].ToString(); } else if (columnName.Equals("ISDEFAULTFOCUS")) { vo.IsDefaultFocus = "Y".Equals(dr[i].ToString()); } // else if (columnName.Equals("AD_REFERENCE_VALUE_ID")) { vo.AD_Reference_Value_ID = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("VALIDATIONCODE")) { vo.ValidationCode = dr[i].ToString(); } else if (columnName.Equals("COLUMNSQL")) { vo.ColumnSQL = dr[i].ToString(); } else if (columnName.Equals("AD_FIELD_ID")) { vo.AD_Field_ID = Utility.Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("MOBILELISTINGFORMAT")) { vo.MobileListingFormat = Utility.Util.GetValueOfString(dr[i]); } else if (columnName.Equals("MRSEQNO")) { int mrseq = Util.GetValueOfInt(dr[i]); if (mrseq > 0) { vo.mrSeqNo = mrseq; } } else if (columnName.Equals("ZOOMWINDOW_ID")) { vo.ZoomWindow_ID = Util.GetValueOfInt(dr[i]); } else if (columnName.Equals("ISLINK")) { vo.isLink = "Y".Equals(Util.GetValueOfString(dr[i])); } else if (columnName.Equals("ISRIGHTPANELINK")) { vo.isRightPaneLink = "Y".Equals(Util.GetValueOfString(dr[i])); } else if (columnName.Equals("ISCOPY")) { vo.IsCopy = "Y".Equals(Util.GetValueOfString(dr[i])); } else if (columnName.Equals("COLUMNWIDTH")) { vo.ColumnWidth = Util.GetValueOfInt(dr[i]); } } if (vo.Header == null) { vo.Header = vo.ColumnName; } } catch (Exception e) { VLogger.Get().Log(Level.SEVERE, "ColumnName=" + columnName, e); return(null); } vo.InitFinish(); return(vo); }
/** Reads the font metrics * @param rf the AFM file * @throws DocumentException the AFM file is invalid * @throws IOException the AFM file could not be read */ public void Process(RandomAccessFileOrArray rf) { string line; bool isMetrics = false; while ((line = rf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line, " ,\n\r\t\f"); if (!tok.HasMoreTokens()) { continue; } string ident = tok.NextToken(); if (ident.Equals("FontName")) { FontName = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("FullName")) { FullName = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("FamilyName")) { FamilyName = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("Weight")) { Weight = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("ItalicAngle")) { ItalicAngle = float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("IsFixedPitch")) { IsFixedPitch = tok.NextToken().Equals("true"); } else if (ident.Equals("CharacterSet")) { CharacterSet = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("FontBBox")) { llx = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); lly = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); urx = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); ury = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("UnderlinePosition")) { UnderlinePosition = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("UnderlineThickness")) { UnderlineThickness = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("EncodingScheme")) { EncodingScheme = tok.NextToken("\u00ff").Substring(1); } else if (ident.Equals("CapHeight")) { CapHeight = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("XHeight")) { XHeight = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("Ascender")) { Ascender = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("Descender")) { Descender = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("StdHW")) { StdHW = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("StdVW")) { StdVW = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("StartCharMetrics")) { isMetrics = true; break; } } if (!isMetrics) { throw new DocumentException("Missing StartCharMetrics in " + fileName); } while ((line = rf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line); if (!tok.HasMoreTokens()) { continue; } string ident = tok.NextToken(); if (ident.Equals("EndCharMetrics")) { isMetrics = false; break; } int C = -1; int WX = 250; string N = ""; int[] B = null; tok = new StringTokenizer(line, ";"); while (tok.HasMoreTokens()) { StringTokenizer tokc = new StringTokenizer(tok.NextToken()); if (!tokc.HasMoreTokens()) { continue; } ident = tokc.NextToken(); if (ident.Equals("C")) { C = int.Parse(tokc.NextToken()); } else if (ident.Equals("WX")) { WX = (int)float.Parse(tokc.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); } else if (ident.Equals("N")) { N = tokc.NextToken(); } else if (ident.Equals("B")) { B = new int[] { int.Parse(tokc.NextToken()), int.Parse(tokc.NextToken()), int.Parse(tokc.NextToken()), int.Parse(tokc.NextToken()) }; } } Object[] metrics = new Object[] { C, WX, N, B }; if (C >= 0) { CharMetrics[C] = metrics; } CharMetrics[N] = metrics; } if (isMetrics) { throw new DocumentException("Missing EndCharMetrics in " + fileName); } if (!CharMetrics.ContainsKey("nonbreakingspace")) { Object[] space = (Object[])CharMetrics["space"]; if (space != null) { CharMetrics["nonbreakingspace"] = space; } } while ((line = rf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line); if (!tok.HasMoreTokens()) { continue; } string ident = tok.NextToken(); if (ident.Equals("EndFontMetrics")) { return; } if (ident.Equals("StartKernPairs")) { isMetrics = true; break; } } if (!isMetrics) { throw new DocumentException("Missing EndFontMetrics in " + fileName); } while ((line = rf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line); if (!tok.HasMoreTokens()) { continue; } string ident = tok.NextToken(); if (ident.Equals("KPX")) { string first = tok.NextToken(); string second = tok.NextToken(); int width = (int)float.Parse(tok.NextToken(), System.Globalization.NumberFormatInfo.InvariantInfo); Object[] relates = (Object[])KernPairs[first]; if (relates == null) { KernPairs[first] = new Object[] { second, width } } ; else { int n = relates.Length; Object[] relates2 = new Object[n + 2]; Array.Copy(relates, 0, relates2, 0, n); relates2[n] = second; relates2[n + 1] = width; KernPairs[first] = relates2; } } else if (ident.Equals("EndKernPairs")) { isMetrics = false; break; } } if (isMetrics) { throw new DocumentException("Missing EndKernPairs in " + fileName); } rf.Close(); }
/// <summary> /// Creates a CJK font. /// @throws DocumentException on error /// @throws IOException on error /// </summary> /// <param name="fontName">the name of the font</param> /// <param name="enc">the encoding of the font</param> /// <param name="emb">always false . CJK font and not embedded</param> internal CjkFont(string fontName, string enc, bool emb) { loadProperties(); FontType = FONT_TYPE_CJK; var nameBase = GetBaseName(fontName); if (!IsCjkFont(nameBase, enc)) { throw new DocumentException("Font '" + fontName + "' with '" + enc + "' encoding is not a CJK font."); } if (nameBase.Length < fontName.Length) { _style = fontName.Substring(nameBase.Length); fontName = nameBase; } _fontName = fontName; encoding = CJK_ENCODING; _vertical = enc.EndsWith("V"); _cMap = enc; if (enc.StartsWith("Identity-")) { _cidDirect = true; var s = CjkFonts[fontName]; s = s.Substring(0, s.IndexOf("_", StringComparison.Ordinal)); var c = (char[])AllCMaps[s]; if (c == null) { c = ReadCMap(s); if (c == null) { throw new DocumentException("The cmap " + s + " does not exist as a resource."); } c[CID_NEWLINE] = '\n'; AllCMaps.Add(s, c); } _translationMap = c; } else { var c = (char[])AllCMaps[enc]; if (c == null) { var s = CjkEncodings[enc]; if (s == null) { throw new DocumentException("The resource cjkencodings.properties does not contain the encoding " + enc); } var tk = new StringTokenizer(s); var nt = tk.NextToken(); c = (char[])AllCMaps[nt]; if (c == null) { c = ReadCMap(nt); AllCMaps.Add(nt, c); } if (tk.HasMoreTokens()) { var nt2 = tk.NextToken(); var m2 = ReadCMap(nt2); for (var k = 0; k < 0x10000; ++k) { if (m2[k] == 0) { m2[k] = c[k]; } } AllCMaps.Add(enc, m2); c = m2; } } _translationMap = c; } _fontDesc = (Hashtable)AllFonts[fontName]; if (_fontDesc == null) { _fontDesc = ReadFontProperties(fontName); AllFonts.Add(fontName, _fontDesc); } _hMetrics = (IntHashtable)_fontDesc["W"]; _vMetrics = (IntHashtable)_fontDesc["W2"]; }
/** Creates a CJK font. * @param fontName the name of the font * @param enc the encoding of the font * @param emb always <CODE>false</CODE>. CJK font and not embedded * @throws DocumentException on error * @throws IOException on error */ internal CJKFont(string fontName, string enc, bool emb) { LoadProperties(); this.FontType = FONT_TYPE_CJK; string nameBase = GetBaseName(fontName); if (!IsCJKFont(nameBase, enc)) { throw new DocumentException("Font '" + fontName + "' with '" + enc + "' encoding is not a CJK font."); } if (nameBase.Length < fontName.Length) { style = fontName.Substring(nameBase.Length); fontName = nameBase; } this.fontName = fontName; encoding = CJK_ENCODING; vertical = enc.EndsWith("V"); CMap = enc; if (enc.StartsWith("Identity-")) { cidDirect = true; string s = cjkFonts[fontName]; s = s.Substring(0, s.IndexOf('_')); char[] c = (char[])allCMaps[s]; if (c == null) { c = ReadCMap(s); if (c == null) { throw new DocumentException("The cmap " + s + " does not exist as a resource."); } c[CID_NEWLINE] = '\n'; allCMaps.Add(s, c); } translationMap = c; } else { char[] c = (char[])allCMaps[enc]; if (c == null) { string s = cjkEncodings[enc]; if (s == null) { throw new DocumentException("The resource cjkencodings.properties does not contain the encoding " + enc); } StringTokenizer tk = new StringTokenizer(s); string nt = tk.NextToken(); c = (char[])allCMaps[nt]; if (c == null) { c = ReadCMap(nt); allCMaps.Add(nt, c); } if (tk.HasMoreTokens()) { string nt2 = tk.NextToken(); char[] m2 = ReadCMap(nt2); for (int k = 0; k < 0x10000; ++k) { if (m2[k] == 0) { m2[k] = c[k]; } } allCMaps.Add(enc, m2); c = m2; } } translationMap = c; } fontDesc = (Hashtable)allFonts[fontName]; if (fontDesc == null) { fontDesc = ReadFontProperties(fontName); allFonts.Add(fontName, fontDesc); } hMetrics = (IntHashtable)fontDesc["W"]; vMetrics = (IntHashtable)fontDesc["W2"]; }
public ColorType(string value) { string colorValue = value.ToLower(); if (colorValue.StartsWith("#")) { try { if (colorValue.Length == 4) { // note: divide by 15 so F = FF = 1 and so on red = Int32.Parse( colorValue.Substring(1, 1), NumberStyles.HexNumber) / 15f; green = Int32.Parse( colorValue.Substring(2, 1), NumberStyles.HexNumber) / 15f; blue = Int32.Parse( colorValue.Substring(3, 1), NumberStyles.HexNumber) / 15f; } else if (colorValue.Length == 7) { // note: divide by 255 so FF = 1 red = Int32.Parse( colorValue.Substring(1, 2), NumberStyles.HexNumber) / 255f; green = Int32.Parse( colorValue.Substring(3, 2), NumberStyles.HexNumber) / 255f; blue = Int32.Parse( colorValue.Substring(5, 2), NumberStyles.HexNumber) / 255f; } else { red = 0; green = 0; blue = 0; FonetDriver.ActiveDriver.FireFonetError( "Unknown colour format. Must be #RGB or #RRGGBB"); } } catch (Exception) { red = 0; green = 0; blue = 0; FonetDriver.ActiveDriver.FireFonetError( "Unknown colour format. Must be #RGB or #RRGGBB"); } } else if (colorValue.StartsWith("rgb(")) { int poss = colorValue.IndexOf("("); int pose = colorValue.IndexOf(")"); if (poss != -1 && pose != -1) { colorValue = colorValue.Substring(poss + 1, pose); StringTokenizer st = new StringTokenizer(colorValue, ","); try { if (st.HasMoreTokens()) { String str = st.NextToken().Trim(); if (str.EndsWith("%")) { this.Red = Int32.Parse(str.Substring(0, str.Length - 1)) * 2.55f; } else { this.Red = Int32.Parse(str) / 255f; } } if (st.HasMoreTokens()) { String str = st.NextToken().Trim(); if (str.EndsWith("%")) { this.Green = Int32.Parse(str.Substring(0, str.Length - 1)) * 2.55f; } else { this.Green = Int32.Parse(str) / 255f; } } if (st.HasMoreTokens()) { String str = st.NextToken().Trim(); if (str.EndsWith("%")) { this.Blue = Int32.Parse(str.Substring(0, str.Length - 1)) * 2.55f; } else { this.Blue = Int32.Parse(str) / 255f; } } } catch { this.Red = 0; this.Green = 0; this.Blue = 0; FonetDriver.ActiveDriver.FireFonetError( "Unknown colour format. Must be #RGB or #RRGGBB"); } } } else if (colorValue.StartsWith("url(")) { // refers to a gradient FonetDriver.ActiveDriver.FireFonetError( "unsupported color format"); } else { if (colorValue.Equals("transparent")) { Red = 0; Green = 0; Blue = 0; Alpha = 1; } else { bool found = false; for (int count = 0; count < names.Length; count++) { if (colorValue.Equals(names[count])) { Red = vals[count, 0] / 255f; Green = vals[count, 1] / 255f; Blue = vals[count, 2] / 255f; found = true; break; } } if (!found) { Red = 0; Green = 0; Blue = 0; FonetDriver.ActiveDriver.FireFonetWarning( "Unknown colour name: " + colorValue + ". Defaulting to black."); } } } }
internal void MergeField(String name, AcroFields.Item item) { Hashtable map = fieldTree; StringTokenizer tk = new StringTokenizer(name, "."); if (!tk.HasMoreTokens()) { return; } while (true) { String s = tk.NextToken(); Object obj = map[s]; if (tk.HasMoreTokens()) { if (obj == null) { obj = new Hashtable(); map[s] = obj; map = (Hashtable)obj; continue; } else if (obj is Hashtable) { map = (Hashtable)obj; } else { return; } } else { if (obj is Hashtable) { return; } PdfDictionary merged = (PdfDictionary)item.merged[0]; if (obj == null) { PdfDictionary field = new PdfDictionary(); foreach (PdfName key in merged.Keys) { if (fieldKeys.ContainsKey(key)) { field.Put(key, merged.Get(key)); } } ArrayList list = new ArrayList(); list.Add(field); CreateWidgets(list, item); map[s] = list; } else { ArrayList list = (ArrayList)obj; PdfDictionary field = (PdfDictionary)list[0]; PdfName type1 = (PdfName)field.Get(PdfName.FT); PdfName type2 = (PdfName)merged.Get(PdfName.FT); if (type1 == null || !type1.Equals(type2)) { return; } int flag1 = 0; PdfObject f1 = field.Get(PdfName.FF); if (f1 != null && f1.IsNumber()) { flag1 = ((PdfNumber)f1).IntValue; } int flag2 = 0; PdfObject f2 = merged.Get(PdfName.FF); if (f2 != null && f2.IsNumber()) { flag2 = ((PdfNumber)f2).IntValue; } if (type1.Equals(PdfName.BTN)) { if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0) { return; } if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0) { return; } } else if (type1.Equals(PdfName.CH)) { if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0) { return; } } CreateWidgets(list, item); } return; } } }
/** * Entry point to the Compile application. * <p> * This program takes any number of arguments: the first is the name of the * desired stemming algorithm to use (a list is available in the package * description) , all of the rest should be the path or paths to a file or * files containing a stemmer table to compile. * * @param args the command line arguments */ public static void Main(string[] args) { if (args.Length < 1) { return; } args[0].ToUpperInvariant(); backward = args[0][0] == '-'; int qq = (backward) ? 1 : 0; bool storeorig = false; if (args[0][qq] == '0') { storeorig = true; qq++; } multi = args[0][qq] == 'M'; if (multi) { qq++; } // LUCENENET TODO: Is this any different than Encoding.UTF8? //String charset = System.getProperty("egothor.stemmer.charset", "UTF-8"); char[] optimizer = new char[args[0].Length - qq]; for (int i = 0; i < optimizer.Length; i++) { optimizer[i] = args[0][qq + i]; } for (int i = 1; i < args.Length; i++) { TextReader @in; // System.out.println("[" + args[i] + "]"); Diff diff = new Diff(); //int stems = 0; // not used int words = 0; AllocTrie(); Console.WriteLine(args[i]); using (@in = new StreamReader( new FileStream(args[i], FileMode.Open, FileAccess.Read), Encoding.UTF8)) { for (string line = @in.ReadLine(); line != null; line = @in.ReadLine()) { try { line = line.ToLowerInvariant(); StringTokenizer st = new StringTokenizer(line); string stem = st.NextToken(); if (storeorig) { trie.Add(stem, "-a"); words++; } while (st.HasMoreTokens()) { string token = st.NextToken(); if (token.Equals(stem) == false) { trie.Add(token, diff.Exec(token, stem)); words++; } } } catch (InvalidOperationException /*x*/) { // no base token (stem) on a line } } } Optimizer o = new Optimizer(); Optimizer2 o2 = new Optimizer2(); Lift l = new Lift(true); Lift e = new Lift(false); Gener g = new Gener(); for (int j = 0; j < optimizer.Length; j++) { string prefix; switch (optimizer[j]) { case 'G': trie = trie.Reduce(g); prefix = "G: "; break; case 'L': trie = trie.Reduce(l); prefix = "L: "; break; case 'E': trie = trie.Reduce(e); prefix = "E: "; break; case '2': trie = trie.Reduce(o2); prefix = "2: "; break; case '1': trie = trie.Reduce(o); prefix = "1: "; break; default: continue; } trie.PrintInfo(System.Console.Out, prefix + " "); } using (DataOutputStream os = new DataOutputStream( new FileStream(args[i] + ".out", FileMode.OpenOrCreate, FileAccess.Write))) { os.WriteUTF(args[0]); trie.Store(os); } } }
public Font GetFont(ChainedProperties props) { var face = props[ElementTags.FACE]; if (face != null) { var tok = new StringTokenizer(face, ","); while (tok.HasMoreTokens()) { face = tok.NextToken().Trim(); if (face.StartsWith("\"")) { face = face.Substring(1); } if (face.EndsWith("\"")) { face = face.Substring(0, face.Length - 1); } if (FontImp.IsRegistered(face)) { break; } } } var style = 0; if (props.HasProperty(HtmlTags.I)) { style |= Font.ITALIC; } if (props.HasProperty(HtmlTags.B)) { style |= Font.BOLD; } if (props.HasProperty(HtmlTags.U)) { style |= Font.UNDERLINE; } if (props.HasProperty(HtmlTags.S)) { style |= Font.STRIKETHRU; } var value = props[ElementTags.SIZE]; float size = 12; if (value != null) { size = float.Parse(value, NumberFormatInfo.InvariantInfo); } var color = Markup.DecodeColor(props["color"]); var encoding = props["encoding"]; if (encoding == null) { encoding = BaseFont.WINANSI; } return(FontImp.GetFont(face, encoding, true, size, style, color)); }
/** * Creates a Font object based on a chain of properties. * @param chain chain of properties * @return an iText Font object */ public Font GetFont(ChainedProperties chain) { // [1] font name String face = chain[HtmlTags.FACE]; // try again, under the CSS key. //ISSUE: If both are present, we always go with face, even if font-family was // defined more recently in our ChainedProperties. One solution would go like this: // Map all our supported style attributes to the 'normal' tag name, so we could // look everything up under that one tag, retrieving the most current value. if (face == null || face.Trim().Length == 0) { face = chain[HtmlTags.FONTFAMILY]; } // if the font consists of a comma separated list, // take the first font that is registered if (face != null) { StringTokenizer tok = new StringTokenizer(face, ","); while (tok.HasMoreTokens()) { face = tok.NextToken().Trim(); if (face.StartsWith("\"")) { face = face.Substring(1); } if (face.EndsWith("\"")) { face = face.Substring(0, face.Length - 1); } if (provider.IsRegistered(face)) { break; } } } // [2] encoding String encoding = chain[HtmlTags.ENCODING]; if (encoding == null) { encoding = BaseFont.WINANSI; } // [3] embedded // [4] font size String value = chain[HtmlTags.SIZE]; float size = 12; if (value != null) { size = float.Parse(value, CultureInfo.InvariantCulture); } // [5] font style int style = 0; // text-decoration String decoration = chain[HtmlTags.TEXTDECORATION]; if (decoration != null && decoration.Trim().Length != 0) { if (HtmlTags.UNDERLINE.Equals(decoration)) { style |= Font.UNDERLINE; } else if (HtmlTags.LINETHROUGH.Equals(decoration)) { style |= Font.STRIKETHRU; } } // italic if (chain.HasProperty(HtmlTags.I)) { style |= Font.ITALIC; } // bold if (chain.HasProperty(HtmlTags.B)) { style |= Font.BOLD; } // underline if (chain.HasProperty(HtmlTags.U)) { style |= Font.UNDERLINE; } // strikethru if (chain.HasProperty(HtmlTags.S)) { style |= Font.STRIKETHRU; } // [6] Color BaseColor color = HtmlUtilities.DecodeColor(chain[HtmlTags.COLOR]); // Get the font object from the provider return(provider.GetFont(face, encoding, true, size, style, color)); }
/** Creates a CJK font. * @param fontName the name of the font * @param enc the encoding of the font * @param emb always <CODE>false</CODE>. CJK font and not embedded * @throws DocumentException on error * @throws IOException on error */ internal CJKFont(string fontName, string enc, bool emb) { LoadProperties(); this.FontType = FONT_TYPE_CJK; string nameBase = GetBaseName(fontName); if (!IsCJKFont(nameBase, enc)) { throw new DocumentException(MessageLocalization.GetComposedMessage("font.1.with.2.encoding.is.not.a.cjk.font", fontName, enc)); } if (nameBase.Length < fontName.Length) { style = fontName.Substring(nameBase.Length); fontName = nameBase; } this.fontName = fontName; encoding = CJK_ENCODING; vertical = enc.EndsWith("V"); CMap = enc; if (enc.StartsWith("Identity-")) { cidDirect = true; string s = cjkFonts[fontName]; s = s.Substring(0, s.IndexOf('_')); char[] c; lock (allCMaps) { allCMaps.TryGetValue(s, out c); } if (c == null) { c = ReadCMap(s); if (c == null) { throw new DocumentException(MessageLocalization.GetComposedMessage("the.cmap.1.does.not.exist.as.a.resource", s)); } c[CID_NEWLINE] = '\n'; lock (allCMaps) { allCMaps[s] = c; } } translationMap = c; } else { char[] c; lock (allCMaps) { allCMaps.TryGetValue(enc, out c); } if (c == null) { string s = cjkEncodings[enc]; if (s == null) { throw new DocumentException(MessageLocalization.GetComposedMessage("the.resource.cjkencodings.properties.does.not.contain.the.encoding.1", enc)); } StringTokenizer tk = new StringTokenizer(s); string nt = tk.NextToken(); lock (allCMaps) { allCMaps.TryGetValue(nt, out c); } if (c == null) { c = ReadCMap(nt); lock (allCMaps) { allCMaps[nt] = c; } } if (tk.HasMoreTokens()) { string nt2 = tk.NextToken(); char[] m2 = ReadCMap(nt2); for (int k = 0; k < 0x10000; ++k) { if (m2[k] == 0) { m2[k] = c[k]; } } lock (allCMaps) { allCMaps[enc] = m2; } c = m2; } } translationMap = c; } lock (allFonts) { allFonts.TryGetValue(fontName, out fontDesc); } allFonts.TryGetValue(fontName, out fontDesc); if (fontDesc == null) { fontDesc = ReadFontProperties(fontName); lock (allFonts) { allFonts[fontName] = fontDesc; } } hMetrics = (IntHashtable)fontDesc["W"]; vMetrics = (IntHashtable)fontDesc["W2"]; }
static AdobeGlyphList() { Stream resource = null; try { resource = ResourceUtil.GetResourceStream(FontResources.ADOBE_GLYPH_LIST); if (resource == null) { throw new Exception(FontResources.ADOBE_GLYPH_LIST + " not found as resource."); } byte[] buf = new byte[1024]; MemoryStream stream = new MemoryStream(); while (true) { int size = resource.Read(buf); if (size < 0) { break; } stream.Write(buf, 0, size); } resource.Dispose(); resource = null; String s = PdfEncodings.ConvertToString(stream.ToArray(), null); StringTokenizer tk = new StringTokenizer(s, "\r\n"); while (tk.HasMoreTokens()) { String line = tk.NextToken(); if (line.StartsWith("#")) { continue; } StringTokenizer t2 = new StringTokenizer(line, " ;\r\n\t\f"); if (!t2.HasMoreTokens()) { continue; } String name = t2.NextToken(); if (!t2.HasMoreTokens()) { continue; } String hex = t2.NextToken(); // AdobeGlyphList could contains symbols with marks, e.g.: // resh;05E8 // reshhatafpatah;05E8 05B2 // So in this case we will just skip this nam if (t2.HasMoreTokens()) { continue; } int num = Convert.ToInt32(hex, 16); unicode2names.Put(num, name); names2unicode.Put(name, num); } } catch (Exception e) { System.Console.Error.WriteLine("AdobeGlyphList.txt loading error: " + e.Message); } finally { if (resource != null) { try { resource.Dispose(); } catch (Exception) { } } } }
public virtual IList <Ca.Infoway.Messagebuilder.Marshalling.HL7.Hl7DataTypeName> GetInnerTypes() { IList <Ca.Infoway.Messagebuilder.Marshalling.HL7.Hl7DataTypeName> innerTypes = new List <Ca.Infoway.Messagebuilder.Marshalling.HL7.Hl7DataTypeName >(); bool first = true; for (StringTokenizer tokenizer = new StringTokenizer(this.name, "<,>", true); tokenizer.HasMoreTokens();) { string token = tokenizer.NextToken(); if (first || "<,>".IndexOf(token) >= 0) { } else { // skip; innerTypes.Add(Ca.Infoway.Messagebuilder.Marshalling.HL7.Hl7DataTypeName.Create(token)); } first = false; } return(innerTypes); }
/** * Validate Credit Card Number. * - Check Card Type and Length * @param creditCardNumber CC Number * @param creditCardType CC Type * @return "" or Error AD_Message */ public static String ValidateCreditCardNumber(String creditCardNumber, String creditCardType) { if (creditCardNumber == null || creditCardType == null) { return("CreditCardNumberError"); } // http://www.beachnet.com/~hstiles/cardtype.html // http://staff.semel.fi/~kribe/document/luhn.htm String ccStartList = ""; // comma separated list of starting numbers String ccLengthList = ""; // comma separated list of lengths // if (creditCardType.Equals(X_C_Payment.CREDITCARDTYPE_MasterCard)) { ccStartList = "51,52,53,54,55"; ccLengthList = "16"; } else if (creditCardType.Equals(X_C_Payment.CREDITCARDTYPE_Visa)) { ccStartList = "4"; ccLengthList = "13,16"; } else if (creditCardType.Equals(X_C_Payment.CREDITCARDTYPE_Amex)) { ccStartList = "34,37"; ccLengthList = "15"; } else if (creditCardType.Equals(X_C_Payment.CREDITCARDTYPE_Discover)) { ccStartList = "6011"; ccLengthList = "16"; } else if (creditCardType.Equals(X_C_Payment.CREDITCARDTYPE_Diners)) { ccStartList = "300,301,302,303,304,305,36,38"; ccLengthList = "14"; } else { // enRouteCard ccStartList = "2014,2149"; ccLengthList = "15"; // JCBCard ccStartList += ",3088,3096,3112,3158,3337,3528"; ccLengthList += ",16"; // JCBCard ccStartList += ",2131,1800"; ccLengthList += ",15"; } // Clean up number String ccNumber = CheckNumeric(creditCardNumber); /** * Check Length */ int ccLength = ccNumber.Length; Boolean ccLengthOK = false; StringTokenizer st = new StringTokenizer(ccLengthList, ",", false); while (st.HasMoreTokens() && !ccLengthOK) { int l = int.Parse(st.NextToken()); if (ccLength == l) { ccLengthOK = true; } } if (!ccLengthOK) { _log.Fine("validateCreditCardNumber Length=" + ccLength + " <> " + ccLengthList); return("CreditCardNumberError");//Credit Card Number not valid";// } /** * Check Start Digits */ Boolean ccIdentified = false; st = new StringTokenizer(ccStartList, ",", false); while (st.HasMoreTokens() && !ccIdentified) { if (ccNumber.StartsWith(st.NextToken())) { ccIdentified = true; } } if (!ccIdentified) { _log.Fine("validateCreditCardNumber Type=" + creditCardType + " <> " + ccStartList); } // String check = ValidateCreditCardNumber(ccNumber); if (check.Length != 0) { return(check); } if (!ccIdentified) { return("CreditCardNumberProblem?");//There seems to be a Credit Card Number problem.\n\n Continue?";// } return(""); }
private string UnqualifyInnerTypes() { StringBuilder builder = new StringBuilder(); bool first = true; for (StringTokenizer tokenizer = new StringTokenizer(this.name, "<,>", true); tokenizer.HasMoreTokens();) { string token = tokenizer.NextToken(); if ("<,>".IndexOf(token) >= 0) { builder.Append(token); } else { if (IsQualified(token) && !first) { builder.Append(StringUtils.SubstringBefore(token, ".")); } else { builder.Append(token); } } first = false; } return(builder.ToString()); }
private void DelApp_Click(object sender, EventArgs e) { int sel = Cmdlist.SelectedIndex; string temp = ""; if (sel >= 2) { try { temp = ch.ElementAt(sel); ch.RemoveAt(sel); } catch { } string txt = ""; int flag = 0; using (StreamReader sr = File.OpenText("abc.txt")) { while ((txt = sr.ReadLine()) != null) { StringTokenizer st = new StringTokenizer(txt, "$@"); while (st.HasMoreTokens()) { if (temp == st.NextToken()) { st.NextToken(); flag = 1; } } if (flag == 0) { using (StreamWriter sw = File.AppendText("temp.txt")) { sw.WriteLine(txt); } } else { flag = 0; } } } Cmdlist.DataSource = null; Cmdlist.DataSource = ch; try { File.Delete("abc.txt"); File.Move("temp.txt", "abc.txt"); MessageBox.Show(temp); } catch { MessageBox.Show("Database Empty"); } } else { MessageBox.Show("Default Command provided by the developer and therefore cannot be deleted."); } }
/// <summary>Gives you a BaseColor based on a name.</summary> /// <param name="name"> /// a name such as black, violet, cornflowerblue or #RGB or /// #RRGGBB or RGB or RRGGBB or rgb(R,G,B) /// </param> /// <returns>the corresponding BaseColor object. Never returns null.</returns> /// <exception cref="System.ArgumentException">if the String isn't a know representation of a color.</exception> public static DeviceRgb GetRGBColor(String name) { int[] color = new int[] { 0, 0, 0, 255 }; String colorName = name.ToLower(System.Globalization.CultureInfo.InvariantCulture); bool colorStrWithoutHash = MissingHashColorFormat(colorName); if (colorName.StartsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { // lop off the # to unify hex parsing. colorName = colorName.Substring(1); } if (colorName.Length == 3) { String red = colorName.JSubstring(0, 1); color[0] = System.Convert.ToInt32(red + red, 16); String green = colorName.JSubstring(1, 2); color[1] = System.Convert.ToInt32(green + green, 16); String blue = colorName.Substring(2); color[2] = System.Convert.ToInt32(blue + blue, 16); return(new DeviceRgb(color[0], color[1], color[2])); } if (colorName.Length == 6) { color[0] = System.Convert.ToInt32(colorName.JSubstring(0, 2), 16); color[1] = System.Convert.ToInt32(colorName.JSubstring(2, 4), 16); color[2] = System.Convert.ToInt32(colorName.Substring(4), 16); return(new DeviceRgb(color[0], color[1], color[2])); } throw new PdfException(PdfException.UnknownColorFormatMustBeRGBorRRGGBB); } if (colorName.StartsWith("rgb(")) { String delim = "rgb(), \t\r\n\f"; StringTokenizer tok = new StringTokenizer(colorName, delim); for (int k = 0; k < 3; ++k) { if (tok.HasMoreTokens()) { color[k] = GetRGBChannelValue(tok.NextToken()); color[k] = Math.Max(0, color[k]); color[k] = Math.Min(255, color[k]); } } return(new DeviceRgb(color[0], color[1], color[2])); } if (colorName.StartsWith("rgba(")) { String delim = "rgba(), \t\r\n\f"; StringTokenizer tok = new StringTokenizer(colorName, delim); for (int k = 0; k < 3; ++k) { if (tok.HasMoreTokens()) { color[k] = GetRGBChannelValue(tok.NextToken()); color[k] = Math.Max(0, color[k]); color[k] = Math.Min(255, color[k]); } } return(new DeviceRgb(color[0], color[1], color[2])); } if (!NAMES.Contains(colorName)) { throw new PdfException(PdfException.ColorNotFound).SetMessageParams(colorName); } color = NAMES.Get(colorName); return(new DeviceRgb(color[0], color[1], color[2])); }
/** * Creates an Table object based on a list of properties. * @param attributes * @return a Table */ public static Table GetTable(TagProperties attributes) { String value; Table table; value = attributes[ElementTags.WIDTHS]; if (value != null) { StringTokenizer widthTokens = new StringTokenizer(value, ";"); ArrayList values = new ArrayList(); while (widthTokens.HasMoreTokens()) { values.Add(widthTokens.NextToken()); } table = new Table(values.Count); float[] widths = new float[table.Columns]; for (int i = 0; i < values.Count; i++) { value = (String)values[i]; widths[i] = float.Parse(value, NumberFormatInfo.InvariantInfo); } table.Widths = widths; } else { value = attributes[ElementTags.COLUMNS]; try { table = new Table(int.Parse(value)); } catch { table = new Table(1); } } table.Border = Table.BOX; table.BorderWidth = 1; table.DefaultCell.Border = Table.BOX; value = attributes[ElementTags.LASTHEADERROW]; if (value != null) { table.LastHeaderRow = int.Parse(value); } value = attributes[ElementTags.ALIGN]; if (value != null) { table.SetAlignment(value); } value = attributes[ElementTags.CELLSPACING]; if (value != null) { table.Spacing = float.Parse(value, NumberFormatInfo.InvariantInfo); } value = attributes[ElementTags.CELLPADDING]; if (value != null) { table.Padding = float.Parse(value, NumberFormatInfo.InvariantInfo); } value = attributes[ElementTags.OFFSET]; if (value != null) { table.Offset = float.Parse(value, NumberFormatInfo.InvariantInfo); } value = attributes[ElementTags.WIDTH]; if (value != null) { if (value.EndsWith("%")) { table.Width = float.Parse(value.Substring(0, value.Length - 1), NumberFormatInfo.InvariantInfo); } else { table.Width = float.Parse(value, NumberFormatInfo.InvariantInfo); table.Locked = true; } } table.TableFitsPage = Utilities.CheckTrueOrFalse(attributes, ElementTags.TABLEFITSPAGE); table.CellsFitPage = Utilities.CheckTrueOrFalse(attributes, ElementTags.CELLSFITPAGE); table.Convert2pdfptable = Utilities.CheckTrueOrFalse(attributes, ElementTags.CONVERT2PDFP); SetRectangleProperties(table, attributes); return(table); }
static UniAddress() { string ro = Config.GetProperty("jcifs.resolveOrder"); IPAddress nbns = NbtAddress.GetWinsAddress(); try { _baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName ("255.255.255.255")); } catch (UnknownHostException) { } if (string.IsNullOrEmpty(ro)) { if (nbns == null) { _resolveOrder = new int[3]; _resolveOrder[0] = ResolverLmhosts; _resolveOrder[1] = ResolverDns; _resolveOrder[2] = ResolverBcast; } else { _resolveOrder = new int[4]; _resolveOrder[0] = ResolverLmhosts; _resolveOrder[1] = ResolverWins; _resolveOrder[2] = ResolverDns; _resolveOrder[3] = ResolverBcast; } } else { int[] tmp = new int[4]; StringTokenizer st = new StringTokenizer(ro, ","); int i = 0; while (st.HasMoreTokens()) { string s = st.NextToken().Trim(); if (Runtime.EqualsIgnoreCase(s, "LMHOSTS")) { tmp[i++] = ResolverLmhosts; } else { if (Runtime.EqualsIgnoreCase(s, "WINS")) { if (nbns == null) { if (_log.Level > 1) { _log.WriteLine("UniAddress resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set" ); } continue; } tmp[i++] = ResolverWins; } else { if (Runtime.EqualsIgnoreCase(s, "BCAST")) { tmp[i++] = ResolverBcast; } else { if (Runtime.EqualsIgnoreCase(s, "DNS")) { tmp[i++] = ResolverDns; } else { if (_log.Level > 1) { _log.WriteLine("unknown resolver method: " + s); } } } } } } _resolveOrder = new int[i]; Array.Copy(tmp, 0, _resolveOrder, 0, i); } }
static GlyphList() { Stream istr = null; try { istr = BaseFont.GetResourceStream(BaseFont.RESOURCE_PATH + "glyphlist.txt"); if (istr == null) { String msg = "glyphlist.txt not found as resource."; throw new Exception(msg); } byte[] buf = new byte[1024]; MemoryStream outp = new MemoryStream(); while (true) { int size = istr.Read(buf, 0, buf.Length); if (size == 0) { break; } outp.Write(buf, 0, size); } istr.Close(); istr = null; String s = PdfEncodings.ConvertToString(outp.ToArray(), null); StringTokenizer tk = new StringTokenizer(s, "\r\n"); while (tk.HasMoreTokens()) { String line = tk.NextToken(); if (line.StartsWith("#")) { continue; } StringTokenizer t2 = new StringTokenizer(line, " ;\r\n\t\f"); String name = null; String hex = null; if (!t2.HasMoreTokens()) { continue; } name = t2.NextToken(); if (!t2.HasMoreTokens()) { continue; } hex = t2.NextToken(); int num = int.Parse(hex, NumberStyles.HexNumber); unicode2names[num] = name; names2unicode[name] = new int[] { num }; } } catch (Exception e) { Console.Error.WriteLine("glyphlist.txt loading error: " + e.Message); } finally { if (istr != null) { try { istr.Close(); } catch { // empty on purpose } } } }
public Font GetFont(ChainedProperties props) { String face = props[ElementTags.FACE]; // try again, under the CSS key. //ISSUE: If both are present, we always go with face, even if font-family was // defined more recently in our ChainedProperties. One solution would go like this: // Map all our supported style attributes to the 'normal' tag name, so we could // look everything up under that one tag, retrieving the most current value. if (face == null || face.Trim().Length == 0) { face = props[Markup.CSS_KEY_FONTFAMILY]; } if (face != null) { StringTokenizer tok = new StringTokenizer(face, ","); while (tok.HasMoreTokens()) { face = tok.NextToken().Trim(); if (face.StartsWith("\"")) { face = face.Substring(1); } if (face.EndsWith("\"")) { face = face.Substring(0, face.Length - 1); } if (fontImp.IsRegistered(face)) { break; } } } int style = 0; String textDec = props[Markup.CSS_KEY_TEXTDECORATION]; if (textDec != null && textDec.Trim().Length != 0) { if (Markup.CSS_VALUE_UNDERLINE.Equals(textDec)) { style |= Font.UNDERLINE; } else if (Markup.CSS_VALUE_LINETHROUGH.Equals(textDec)) { style |= Font.STRIKETHRU; } } if (props.HasProperty(HtmlTags.I)) { style |= Font.ITALIC; } if (props.HasProperty(HtmlTags.B)) { style |= Font.BOLD; } if (props.HasProperty(HtmlTags.U)) { style |= Font.UNDERLINE; } if (props.HasProperty(HtmlTags.S)) { style |= Font.STRIKETHRU; } String value = props[ElementTags.SIZE]; float size = 12; if (value != null) { size = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo); } BaseColor color = Markup.DecodeColor(props["color"]); String encoding = props["encoding"]; if (encoding == null) { encoding = BaseFont.WINANSI; } return(fontImp.GetFont(face, encoding, true, size, style, color)); }
internal static void CreateOutlineAction(PdfDictionary outline, Dictionary <String, Object> map, PdfWriter writer, bool namedAsNames) { try { String action = GetVal(map, "Action"); if ("GoTo".Equals(action)) { String p; if ((p = GetVal(map, "Named")) != null) { if (namedAsNames) { outline.Put(PdfName.DEST, new PdfName(p)); } else { outline.Put(PdfName.DEST, new PdfString(p, null)); } } else if ((p = GetVal(map, "Page")) != null) { PdfArray ar = new PdfArray(); StringTokenizer tk = new StringTokenizer(p); int n = int.Parse(tk.NextToken()); ar.Add(writer.GetPageReference(n)); if (!tk.HasMoreTokens()) { ar.Add(PdfName.XYZ); ar.Add(new float[] { 0, 10000, 0 }); } else { String fn = tk.NextToken(); if (fn.StartsWith("/")) { fn = fn.Substring(1); } ar.Add(new PdfName(fn)); for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k) { fn = tk.NextToken(); if (fn.Equals("null")) { ar.Add(PdfNull.PDFNULL); } else { ar.Add(new PdfNumber(fn)); } } } outline.Put(PdfName.DEST, ar); } } else if ("GoToR".Equals(action)) { String p; PdfDictionary dic = new PdfDictionary(); if ((p = GetVal(map, "Named")) != null) { dic.Put(PdfName.D, new PdfString(p, null)); } else if ((p = GetVal(map, "NamedN")) != null) { dic.Put(PdfName.D, new PdfName(p)); } else if ((p = GetVal(map, "Page")) != null) { PdfArray ar = new PdfArray(); StringTokenizer tk = new StringTokenizer(p); ar.Add(new PdfNumber(tk.NextToken())); if (!tk.HasMoreTokens()) { ar.Add(PdfName.XYZ); ar.Add(new float[] { 0, 10000, 0 }); } else { String fn = tk.NextToken(); if (fn.StartsWith("/")) { fn = fn.Substring(1); } ar.Add(new PdfName(fn)); for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k) { fn = tk.NextToken(); if (fn.Equals("null")) { ar.Add(PdfNull.PDFNULL); } else { ar.Add(new PdfNumber(fn)); } } } dic.Put(PdfName.D, ar); } String file = GetVal(map, "File"); if (dic.Size > 0 && file != null) { dic.Put(PdfName.S, PdfName.GOTOR); dic.Put(PdfName.F, new PdfString(file)); String nw = GetVal(map, "NewWindow"); if (nw != null) { if (nw.Equals("true")) { dic.Put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE); } else if (nw.Equals("false")) { dic.Put(PdfName.NEWWINDOW, PdfBoolean.PDFFALSE); } } outline.Put(PdfName.A, dic); } } else if ("URI".Equals(action)) { String uri = GetVal(map, "URI"); if (uri != null) { PdfDictionary dic = new PdfDictionary(); dic.Put(PdfName.S, PdfName.URI); dic.Put(PdfName.URI, new PdfString(uri)); outline.Put(PdfName.A, dic); } } else if ("JS".Equals(action)) { String code = GetVal(map, "Code"); if (code != null) { outline.Put(PdfName.A, PdfAction.JavaScript(code, writer)); } } else if ("Launch".Equals(action)) { String file = GetVal(map, "File"); if (file != null) { PdfDictionary dic = new PdfDictionary(); dic.Put(PdfName.S, PdfName.LAUNCH); dic.Put(PdfName.F, new PdfString(file)); outline.Put(PdfName.A, dic); } } } catch { // empty on purpose } }
/// <exception cref="System.Exception"/> private void CheckHistoryParsing(int numMaps, int numReduces, int numSuccessfulMaps ) { Configuration conf = new Configuration(); conf.Set(MRJobConfig.UserName, Runtime.GetProperty("user.name")); long amStartTimeEst = Runtime.CurrentTimeMillis(); conf.SetClass(CommonConfigurationKeysPublic.NetTopologyNodeSwitchMappingImplKey, typeof(TestJobHistoryParsing.MyResolver), typeof(DNSToSwitchMapping)); RackResolver.Init(conf); MRApp app = new TestJobHistoryEvents.MRAppWithHistory(numMaps, numReduces, true, this.GetType().FullName, true); app.Submit(conf); Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = app.GetContext().GetAllJobs().Values .GetEnumerator().Next(); JobId jobId = job.GetID(); Log.Info("JOBID is " + TypeConverter.FromYarn(jobId).ToString()); app.WaitForState(job, JobState.Succeeded); // make sure all events are flushed app.WaitForState(Service.STATE.Stopped); string jobhistoryDir = JobHistoryUtils.GetHistoryIntermediateDoneDirForUser(conf); FileContext fc = null; try { fc = FileContext.GetFileContext(conf); } catch (IOException ioe) { Log.Info("Can not get FileContext", ioe); throw (new Exception("Can not get File Context")); } if (numMaps == numSuccessfulMaps) { string summaryFileName = JobHistoryUtils.GetIntermediateSummaryFileName(jobId); Path summaryFile = new Path(jobhistoryDir, summaryFileName); string jobSummaryString = GetJobSummary(fc, summaryFile); NUnit.Framework.Assert.IsNotNull(jobSummaryString); NUnit.Framework.Assert.IsTrue(jobSummaryString.Contains("resourcesPerMap=100")); NUnit.Framework.Assert.IsTrue(jobSummaryString.Contains("resourcesPerReduce=100") ); IDictionary <string, string> jobSummaryElements = new Dictionary <string, string>(); StringTokenizer strToken = new StringTokenizer(jobSummaryString, ","); while (strToken.HasMoreTokens()) { string keypair = strToken.NextToken(); jobSummaryElements[keypair.Split("=")[0]] = keypair.Split("=")[1]; } NUnit.Framework.Assert.AreEqual("JobId does not match", jobId.ToString(), jobSummaryElements ["jobId"]); NUnit.Framework.Assert.AreEqual("JobName does not match", "test", jobSummaryElements ["jobName"]); NUnit.Framework.Assert.IsTrue("submitTime should not be 0", long.Parse(jobSummaryElements ["submitTime"]) != 0); NUnit.Framework.Assert.IsTrue("launchTime should not be 0", long.Parse(jobSummaryElements ["launchTime"]) != 0); NUnit.Framework.Assert.IsTrue("firstMapTaskLaunchTime should not be 0", long.Parse (jobSummaryElements["firstMapTaskLaunchTime"]) != 0); NUnit.Framework.Assert.IsTrue("firstReduceTaskLaunchTime should not be 0", long.Parse (jobSummaryElements["firstReduceTaskLaunchTime"]) != 0); NUnit.Framework.Assert.IsTrue("finishTime should not be 0", long.Parse(jobSummaryElements ["finishTime"]) != 0); NUnit.Framework.Assert.AreEqual("Mismatch in num map slots", numSuccessfulMaps, System.Convert.ToInt32 (jobSummaryElements["numMaps"])); NUnit.Framework.Assert.AreEqual("Mismatch in num reduce slots", numReduces, System.Convert.ToInt32 (jobSummaryElements["numReduces"])); NUnit.Framework.Assert.AreEqual("User does not match", Runtime.GetProperty("user.name" ), jobSummaryElements["user"]); NUnit.Framework.Assert.AreEqual("Queue does not match", "default", jobSummaryElements ["queue"]); NUnit.Framework.Assert.AreEqual("Status does not match", "SUCCEEDED", jobSummaryElements ["status"]); } JobHistory jobHistory = new JobHistory(); jobHistory.Init(conf); HistoryFileManager.HistoryFileInfo fileInfo = jobHistory.GetJobFileInfo(jobId); JobHistoryParser.JobInfo jobInfo; long numFinishedMaps; lock (fileInfo) { Path historyFilePath = fileInfo.GetHistoryFile(); FSDataInputStream @in = null; Log.Info("JobHistoryFile is: " + historyFilePath); try { @in = fc.Open(fc.MakeQualified(historyFilePath)); } catch (IOException ioe) { Log.Info("Can not open history file: " + historyFilePath, ioe); throw (new Exception("Can not open History File")); } JobHistoryParser parser = new JobHistoryParser(@in); EventReader realReader = new EventReader(@in); EventReader reader = Org.Mockito.Mockito.Mock <EventReader>(); if (numMaps == numSuccessfulMaps) { reader = realReader; } else { AtomicInteger numFinishedEvents = new AtomicInteger(0); // Hack! Org.Mockito.Mockito.When(reader.GetNextEvent()).ThenAnswer(new _Answer_257(realReader , numFinishedEvents, numSuccessfulMaps)); } jobInfo = parser.Parse(reader); numFinishedMaps = ComputeFinishedMaps(jobInfo, numMaps, numSuccessfulMaps); if (numFinishedMaps != numMaps) { Exception parseException = parser.GetParseException(); NUnit.Framework.Assert.IsNotNull("Didn't get expected parse exception", parseException ); } } NUnit.Framework.Assert.AreEqual("Incorrect username ", Runtime.GetProperty("user.name" ), jobInfo.GetUsername()); NUnit.Framework.Assert.AreEqual("Incorrect jobName ", "test", jobInfo.GetJobname( )); NUnit.Framework.Assert.AreEqual("Incorrect queuename ", "default", jobInfo.GetJobQueueName ()); NUnit.Framework.Assert.AreEqual("incorrect conf path", "test", jobInfo.GetJobConfPath ()); NUnit.Framework.Assert.AreEqual("incorrect finishedMap ", numSuccessfulMaps, numFinishedMaps ); NUnit.Framework.Assert.AreEqual("incorrect finishedReduces ", numReduces, jobInfo .GetFinishedReduces()); NUnit.Framework.Assert.AreEqual("incorrect uberized ", job.IsUber(), jobInfo.GetUberized ()); IDictionary <TaskID, JobHistoryParser.TaskInfo> allTasks = jobInfo.GetAllTasks(); int totalTasks = allTasks.Count; NUnit.Framework.Assert.AreEqual("total number of tasks is incorrect ", (numMaps + numReduces), totalTasks); // Verify aminfo NUnit.Framework.Assert.AreEqual(1, jobInfo.GetAMInfos().Count); NUnit.Framework.Assert.AreEqual(MRApp.NmHost, jobInfo.GetAMInfos()[0].GetNodeManagerHost ()); JobHistoryParser.AMInfo amInfo = jobInfo.GetAMInfos()[0]; NUnit.Framework.Assert.AreEqual(MRApp.NmPort, amInfo.GetNodeManagerPort()); NUnit.Framework.Assert.AreEqual(MRApp.NmHttpPort, amInfo.GetNodeManagerHttpPort() ); NUnit.Framework.Assert.AreEqual(1, amInfo.GetAppAttemptId().GetAttemptId()); NUnit.Framework.Assert.AreEqual(amInfo.GetAppAttemptId(), amInfo.GetContainerId() .GetApplicationAttemptId()); NUnit.Framework.Assert.IsTrue(amInfo.GetStartTime() <= Runtime.CurrentTimeMillis( ) && amInfo.GetStartTime() >= amStartTimeEst); ContainerId fakeCid = MRApp.NewContainerId(-1, -1, -1, -1); // Assert at taskAttempt level foreach (JobHistoryParser.TaskInfo taskInfo in allTasks.Values) { int taskAttemptCount = taskInfo.GetAllTaskAttempts().Count; NUnit.Framework.Assert.AreEqual("total number of task attempts ", 1, taskAttemptCount ); JobHistoryParser.TaskAttemptInfo taInfo = taskInfo.GetAllTaskAttempts().Values.GetEnumerator ().Next(); NUnit.Framework.Assert.IsNotNull(taInfo.GetContainerId()); // Verify the wrong ctor is not being used. Remove after mrv1 is removed. NUnit.Framework.Assert.IsFalse(taInfo.GetContainerId().Equals(fakeCid)); } // Deep compare Job and JobInfo foreach (Task task in job.GetTasks().Values) { JobHistoryParser.TaskInfo taskInfo_1 = allTasks[TypeConverter.FromYarn(task.GetID ())]; NUnit.Framework.Assert.IsNotNull("TaskInfo not found", taskInfo_1); foreach (TaskAttempt taskAttempt in task.GetAttempts().Values) { JobHistoryParser.TaskAttemptInfo taskAttemptInfo = taskInfo_1.GetAllTaskAttempts( )[TypeConverter.FromYarn((taskAttempt.GetID()))]; NUnit.Framework.Assert.IsNotNull("TaskAttemptInfo not found", taskAttemptInfo); NUnit.Framework.Assert.AreEqual("Incorrect shuffle port for task attempt", taskAttempt .GetShufflePort(), taskAttemptInfo.GetShufflePort()); if (numMaps == numSuccessfulMaps) { NUnit.Framework.Assert.AreEqual(MRApp.NmHost, taskAttemptInfo.GetHostname()); NUnit.Framework.Assert.AreEqual(MRApp.NmPort, taskAttemptInfo.GetPort()); // Verify rack-name NUnit.Framework.Assert.AreEqual("rack-name is incorrect", taskAttemptInfo.GetRackname (), RackName); } } } // test output for HistoryViewer TextWriter stdps = System.Console.Out; try { Runtime.SetOut(new TextWriter(outContent)); HistoryViewer viewer; lock (fileInfo) { viewer = new HistoryViewer(fc.MakeQualified(fileInfo.GetHistoryFile()).ToString() , conf, true); } viewer.Print(); foreach (JobHistoryParser.TaskInfo taskInfo_1 in allTasks.Values) { string test = (taskInfo_1.GetTaskStatus() == null ? string.Empty : taskInfo_1.GetTaskStatus ()) + " " + taskInfo_1.GetTaskType() + " task list for " + taskInfo_1.GetTaskId( ).GetJobID(); NUnit.Framework.Assert.IsTrue(outContent.ToString().IndexOf(test) > 0); NUnit.Framework.Assert.IsTrue(outContent.ToString().IndexOf(taskInfo_1.GetTaskId( ).ToString()) > 0); } } finally { Runtime.SetOut(stdps); } }
/// <exception cref="System.IO.IOException"/> protected internal virtual void Process() { RandomAccessFileOrArray raf = fontParser.GetMetricsFile(); String line; bool startKernPairs = false; while (!startKernPairs && (line = raf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line, " ,\n\r\t\f"); if (!tok.HasMoreTokens()) { continue; } String ident = tok.NextToken(); switch (ident) { case "FontName": { fontNames.SetFontName(tok.NextToken("\u00ff").Substring(1)); break; } case "FullName": { String fullName = tok.NextToken("\u00ff").Substring(1); fontNames.SetFullName(new String[][] { new String[] { "", "", "", fullName } }); break; } case "FamilyName": { String familyName = tok.NextToken("\u00ff").Substring(1); fontNames.SetFamilyName(new String[][] { new String[] { "", "", "", familyName } }); break; } case "Weight": { fontNames.SetFontWeight(FontWeights.FromType1FontWeight(tok.NextToken("\u00ff").Substring(1))); break; } case "ItalicAngle": { fontMetrics.SetItalicAngle(float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture) ); break; } case "IsFixedPitch": { fontMetrics.SetIsFixedPitch(tok.NextToken().Equals("true")); break; } case "CharacterSet": { characterSet = tok.NextToken("\u00ff").Substring(1); break; } case "FontBBox": { int llx = (int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture); int lly = (int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture); int urx = (int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture); int ury = (int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture); fontMetrics.SetBbox(llx, lly, urx, ury); break; } case "UnderlinePosition": { fontMetrics.SetUnderlinePosition((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture )); break; } case "UnderlineThickness": { fontMetrics.SetUnderlineThickness((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture )); break; } case "EncodingScheme": { encodingScheme = tok.NextToken("\u00ff").Substring(1).Trim(); break; } case "CapHeight": { fontMetrics.SetCapHeight((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture )); break; } case "XHeight": { fontMetrics.SetXHeight((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture )); break; } case "Ascender": { fontMetrics.SetTypoAscender((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture )); break; } case "Descender": { fontMetrics.SetTypoDescender((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture )); break; } case "StdHW": { fontMetrics.SetStemH((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture)); break; } case "StdVW": { fontMetrics.SetStemV((int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture)); break; } case "StartCharMetrics": { startKernPairs = true; break; } } } if (!startKernPairs) { String metricsPath = fontParser.GetAfmPath(); if (metricsPath != null) { throw new iText.IO.IOException("startcharmetrics is missing in {0}.").SetMessageParams(metricsPath); } else { throw new iText.IO.IOException("startcharmetrics is missing in the metrics file."); } } avgWidth = 0; int widthCount = 0; while ((line = raf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line); if (!tok.HasMoreTokens()) { continue; } String ident = tok.NextToken(); if (ident.Equals("EndCharMetrics")) { startKernPairs = false; break; } int C = -1; int WX = 250; String N = ""; int[] B = null; tok = new StringTokenizer(line, ";"); while (tok.HasMoreTokens()) { StringTokenizer tokc = new StringTokenizer(tok.NextToken()); if (!tokc.HasMoreTokens()) { continue; } ident = tokc.NextToken(); switch (ident) { case "C": { C = Convert.ToInt32(tokc.NextToken()); break; } case "WX": { WX = (int)float.Parse(tokc.NextToken(), System.Globalization.CultureInfo.InvariantCulture); break; } case "N": { N = tokc.NextToken(); break; } case "B": { B = new int[] { Convert.ToInt32(tokc.NextToken()), Convert.ToInt32(tokc.NextToken()), Convert.ToInt32(tokc .NextToken()), Convert.ToInt32(tokc.NextToken()) }; break; } } } int unicode = AdobeGlyphList.NameToUnicode(N); Glyph glyph = new Glyph(C, WX, unicode, B); if (C >= 0) { codeToGlyph.Put(C, glyph); } if (unicode != -1) { unicodeToGlyph.Put(unicode, glyph); } avgWidth += WX; widthCount++; } if (widthCount != 0) { avgWidth /= widthCount; } if (startKernPairs) { String metricsPath = fontParser.GetAfmPath(); if (metricsPath != null) { throw new iText.IO.IOException("endcharmetrics is missing in {0}.").SetMessageParams(metricsPath); } else { throw new iText.IO.IOException("endcharmetrics is missing in the metrics file."); } } // From AdobeGlyphList: // nonbreakingspace;00A0 // space;0020 if (!unicodeToGlyph.ContainsKey(0x00A0)) { Glyph space = unicodeToGlyph.Get(0x0020); if (space != null) { unicodeToGlyph.Put(0x00A0, new Glyph(space.GetCode(), space.GetWidth(), 0x00A0, space.GetBbox())); } } bool endOfMetrics = false; while ((line = raf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line); if (!tok.HasMoreTokens()) { continue; } String ident = tok.NextToken(); if (ident.Equals("EndFontMetrics")) { endOfMetrics = true; break; } else { if (ident.Equals("StartKernPairs")) { startKernPairs = true; break; } } } if (startKernPairs) { while ((line = raf.ReadLine()) != null) { StringTokenizer tok = new StringTokenizer(line); if (!tok.HasMoreTokens()) { continue; } String ident = tok.NextToken(); if (ident.Equals("KPX")) { String first = tok.NextToken(); String second = tok.NextToken(); int? width = (int)float.Parse(tok.NextToken(), System.Globalization.CultureInfo.InvariantCulture); int firstUni = AdobeGlyphList.NameToUnicode(first); int secondUni = AdobeGlyphList.NameToUnicode(second); if (firstUni != -1 && secondUni != -1) { long record = ((long)firstUni << 32) + secondUni; kernPairs.Put(record, width); } } else { if (ident.Equals("EndKernPairs")) { startKernPairs = false; break; } } } } else { if (!endOfMetrics) { String metricsPath = fontParser.GetAfmPath(); if (metricsPath != null) { throw new iText.IO.IOException("endfontmetrics is missing in {0}.").SetMessageParams(metricsPath); } else { throw new iText.IO.IOException("endfontmetrics is missing in the metrics file."); } } } if (startKernPairs) { String metricsPath = fontParser.GetAfmPath(); if (metricsPath != null) { throw new iText.IO.IOException("endkernpairs is missing in {0}.").SetMessageParams(metricsPath); } else { throw new iText.IO.IOException("endkernpairs is missing in the metrics file."); } } raf.Close(); isFontSpecific = !(encodingScheme.Equals("AdobeStandardEncoding") || encodingScheme.Equals("StandardEncoding" )); }
private string GetNextPart(StringTokenizer tokenizer, string deli) { string tokenAccumulator = null; bool isDoubleQuote = false; bool isSingleQuote = false; bool isDataReady = false; string currentToken; while (isDataReady == false && tokenizer.HasMoreTokens()) { currentToken = tokenizer.NextToken(deli); // // First let's combine tokens that are inside "" or '' // if (isDoubleQuote || isSingleQuote) { if (isDoubleQuote && currentToken[0] == doubleQuote) { isDoubleQuote = false; isDataReady = true; } else if (isSingleQuote && currentToken[0] == singleQuote) { isSingleQuote = false; isDataReady = true; } else { tokenAccumulator += currentToken; continue; } } else if (currentToken[0] == doubleQuote) { isDoubleQuote = true; tokenAccumulator = ""; continue; } else if (currentToken[0] == singleQuote) { isSingleQuote = true; tokenAccumulator = ""; continue; } else { tokenAccumulator = currentToken; } if (tokenAccumulator.Equals(currentToken)) { if (delim.IndexOf(tokenAccumulator) >= 0) { if (tokenAccumulator.Equals("=")) { isDataReady = true; } } else { isDataReady = true; } } else { isDataReady = true; } } return(tokenAccumulator); }
internal void MergeField(string name, AcroFields.Item item) { var map = FieldTree; var tk = new StringTokenizer(name, "."); if (!tk.HasMoreTokens()) { return; } while (true) { var s = tk.NextToken(); var obj = map[s]; if (tk.HasMoreTokens()) { if (obj == null) { obj = new Hashtable(); map[s] = obj; map = (Hashtable)obj; continue; } else if (obj is Hashtable) { map = (Hashtable)obj; } else { return; } } else { if (obj is Hashtable) { return; } var merged = item.GetMerged(0); if (obj == null) { var field = new PdfDictionary(); if (PdfName.Sig.Equals(merged.Get(PdfName.Ft))) { _hasSignature = true; } foreach (PdfName key in merged.Keys) { if (FieldKeys.ContainsKey(key)) { field.Put(key, merged.Get(key)); } } var list = new ArrayList { field }; CreateWidgets(list, item); map[s] = list; } else { var list = (ArrayList)obj; var field = (PdfDictionary)list[0]; var type1 = (PdfName)field.Get(PdfName.Ft); var type2 = (PdfName)merged.Get(PdfName.Ft); if (type1 == null || !type1.Equals(type2)) { return; } var flag1 = 0; var f1 = field.Get(PdfName.Ff); if (f1 != null && f1.IsNumber()) { flag1 = ((PdfNumber)f1).IntValue; } var flag2 = 0; var f2 = merged.Get(PdfName.Ff); if (f2 != null && f2.IsNumber()) { flag2 = ((PdfNumber)f2).IntValue; } if (type1.Equals(PdfName.Btn)) { if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0) { return; } if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0) { return; } } else if (type1.Equals(PdfName.Ch)) { if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0) { return; } } CreateWidgets(list, item); } return; } } }
/// <exception cref="System.Exception"/> public virtual int Run(string[] args) { Submitter.CommandLineParser cli = new Submitter.CommandLineParser(); if (args.Length == 0) { cli.PrintUsage(); return(1); } cli.AddOption("input", false, "input path to the maps", "path"); cli.AddOption("output", false, "output path from the reduces", "path"); cli.AddOption("jar", false, "job jar file", "path"); cli.AddOption("inputformat", false, "java classname of InputFormat", "class"); //cli.addArgument("javareader", false, "is the RecordReader in Java"); cli.AddOption("map", false, "java classname of Mapper", "class"); cli.AddOption("partitioner", false, "java classname of Partitioner", "class"); cli.AddOption("reduce", false, "java classname of Reducer", "class"); cli.AddOption("writer", false, "java classname of OutputFormat", "class"); cli.AddOption("program", false, "URI to application executable", "class"); cli.AddOption("reduces", false, "number of reduces", "num"); cli.AddOption("jobconf", false, "\"n1=v1,n2=v2,..\" (Deprecated) Optional. Add or override a JobConf property." , "key=val"); cli.AddOption("lazyOutput", false, "Optional. Create output lazily", "boolean"); Parser parser = cli.CreateParser(); try { GenericOptionsParser genericParser = new GenericOptionsParser(GetConf(), args); CommandLine results = parser.Parse(cli.options, genericParser.GetRemainingArgs()); JobConf job = new JobConf(GetConf()); if (results.HasOption("input")) { FileInputFormat.SetInputPaths(job, results.GetOptionValue("input")); } if (results.HasOption("output")) { FileOutputFormat.SetOutputPath(job, new Path(results.GetOptionValue("output"))); } if (results.HasOption("jar")) { job.SetJar(results.GetOptionValue("jar")); } if (results.HasOption("inputformat")) { SetIsJavaRecordReader(job, true); job.SetInputFormat(GetClass <InputFormat>(results, "inputformat", job)); } if (results.HasOption("javareader")) { SetIsJavaRecordReader(job, true); } if (results.HasOption("map")) { SetIsJavaMapper(job, true); job.SetMapperClass(GetClass <Mapper>(results, "map", job)); } if (results.HasOption("partitioner")) { job.SetPartitionerClass(GetClass <Partitioner>(results, "partitioner", job)); } if (results.HasOption("reduce")) { SetIsJavaReducer(job, true); job.SetReducerClass(GetClass <Reducer>(results, "reduce", job)); } if (results.HasOption("reduces")) { job.SetNumReduceTasks(System.Convert.ToInt32(results.GetOptionValue("reduces"))); } if (results.HasOption("writer")) { SetIsJavaRecordWriter(job, true); job.SetOutputFormat(GetClass <OutputFormat>(results, "writer", job)); } if (results.HasOption("lazyOutput")) { if (System.Boolean.Parse(results.GetOptionValue("lazyOutput"))) { LazyOutputFormat.SetOutputFormatClass(job, job.GetOutputFormat().GetType()); } } if (results.HasOption("program")) { SetExecutable(job, results.GetOptionValue("program")); } if (results.HasOption("jobconf")) { Log.Warn("-jobconf option is deprecated, please use -D instead."); string options = results.GetOptionValue("jobconf"); StringTokenizer tokenizer = new StringTokenizer(options, ","); while (tokenizer.HasMoreTokens()) { string keyVal = tokenizer.NextToken().Trim(); string[] keyValSplit = keyVal.Split("="); job.Set(keyValSplit[0], keyValSplit[1]); } } // if they gave us a jar file, include it into the class path string jarFile = job.GetJar(); if (jarFile != null) { Uri[] urls = new Uri[] { FileSystem.GetLocal(job).PathToFile(new Path(jarFile)).ToURL () }; //FindBugs complains that creating a URLClassLoader should be //in a doPrivileged() block. ClassLoader loader = AccessController.DoPrivileged(new _PrivilegedAction_494(urls )); job.SetClassLoader(loader); } RunJob(job); return(0); } catch (ParseException pe) { Log.Info("Error : " + pe); cli.PrintUsage(); return(1); } }