public MenuInputWidget( Game game, Font font, Font boldFont ) : base(game) { HorizontalAnchor = Anchor.LeftOrTop; VerticalAnchor = Anchor.BottomOrRight; this.font = font; this.boldFont = boldFont; chatInputText = new StringBuffer( 64 ); }
public void StringBuffer_Create() { StringBuffer buffer = new StringBuffer("Hello World"); Assert.AreEqual("Hello World", buffer.Content); Assert.AreEqual(11, buffer.Length); Assert.AreEqual(0, buffer.Position); }
public void StringBuffer_Peek() { StringBuffer buffer = new StringBuffer("Hello World"); Assert.AreEqual(0, buffer.Position); Assert.AreEqual('H', (char)buffer.Peek()); Assert.AreEqual(0, buffer.Position); }
void Awake() { inputBuffer = new StringBuffer(); currentIllnesses = new List<Illness>(); illnessesDef = new List<Illness>(); tooSlowText = GameObject.Find("TooSlow"); tooSlowText.SetActive(false); if (PlayerPrefs.GetInt("hardmode") == 1) { illnessesDef.Add(new Illness("Arrow", "udruldur", 2.1f)); illnessesDef.Add(new Illness("Axe", "llurdul", 1.8f)); illnessesDef.Add(new Illness("Eye", "lrlruld", 2.0f)); illnessesDef.Add(new Illness("Hair", "udldrulu", 2.1f)); illnessesDef.Add(new Illness("Green", "dudulrud", 2.3f)); illnessesDef.Add(new Illness("Knife", "rulruudru", 2.3f)); } else { illnessesDef.Add(new Illness("Arrow", "dudu", 0.8f)); illnessesDef.Add(new Illness("Axe", "udlr", 0.8f)); illnessesDef.Add(new Illness("Eye", "lurldr", 1.3f)); illnessesDef.Add(new Illness("Hair", "uurdd", 1.3f)); illnessesDef.Add(new Illness("Green", "lldrru", 1.5f)); illnessesDef.Add(new Illness("Knife", "durulu", 1.5f)); } gameManager = GetComponent<GameManager>(); checkSequence = false; }
public override string toString() { StringBuffer stringBuffer = new StringBuffer("AxisEntity: "); stringBuffer.append("tooltip = "); stringBuffer.append(this.getToolTipText()); return stringBuffer.toString(); }
/** * convert byte array to Hex String. * * @param info - the propmt String * @param buf - the byte array which will be converted * @param offset - the start position of buf * @param length - the converted length * @param isOneLine16 - if true 16 bytes one line, false all bytes in one line * @return Hex String */ public static string buf2String(string info, byte[] buf, int offset, int length, bool oneLine16) { int i, index; StringBuffer sBuf = new StringBuffer(); sBuf.Append(info); for (i = 0 + offset; i < length + offset; i++) { if (i % 16 == 0) { if (oneLine16) { sBuf.Append(lineSeperate); } } else if (i % 8 == 0) { if (oneLine16) { sBuf.Append(" "); } } index = buf[i] < 0 ? buf[i] + DEFAULT_TABLE_LENGTH : buf[i]; sBuf.Append(convertTable[index]); } return sBuf.ToString(); }
public IXmlAttributeValue Parse(IXmlAttributeValue xmlAttributeValue) { ReferenceNameAttributeValue attributeValue = new ReferenceNameAttributeValue(); CompositeElement result = null; string rawValue = xmlAttributeValue.UnquotedValue; try { result = ParseTypeNameOrAttributeValue(rawValue); } catch (SyntaxError syntaxError) { result = (CompositeElement)syntaxError.ParsingResult; result = handleError(result, syntaxError); } attributeValue.AddChild(new XmlToken(L4NTokenNodeType.QUOTE, new StringBuffer(new string('\"', 1)), 0, 1)); attributeValue.AddChild(result); int resultLegth = result.GetText().Length; if(resultLegth < rawValue.Length) { string suffix = rawValue.Substring(resultLegth); StringBuffer sb = new StringBuffer(suffix); XmlToken suffixToken = new XmlToken(L4NTokenNodeType.TEXT , sb, 0, suffix.Length); attributeValue.AddChild(suffixToken); } attributeValue.AddChild(new XmlToken(L4NTokenNodeType.QUOTE, new StringBuffer(new string('\"', 1)), 0, 1)); return attributeValue; }
public void IsExtendedTest(string path, bool expected) { StringBuffer sb = new StringBuffer(); sb.Append(path); Assert.Equal(expected, PathInternal.IsExtended(sb)); Assert.Equal(expected, PathInternal.IsExtended(path)); }
private StringBuffer GetBuffer() { if (this._buffer == null) this._buffer = new StringBuffer(4096); else this._buffer.Position = 0; return this._buffer; }
public void StringBuffer_Rewind() { StringBuffer buffer = new StringBuffer("Hello World"); Assert.IsTrue(buffer.Seek(6)); Assert.AreEqual(6, buffer.Position); buffer.Rewind(); Assert.AreEqual(0, buffer.Position); }
private static string ByteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.Length; i++) resultSb.Append(ByteToHexString(b[i])); return resultSb.ToString(); }
public override string toString() { StringBuffer stringBuffer = new StringBuffer("CategoryLabelEntity: "); stringBuffer.append("category="); stringBuffer.append((object) this.key); stringBuffer.append(new StringBuffer().append(", tooltip=").append(this.getToolTipText()).toString()); stringBuffer.append(new StringBuffer().append(", url=").append(this.getURLText()).toString()); return stringBuffer.toString(); }
/// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param> public JsonTextReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); _reader = reader; _buffer = new StringBuffer(4096); _currentLineNumber = 1; }
public void setUp() { aMap = new ExtendableMap(); aMap.addBidirectionalLink("A", "B", 5.0); aMap.addBidirectionalLink("A", "C", 6.0); aMap.addBidirectionalLink("B", "C", 4.0); aMap.addBidirectionalLink("C", "D", 7.0); aMap.addUnidirectionalLink("B", "E", 14.0); envChanges = new StringBuffer(); }
/// <summary> /// Instantiate the buffer with a copy of the specified StringBuffer. /// </summary> public StringBuffer(StringBuffer initialContents) : base(0) { // We don't pass the count of bytes to the base constructor, appending will // initialize to the correct size for the specified initial contents. if (initialContents != null) { Append(initialContents); } }
public static string GetModelCodeFormDb(string tableName) { using (var session = new SessionFactory().OpenSession()) { var model = session.FindBySql<DbTable>("show full fields from " + tableName); if (model == null || model.Count == 0) { // table不存在 return null; } var tb = new StringBuffer(); foreach (var col in model) { tb += Environment.NewLine; if (col.Null.Equals("NO")) { tb += string.Format("[Required]{0}", Environment.NewLine); } if (col.Key.Equals("PRI")) { tb += "[PrimaryKey]" + Environment.NewLine; } if (!string.IsNullOrEmpty(col.Comment)) { tb += string.Format("[DisplayName(\"{0}\")]{1}", col.Comment, Environment.NewLine); } var type = col.Type; if (type.Contains("(")) { var temp = type.Split('('); type = temp[0]; var length = temp[1].Substring(0, temp[1].LastIndexOf(")", StringComparison.Ordinal)); if (type.Equals("text") || type.Equals("varchar")) tb += string.Format("[StringLength({0})]{1}", length, Environment.NewLine); } var name = col.Field.Pascalize(); var mappingDic = new Dictionary<string, string> { {"tinyint", "bool"}, {"int", "int"}, {"bigint", "long"}, {"varchar", "string"}, {"text", "string"}, {"datetime", "DateTime"}, {"decimal", "Decimal"} }; //未匹配的默认为string var typeStr = mappingDic[type] ?? "string"; tb += string.Format("public {0}{1}{2}{3}{4}", typeStr, (col.Null.Equals("YES") && !typeStr.Equals("string") ? "? " : " "), name, "{get; set;}", Environment.NewLine); } return tb.ToString(); } }
public virtual void insertString(int offs, string str, AttributeSet a) { if (str == null) return; if (this.maxlen < 0) base.insertString(offs, str, a); char[] chArray = String.instancehelper_toCharArray(str); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(chArray, 0, Math.min(this.maxlen, chArray.Length)); base.insertString(offs, stringBuffer.toString(), a); }
public virtual StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { string str = String.instancehelper_toUpperCase(Long.toHexString(number)); int num1 = this.m_numDigits - String.instancehelper_length(str); int num2 = 0 >= num1 ? 0 : num1; StringBuffer stringBuffer = new StringBuffer("0x"); for (int index = 0; index < num2; ++index) stringBuffer.append(0); stringBuffer.append(str); return stringBuffer; }
public static void SetAttributeValiue(IXmlAttribute attribute, string newValue) { if (newValue == null) throw new ArgumentNullException("newValue"); Assert.CheckNotNull(attribute.Value, "attribute.Value"); IXmlAttributeValueNode oldValueNode = attribute.Value.ToTreeNode(); StringBuffer buffer = new StringBuffer("\"" + newValue + "\""); XmlTokenTypes types = XmlTokenTypeFactory.GetTokenTypes(attribute.Language); XmlValueToken newValueNode = new XmlValueToken(types.STRING, buffer, 0, buffer.Length); LowLevelModificationUtil.ReplaceChildRange(oldValueNode, oldValueNode, new ITreeNode[] { newValueNode }); }
/// <summary>Adds the blank line after.</summary> /// <param name="statement">The statement.</param> public void AddBlankLineAfter([NotNull] IStatement statement) { if (statement == null) { throw new ArgumentNullException("statement"); } var newLineText = new StringBuffer("\r\n"); ITreeNode newLine = TreeElementFactory.CreateLeafElement(CSharpTokenType.NEW_LINE, newLineText, 0, newLineText.Length); ModificationUtil.AddChildAfter(statement, newLine); }
public static string join(string delimiter, Collection values) { StringBuffer stringBuffer = new StringBuffer(); Iterator iterator = values.iterator(); while (iterator.hasNext()) { object obj = iterator.next(); stringBuffer.append(ParameterizedAssertionError.stringValueOf(obj)); if (iterator.hasNext()) stringBuffer.append(delimiter); } return stringBuffer.toString(); }
protected internal virtual File performSelectFile(File selectedFile, int dialogType, bool appendExtension) { if (this.fileChooser == null) this.fileChooser = this.createFileChooser(); this.fileChooser.setSelectedFile(selectedFile); this.fileChooser.setDialogType(dialogType); if (this.fileChooser.showDialog(this.parent, (string) null) != 0) return (File) null; string @base = this.fileChooser.getSelectedFile().getAbsolutePath(); if (!StringUtils.endsWithIgnoreCase(@base, this.getFileExtension())) @base = new StringBuffer().append(@base).append(this.getFileExtension()).toString(); return new File(@base); }
/// <summary> /// Returns a human readable text of this entry /// </summary> /// <returns></returns> public unsafe StringBuffer ToStringBuffer() { var buf = new StringBuffer(); buf.Append("0x"); buf.Append((uint)MethodDefinition->Method, "X"); buf.Append("+0x"); buf.Append(Offset, "X"); buf.Append(" "); var idx = MethodName.IndexOf(' ') + 1; //Skip return type buf.Append(MethodName, idx); return buf; }
protected ILexer CreateLexer(IProjectFile projectFile, StreamReader sr) { var lexer = this.CreateLexer(sr); if (lexer != null) { return lexer; } var buffer = new StringBuffer(sr.ReadToEnd()); var sourceFile = projectFile.ToSourceFile(); Assert.IsNotNull(sourceFile, "sourceFile == null"); var lexerFactory = PsiProjectFileTypeCoordinator.Instance.CreateLexerFactory(this.Solution, sourceFile, buffer); Assert.IsNotNull(lexerFactory, "lexerFactory == null"); return lexerFactory.CreateLexer(buffer); }
public static void FormatDecimal(StringBuffer formatter, uint* value, StringView specifier, CachedCulture culture) { int digits; var fmt = ParseFormatSpecifier(specifier, out digits); var number = new Number(); var buffer = stackalloc char[MaxNumberDigits + 1]; number.Digits = buffer; DecimalToNumber(value, ref number); if (fmt != 0) NumberToString(formatter, ref number, fmt, digits, culture, isDecimal: true); else NumberToCustomFormatString(formatter, ref number, specifier, culture); }
public Year(int year) { Year year1 = this; if (year < -9999 || year > 9999) { string str = new StringBuffer().append("Year constructor: year (").append(year).append(") outside valid range.").toString(); Throwable.__\u003CsuppressFillInStackTrace\u003E(); throw new IllegalArgumentException(str); } else { this.year = (short) year; this.peg(Calendar.getInstance()); } }
public Range(double lower, double upper) { base.\u002Ector(); Range range = this; if (lower > upper) { string str = new StringBuffer().append("Range(double, double): require lower (").append(lower).append(") <= upper (").append(upper).append(").").toString(); Throwable.__\u003CsuppressFillInStackTrace\u003E(); throw new IllegalArgumentException(str); } else { this.lower = lower; this.upper = upper; } }
public void StringBuffer_Read() { StringBuffer buffer = new StringBuffer("Hello World"); Assert.AreEqual('H', (char)buffer.Read()); Assert.AreEqual('e', (char)buffer.Read()); Assert.AreEqual('l', (char)buffer.Read()); Assert.AreEqual('l', (char)buffer.Read()); Assert.AreEqual('o', (char)buffer.Read()); Assert.AreEqual(' ', (char)buffer.Read()); Assert.AreEqual('W', (char)buffer.Read()); Assert.AreEqual('o', (char)buffer.Read()); Assert.AreEqual('r', (char)buffer.Read()); Assert.AreEqual('l', (char)buffer.Read()); Assert.AreEqual('d', (char)buffer.Read()); Assert.AreEqual(-1, buffer.Read()); }
string GetColourString() { int count = 0; for( int i = ' '; i <= '~'; i++ ) { if( i >= 'A' && i <= 'F' ) continue; if( game.Drawer2D.Colours[i].A > 0 ) count++; } StringBuffer buffer = new StringBuffer( count * 4 ); int index = 0; for( int i = ' '; i <= '~'; i++ ) { if( i >= 'A' && i <= 'F' ) continue; if( game.Drawer2D.Colours[i].A == 0 ) continue; buffer.Append( ref index, '&' ).Append( ref index, (char)i ) .Append( ref index, '%' ).Append( ref index, (char)i ); } return buffer.ToString(); }
protected override void DoOneTest(string testName) { Logger.Catch(() => { testName = testName + ".js"; var testFile = GetTestDataFilePath2(testName); ExecuteWithGold(testName, writer => { var expressions = File.ReadAllLines(testFile.FullPath); foreach (var angularJsExpression in expressions) { var buffer = new StringBuffer(angularJsExpression); var lexer = new AngularJsLexerGenerated(buffer); var parser = new AngularJsParser(lexer); try { var parsedFile = parser.ParseFile(); Assert.NotNull(parsedFile); writer.WriteLine("Expression: «{0}»", angularJsExpression); writer.WriteLine("Language: {0}", parsedFile.Language); DebugUtil.DumpPsi(writer, parsedFile); writer.WriteLine(); var containingFile = parsedFile.GetContainingFile(); if (containingFile != null) { var rangeTranslator = ((IFileImpl) containingFile).SecondaryRangeTranslator as RangeTranslatorWithGeneratedRangeMap; if (rangeTranslator != null) WriteCommentedText(writer, "//", rangeTranslator.Dump(containingFile)); } } catch (Exception e) { writer.WriteLine(e); } } }); }); }
/// <summary> /// More http://www.w3.org/TR/REC-xml/#NT-VersionInfo. /// </summary> /// <param name="c">The next input character.</param> /// <param name="q">The quote character.</param> /// <param name="decl">The current declaration token.</param> XmlToken DeclarationVersionValue(Char c, Char q, XmlDeclarationToken decl) { while (c != q) { if (c == Symbols.EndOfFile) { throw XmlParseError.EOF.At(GetCurrentPosition()); } StringBuffer.Append(c); c = GetNext(); } decl.Version = FlushBuffer(); c = GetNext(); if (c.IsSpaceCharacter()) { return(DeclarationAfterVersion(c, decl)); } return(DeclarationEnd(c, decl)); }
public override BaseHelper GetField(Dictionary <string, object> wheres, QueryObj query, string whichColumn = null) { string showCols = whichColumn ?? CurrentTable.PrimaryKey; if (!CurrentTable.Columns.ContainsKey(whichColumn)) { return(End(string.Empty, string.Empty)); } StringBuffer orderBySql = string.IsNullOrEmpty(query.SortOn) ? string.Empty : (" Order By " + query.SortOn); WhereCondition which = MakeWhere(wheres); var sql = new StringBuffer(); //"Select " + showCols + " FROM " + CurrentTable.Name + which.WhereSql + orderBySql + " ;"; sql.AppendFormat("SELECT {0} FROM {1} {2} {3};", showCols, CurrentTable.Name, which.WhereSql, orderBySql); //HttpContext.Current.Response.Write("<hr>"+sql + "<hr><hr>"); //return this; object objVal = dac.ExecuteScalar(sql, which.Params); return(End(objVal, sql)); }
protected override void OnBindData(RecyclerView.ViewHolder viewHolder, int position, BooksByTag.TagBook item) { StringBuffer sbTags = new StringBuffer(); foreach (string tag in item.tags) { if (!TextUtils.IsEmpty(tag)) { sbTags.Append(tag); sbTags.Append(" | "); } } var holder = viewHolder as EasyRVHolder; holder.setRoundImageUrl(Resource.Id.ivBookCover, Constant.IMG_BASE_URL + item.cover, Resource.Drawable.cover_default) .setText(Resource.Id.tvBookListTitle, item.title) .setText(Resource.Id.tvShortIntro, item.shortIntro) .setText(Resource.Id.tvTags, (item.tags.Count() == 0 ? "" : sbTags.Substring(0, sbTags .LastIndexOf(" | ")))); holder.Click += (sender, e) => { itemClickListener.onItemClick(holder.getItemView(), position, item); }; }
/// <summary> /// See 8.2.4.54 DOCTYPE name state /// </summary> /// <param name="doctype">The current doctype token.</param> /// <returns>The emitted token.</returns> private XmlToken DoctypeName(XmlDoctypeToken doctype) { var c = GetNext(); while (c.IsXmlName()) { StringBuffer.Append(c); c = GetNext(); } doctype.Name = FlushBuffer(); if (c == Symbols.GreaterThan) { return(doctype); } else if (c.IsSpaceCharacter()) { return(DoctypeNameAfter(doctype)); } throw XmlParseError.DoctypeInvalid.At(GetCurrentPosition()); }
/// <summary> /// More http://www.w3.org/TR/REC-xml/#NT-XMLDecl. /// </summary> private XmlToken DeclarationStart() { var c = GetNext(); if (!c.IsSpaceCharacter()) { StringBuffer.Append(TagNames.Xml); return(ProcessingTarget(c, NewProcessing())); } do { c = GetNext(); }while (c.IsSpaceCharacter()); if (ContinuesWithSensitive(AttributeNames.Version)) { Advance(6); return(DeclarationVersionAfterName(NewDeclaration())); } throw XmlParseError.XmlDeclarationInvalid.At(GetCurrentPosition()); }
/// <summary> /// See http://www.w3.org/TR/REC-xml/#NT-CData. /// </summary> private XmlCDataToken CData() { var c = GetNext(); while (true) { if (c == Symbols.EndOfFile) { throw XmlParseError.EOF.At(GetCurrentPosition()); } if (c == Symbols.SquareBracketClose && ContinuesWithSensitive("]]>")) { Advance(2); break; } StringBuffer.Append(c); c = GetNext(); } return(NewCharacterData()); }
/// <summary> /// Delete /// </summary> /// <param name="wheres"></param> /// <returns></returns> public override BaseHelper Del(Dictionary <string, object> wheres) { if (wheres == null) { throw new InvalidExpressionException("Error: 'WHERE' condition can't be null."); } WhereCondition whereObj = MakeWhere(wheres); var sql = new StringBuffer(); sql.AppendFormat("Delete From {0}{1} {2};", Schema, CurrentTable.Name, whereObj.WhereSql); //SELECT ROW_COUNT(); if (inTrans) { return(SetTrans(sql, whereObj.Params)); } else { int v = dac.ExecuteNonQuery(sql, whereObj.Params); return(End(v, sql)); } }
public static void AppendPropertyName(this StringBuffer sb, string propertyName) { sb.EnsureCapacity(propertyName.Length + 4); var buffer = sb.Buffer; var position = sb.Length; buffer[position++] = '\"'; var len = propertyName.Length; for (var i = 0; i < len; i++) { buffer[position + i] = propertyName[i]; } position += len; buffer[position++] = '\"'; buffer[position++] = ':'; buffer[position++] = ' '; sb.Length = position; }
public async Task <bool> AreWeFileHandling(Document document) { if (!BittrexFileUploadState.Waiting) { return(false); } _log.LogInformation($"Am I waiting for the file? = {BittrexFileUploadState.Waiting}"); if (document == null) { var message = new StringBuffer(); message.Append(StringContants.DidNotRecieveFile); await _bus.SendAsync(new SendMessageCommand(message)); BittrexFileUploadState.Reset(); return(true); } await _bus.SendAsync(new BittrexTradeExportCommand(document.FileId)); BittrexFileUploadState.Reset(); return(true); }
public static String HexDump(Byte[] data1, Int32 len, Boolean showAddress) { StringBuffer result = new StringBuffer(); StringBuffer charfield = new StringBuffer(); var i = 0; while (i < len) { if ((i & 0xf) == 0) { if (showAddress) { var address = i.ToString("X4"); address = ("0000".Substring(0, 4 - address.Length) + address).ToUpper(); result.Append(address + ": "); } } Int32 v = data1[i]; result.Append(Hex2(v)); result.Append(" "); charfield.Append(ReadableChar(v)); i++; if ((i & 0xf) == 0) { result.Append(charfield); result.Append("\\n"); charfield.Length = 0; } else if ((i & 0xf) == 8) { result.Append(" "); } } return(result.ToString()); }
public Highlighter(string text) { var stripped = Stripper.Matcher(text).ReplaceAll(""); Mask = new bool[stripped.Length]; var m = HIGHLIGHTER.Matcher(stripped); var pos = 0; var lastMatch = 0; while (m.Find()) { pos += (m.Start() - lastMatch); var groupLen = m.Group(1).Length; for (var i = pos; i < pos + groupLen; i++) { Mask[i] = true; } pos += groupLen; lastMatch = m.End(); } m.Reset(text); var sb = new StringBuffer(); while (m.Find()) { m.AppendReplacement(sb, m.Group(1)); } m.AppendTail(sb); Text = sb.ToString(); }
public async Task Handle(BittrexTradeExportCommand command) { try { var bot = new TelegramBotClient(_config.BotToken); var file = await bot.GetFileAsync(command.FileId); var trades = BittrexConvertor.BittrexFileToTrades(file.FileStream, _log); await _databaseService.DeleteAllTrades(Constants.Bittrex); var newTrades = await _databaseService.AddTrades(trades); var sb = new StringBuffer(); sb.Append(string.Format("{0} new bittrex trades added.", newTrades.Count)); await _bus.SendAsync(new SendMessageCommand(sb)); } catch (Exception) { var sb = new StringBuffer(); sb.Append(StringContants.CouldNotProcessFile); await _bus.SendAsync(new SendMessageCommand(sb)); } }
//帮助文档 private void Help_Click(object sender, EventArgs e) { var fs = Resources.OpenRawResource(Resource.Raw.Help); InputStreamReader read = new InputStreamReader(fs, "gbk"); BufferedReader reader = new BufferedReader(read); StringBuffer sb = new StringBuffer(""); while (true) { var line = reader.ReadLine(); if (line == null) { break; } sb.Append(line); sb.Append("\n"); } read.Close(); fs.Close(); reader.Close(); MessageBox.Show(sb.ToString()); }
public unsafe void CopyTo(uint bufferIndex, StringBuffer destination, uint destinationIndex, uint count) { if (destination == null) { throw new ArgumentNullException("destination"); } if (destinationIndex > destination._length) { throw new ArgumentOutOfRangeException("destinationIndex"); } if (bufferIndex >= _length) { throw new ArgumentOutOfRangeException("bufferIndex"); } if (_length < checked (bufferIndex + count)) { throw new ArgumentOutOfRangeException("count"); } if (count == 0) { return; } uint lastIndex = checked (destinationIndex + count); if (destination._length < lastIndex) { destination.Length = lastIndex; } Buffer.MemoryCopy( source: CharPointer + bufferIndex, destination: destination.CharPointer + destinationIndex, destinationSizeInBytes: checked ((long)(destination.ByteCapacity - (destinationIndex * sizeof(char)))), sourceBytesToCopy: checked ((long)count * sizeof(char))); }
private Token HashStart() { var current = GetNext(); if (current.IsNameStart()) { StringBuffer.Append(current); return(HashRest()); } if (IsValidEscape(current)) { current = GetNext(); StringBuffer.Append(ConsumeEscape(current)); return(HashRest()); } if (current == Symbols.ReverseSolidus) { RaiseErrorOccurred(ParseError.InvalidCharacter); Back(); return(NewDelimiter(Symbols.Num)); } Back(); return(NewDelimiter(Symbols.Num)); }
public override bool DeleteUserPropsForAdmin(UserPropFilter filter, int topCount, out int deletedCount) { deletedCount = 0; using (SqlQuery query = new SqlQuery()) { string conditions = BuildCondition(query, filter); StringBuffer sql = new StringBuffer(); sql += @" DECLARE @DeleteData table (UserPropID int); INSERT INTO @DeleteData SELECT TOP (@TopCount) [UserPropID] FROM [bx_UserPropsView] WHERE " + conditions + @"; DELETE [bx_UserPropsView] WHERE UserPropID IN (SELECT [UserPropID] FROM @DeleteData); SELECT @@ROWCOUNT;"; query.CreateTopParameter("@TopCount", topCount); query.CommandText = sql.ToString(); using (XSqlDataReader reader = query.ExecuteReader()) { DeleteResult deleteResult = new DeleteResult(); if (reader.Read()) { deletedCount = reader.Get <int>(0); } return(true); } } }
public static string Encode(byte[] var0) { StringBuffer var1 = new StringBuffer(); int var2 = var0.Length; int var3 = 0; while (var3 < var2) { int var4 = var0[var3++] & 255; if (var3 == var2) { var1.Append(Base64EncodeChars[var4 >> 2]); var1.Append(Base64EncodeChars[(var4 & 3) << 4]); var1.Append("=="); break; } int var5 = var0[var3++] & 255; if (var3 == var2) { var1.Append(Base64EncodeChars[var4 >> 2]); var1.Append(Base64EncodeChars[(var4 & 3) << 4 | (var5 & 240) >> 4]); var1.Append(Base64EncodeChars[(var5 & 15) << 2]); var1.Append("="); break; } int var6 = var0[var3++] & 255; var1.Append(Base64EncodeChars[var4 >> 2]); var1.Append(Base64EncodeChars[(var4 & 3) << 4 | (var5 & 240) >> 4]); var1.Append(Base64EncodeChars[(var5 & 15) << 2 | (var6 & 192) >> 6]); var1.Append(Base64EncodeChars[var6 & 63]); } return(var1.ToString()); }
private void btnDBCreateIndex_Click(object sender, EventArgs e) { StringBuffer sql = "SELECT TOP 1000 Id,FirstName,LastName FROM Person(NOLOCK)"; try { IList<Person> listPersons = EntityConvertor.QueryForList<Person>(sql.ToString(), strSqlConn, null); SetOutput("======================DB索引创建开始==============================="); IndexModifier modifier = new IndexModifier(INDEX_STORE_PATH, new StandardAnalyzer(), true); #region 同步创建索引 Stopwatch watch = new Stopwatch(); watch.Start(); IndexDB(modifier, listPersons); modifier.Optimize();//优化索引 modifier.Close();//关闭索引读写器 watch.Stop(); StringBuffer sb = "索引完成,共用时:" + watch.Elapsed.Hours + "时 " + watch.Elapsed.Minutes + "分 " + watch.Elapsed.Seconds + "秒 " + watch.Elapsed.Milliseconds + "毫秒"; SetOutput(sb); #endregion //#region 异步创建索引 //dtStart = DateTime.Now; //AsyncIndexDBCaller caller = new AsyncIndexDBCaller(IndexDB); //IAsyncResult ar = caller.BeginInvoke(modifier, listPersons, new AsyncCallback(IndexCallback), modifier); //#endregion } catch (Exception ex) { SetOutput(ex.Message); } }
public InputWidget(Game game, Font font, string prefix, int maxLines) : base(game) { Text = new StringBuffer(Utils.StringLength * maxLines); lines = new string[maxLines]; lineSizes = new Size[maxLines]; this.font = font; Prefix = prefix; DrawTextArgs args = new DrawTextArgs("_", font, true); caretTex = game.Drawer2D.MakeTextTexture(ref args, 0, 0); caretTex.Width = (ushort)((caretTex.Width * 3) / 4); caretWidth = caretTex.Width; if (Prefix == null) { return; } args = new DrawTextArgs(Prefix, font, true); Size size = game.Drawer2D.MeasureText(ref args); prefixWidth = Width = size.Width; prefixHeight = Height = size.Height; }
public void AppendTests(string source, string value, int startIndex, int count, string expected) { // From string using (var buffer = new StringBuffer(source)) { buffer.Append(value, startIndex, count); buffer.ToString().Should().Be(expected); } // From buffer using (var buffer = new StringBuffer(source)) using (var valueBuffer = new StringBuffer(value)) { if (count == -1) { buffer.Append(valueBuffer, (uint)startIndex); } else { buffer.Append(valueBuffer, (uint)startIndex, (uint)count); } buffer.ToString().Should().Be(expected); } }
private Token Comment() { var current = GetNext(); while (current != Symbols.EndOfFile) { if (current == Symbols.Asterisk) { current = GetNext(); if (current == Symbols.Solidus) { return(NewComment(FlushBuffer())); } StringBuffer.Append(Symbols.Asterisk); } else { StringBuffer.Append(current); current = GetNext(); } } RaiseErrorOccurred(ParseError.EOF); return(NewComment(FlushBuffer(), true)); }
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmSectionBlockSplitToken splitToken, MarkdownBlockContext context) { StringBuffer content = string.Empty; if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n")) { Logger.LogWarning( "The content part of [!div] syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.MissingNewLineBelowSectionHeader); } content += "<div"; content += ((DfmSectionBlockToken)splitToken.Token).Attributes; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</div>\n"; return(content); }
/*===============================CurrentDirectory=============================== **Action: Provides a getter and setter for the current directory. The original ** current DirectoryInfo is the one from which the process was started. **Returns: The current DirectoryInfo (from the getter). Void from the setter. **Arguments: The current DirectoryInfo to which to switch to the setter. **Exceptions: ** ==============================================================================*/ public static String GetCurrentDirectory() { // Start with a buffer the size of MAX_PATH StringBuffer buffer = new StringBuffer(260); try { uint result = 0; while ((result = Win32Native.GetCurrentDirectoryW((uint)buffer.Capacity, buffer.UnderlyingArray)) > buffer.Capacity) { // Reported size is greater than the buffer size. Increase the capacity. // The size returned includes the null only if more space is needed (this case). buffer.EnsureCapacity(checked ((int)result)); } if (result == 0) { __Error.WinIOError(); } buffer.Length = (int)result; #if !PLATFORM_UNIX if (buffer.Contains('~')) { return(Path.GetFullPath(buffer.ToString())); } #endif return(buffer.ToString()); } finally { buffer.Free(); } }
public void AppendTests(string source, string value, int startIndex, int count, string expected) { // From string using (var buffer = new StringBuffer(source)) { buffer.Append(value, startIndex, count); Assert.Equal(expected, buffer.ToString()); } // From buffer using (var buffer = new StringBuffer(source)) using (var valueBuffer = new StringBuffer(value)) { if (count == -1) { buffer.Append(valueBuffer, (ulong)startIndex, valueBuffer.Length - (ulong)startIndex); } else { buffer.Append(valueBuffer, (ulong)startIndex, (ulong)count); } Assert.Equal(expected, buffer.ToString()); } }
protected override void DoTest(IProject testProject) { var projectFile = testProject.GetAllProjectFiles().FirstNotNull(); Assert.NotNull(projectFile); var text = projectFile.Location.ReadAllText2(); var buffer = new StringBuffer(text.Text); var languageService = ShaderLabLanguage.Instance.LanguageService().NotNull(); var lexer = languageService.GetPrimaryLexerFactory().CreateLexer(buffer); var psiModule = Solution.PsiModules().GetPrimaryPsiModule(testProject, TargetFrameworkId.Default); var parser = languageService.CreateParser(lexer, psiModule, null); var psiFile = parser.ParseFile().NotNull(); if (DebugUtil.HasErrorElements(psiFile)) { DebugUtil.DumpPsi(Console.Out, psiFile); Assert.Fail("File contains error elements"); } Assert.AreEqual(text.Text, psiFile.GetText(), "Reconstructed text mismatch"); CheckRange(text.Text, psiFile); }
/// <summary> /// Translates a string from ASCII Compatible Encoding (ACE) to Unicode, /// as defined by the ToUnicode operation of <a href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>. /// /// <para>ToUnicode never fails. In case of any error, the input string is returned unmodified. /// /// </para> /// <para> A label is an individual part of a domain name. The original ToUnicode operation, /// as defined in RFC 3490, only operates on a single label. This method can handle /// both label and entire domain name, by assuming that labels in a domain name are /// always separated by dots. The following characters are recognized as dots: /// \u002E (full stop), \u3002 (ideographic full stop), \uFF0E (fullwidth full stop), /// and \uFF61 (halfwidth ideographic full stop). /// /// </para> /// </summary> /// <param name="input"> the string to be processed </param> /// <param name="flag"> process flag; can be 0 or any logical OR of possible flags /// </param> /// <returns> the translated {@code String} </returns> public static String ToUnicode(String input, int flag) { int p = 0, q = 0; StringBuffer @out = new StringBuffer(); if (IsRootLabel(input)) { return("."); } while (p < input.Length()) { q = SearchDots(input, p); @out.Append(ToUnicodeInternal(input.Substring(p, q - p), flag)); if (q != (input.Length())) { // has more labels, or keep the trailing dot as at present @out.Append('.'); } p = q + 1; } return(@out.ToString()); }
private string BuildConditionsByFilter(SqlQuery query, AdminTagFilter filter) { StringBuffer sqlConditions = new StringBuffer(); if (string.IsNullOrEmpty(filter.Name)) { sqlConditions += " AND [Name] Like '%' + @Name + '%'"; query.CreateParameter <string>("@Name", filter.Name, SqlDbType.NVarChar, 50); } if (filter.Type != null) { sqlConditions += " AND ([ID] IN (SELECT [TagID] FROM [bx_TagRelation] WHERE [Type] = @Type))"; query.CreateParameter <TagType?>("@Type", filter.Type, SqlDbType.TinyInt); } if (filter.IsLock != null) { sqlConditions += " AND [IsLock] = @IsLock"; query.CreateParameter <bool?>("@IsLock", filter.IsLock, SqlDbType.Bit); } if (filter.TotalElementsScopeBegin != null && filter.TotalElementsScopeEnd != null) { sqlConditions += " AND ([TotalElements] >= @TotalElementsBegin AND [TotalElements] <= @TotalElementsEnd)"; query.CreateParameter <int?>("@TotalElementsBegin", filter.TotalElementsScopeBegin, SqlDbType.Int); query.CreateParameter <int?>("@TotalElementsEnd", filter.TotalElementsScopeEnd, SqlDbType.Int); } if (sqlConditions.Length > 0) { sqlConditions.Remove(0, 5); } return(sqlConditions.ToString()); }
/// <inheritdoc /> protected override Task <bool> SendInternalAsync(IByteStreamHandler byteStreamHandler, ReadOnlySpan <char> rawMessage) { byteStreamHandler.MustNotBeNull(nameof(byteStreamHandler)); rawMessage.MustBeLongerThan(0, nameof(rawMessage)); // Perform message formatting var sendBuffer = StringBuffer.Acquire(rawMessage.Length); byte[]? bytes = null; try { sendBuffer.Append(rawMessage); sendBuffer.GetInternalData(out var buffer, out var currentCount); var sendMessageByteLength = _encoding.GetByteCount(buffer, 0, currentCount); bytes = ByteArrayPool.Take(sendMessageByteLength); _encoding.GetBytes(buffer, 0, currentCount, bytes, 0); StringBuffer.Release(sendBuffer); sendBuffer = null; return(byteStreamHandler.SendAsync( new ArraySegment <byte>(bytes, 0, sendMessageByteLength))); } finally { if (bytes != null) { ByteArrayPool.Return(bytes); } if (sendBuffer != null) { StringBuffer.Release(sendBuffer); } } }
private void SetupChat() { Log.Debug(TAG, "SetupChat()"); // Initialize the array adapter for the conversation thread conversationArrayAdapter = new ArrayAdapter <string> (this, Resource.Layout.message); conversationView = FindViewById <ListView> (Resource.Id.@in); conversationView.Adapter = conversationArrayAdapter; // Initialize the compose field with a listener for the return key outEditText = FindViewById <EditText> (Resource.Id.edit_text_out); // The action listener for the EditText widget, to listen for the return key outEditText.EditorAction += delegate(object sender, TextView.EditorActionEventArgs e) { // If the action is a key-up event on the return key, send the message if (e.ActionId == ImeAction.ImeNull && e.Event.Action == KeyEventActions.Up) { var message = new Java.Lang.String(((TextView)sender).Text); SendMessage(message); } }; // Initialize the send button with a listener that for click events sendButton = FindViewById <Button> (Resource.Id.button_send); sendButton.Click += delegate(object sender, EventArgs e) { // Send a message using content of the edit text widget var view = FindViewById <TextView> (Resource.Id.edit_text_out); var message = new Java.Lang.String(view.Text); SendMessage(message); }; // Initialize the BluetoothChatService to perform bluetooth connections chatService = new BluetoothChatService(this, new MyHandler(this)); // Initialize the buffer for outgoing messages outStringBuffer = new StringBuffer(""); }
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmNoteBlockSplitToken splitToken, IMarkdownContext context) { StringBuffer content = string.Empty; if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n")) { Logger.LogWarning( "The content part of NOTE/WARNING/CAUTION/IMPORTANT/NEXT syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.MissingNewLineBelowSectionHeader); } var noteToken = (DfmNoteBlockToken)splitToken.Token; content += "<div class=\""; content += noteToken.NoteType.ToUpper(); content += "\""; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; if (Tokens != null && Tokens.TryGetValue(noteToken.NoteType.ToLower(), out string heading)) { content += heading; } else { content += "<h5>"; content += noteToken.NoteType.ToUpper(); content += "</h5>"; } foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</div>\n"; return(content); }