Clear() public method

public Clear ( ) : StringBuilder
return StringBuilder
Beispiel #1
0
        /// <summary>
        /// 画面の設定を保存する
        /// </summary>
        void SaveDisplayInfo()
        {
            ns_IniFile.SettingIni     _ini    = new ns_IniFile.SettingIni();
            System.Text.StringBuilder SetData = new System.Text.StringBuilder();

            //動画
            SetData.Clear();
            SetData.Append(SaveDisplayInfo_Movie(0, txt_movie_1.Text));
            SetData.Append(",");
            SetData.Append(SaveDisplayInfo_Movie(1, txt_movie_2.Text));
            SetData.Append(",");
            SetData.Append(SaveDisplayInfo_Movie(2, txt_movie_3.Text));
            SetData.Append(",");
            SetData.Append(SaveDisplayInfo_Movie(3, txt_movie_4.Text));
            _ini.Func_SetIni(ns_IniFile.SettingIni.IniFileID.DISPLAY, SetData.ToString());

            //画面の結合
            SetData.Clear();
            SetData.Append(checkBox_display_1.IsChecked.ToString());
            SetData.Append(",");
            SetData.Append(checkBox_display_2.IsChecked.ToString());
            SetData.Append(",");
            SetData.Append(checkBox_display_3.IsChecked.ToString());
            SetData.Append(",");
            SetData.Append(checkBox_display_4.IsChecked.ToString());
            SetData.Append(",");
            SetData.Append(radioButton_Horizon.IsChecked.ToString());
            SetData.Append(",");
            SetData.Append(radioButton_Vertical.IsChecked.ToString());
            _ini.Func_SetIni(ns_IniFile.SettingIni.IniFileID.OPTION, SetData.ToString());
        }
        public void AppendIntTest()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
              StringBuilder stringBuilder = new StringBuilder();

              stringBuilder.AppendNumber(1234567890);
              Assert.AreEqual("1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(-1234567890);
              Assert.AreEqual("-1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.None);
              Assert.AreEqual("1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.PositiveSign);
              Assert.AreEqual("+1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.NumberGroup);
              Assert.AreEqual("1,234,567,890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.PositiveSign | AppendNumberOptions.NumberGroup);
              Assert.AreEqual("+1,234,567,890", stringBuilder.ToString());
        }
Beispiel #3
0
 /// <summary>
 /// Разбить на слова.
 /// </summary>
 /// <param name="src">Исходная строка.</param>
 /// <returns>Разбитая на слова строка.</returns>
 public IEnumerable<string> Split(string src)
 {
     var sb = new StringBuilder();
     for (int i = 0; i < src.Length; i++)
     {
         var ch = src[i];
         if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
         {
             sb.Append(' ');
             yield return sb.ToString();
             sb.Clear();
         }
         else
         {
             sb.Append(ch);
             //if (ch == '.' || ch == ',' || ch == ':' || ch == '/' || ch == '\\' || ch == '#' || ch =='?' || ch == '!' || ch == '*' || ch == '-')
             if (char.IsPunctuation(ch) || ch == '.' || ch == ',' || ch == ':' || ch == '/' || ch == '\\' || ch == '#' || ch == '?' || ch == '!' || ch == '*' || ch == '-')
             {
                 yield return sb.ToString();
                 sb.Clear();
             }
         }
     }
     if (sb.Length > 0)
     {
         yield return sb.ToString();
     }
 }
Beispiel #4
0
        private bool InsertAssistWord()
        {
            bool isInserted = false;

            if (AssistListBox.SelectedIndex != -1)
            {
                string selectedString = "";
                if (AssistListBox.SelectedItem.ToString().IndexOf('[') < 0)
                {
                    selectedString = AssistListBox.SelectedItem.ToString();
                }
                else
                {
                    selectedString = AssistListBox.SelectedItem.ToString().Substring(0, AssistListBox.SelectedItem.ToString().IndexOf('[') - 2);
                }
                //if (AutoAddWhiteSpaceAfterTriggered)
                //{
                //    selectedString += " ";
                //}
                this.InsertText(selectedString);
                isInserted = true;
            }
            //AssistListBox.Visibility = System.Windows.Visibility.Collapsed;
            AssistPopup.IsOpen = false;
            sbLastWords.Clear();
            IsAssistKeyPressed = false;
            return(isInserted);
        }
    public string ReverseWords(string s) {
        var sb = new StringBuilder();
        var wordList = new List<string>();
        foreach (var ch in s)
        {
            if (char.IsWhiteSpace(ch))
            {
                if (sb.Length > 0)
                {
                    wordList.Add(sb.ToString());
                    sb.Clear();
                }
            }
            else
            {
                sb.Append(ch);
            }
        }
        if (sb.Length > 0)
        {
            wordList.Add(sb.ToString());
            sb.Clear();
        }
        
        foreach (var word in ((IEnumerable<string>)wordList).Reverse())
        {
            if (sb.Length > 0)
            {
                sb.Append(' ');
            }
            sb.Append(word);
        }

        return sb.ToString();
    }
Beispiel #6
0
        static void Main(string[] args)
        {
            var text1 = File.ReadAllBytes(@"..\doc\pi.t");
              var text2 = File.ReadAllBytes(@"..\doc\e.t");

              var comparer = new Comparer();
              var k = 5;

              var result = comparer.Compare(text1, text2, k);

              var sb = new StringBuilder();
              sb.AppendLine(string.Format("Max length: {0}\n", result.MaxLength));
              using (var file = System.IO.File.AppendText(@"..\doc\pie.t"))
              {
            file.Write(sb.ToString());
            sb.Clear();
            foreach (var index in result.Indices)
            {
              sb.AppendLine(string.Format("Length: {0}, pi_index: {1}, e_index: {2}",
            index.Value,
            index.Key.Item1,
            index.Key.Item2));
              file.Write(sb.ToString());
              sb.Clear();
            }
              }
        }
        private IEnumerable<string> GetTokens() {
            var token = new StringBuilder();
            var lastCharacter = '\0';
            foreach (var character in _xPath) {
                if (IsQuote(lastCharacter)) {
                    token.Append(character);
                    if (character == lastCharacter) {
                        yield return token.ToString();
                        token.Clear();
                        lastCharacter = '\0';
                    }
                    continue;
                }

                if (IsQuote(character) || IsName(character) != IsName(lastCharacter)) {
                    if (token.Length > 0)
                        yield return TrimToken(token);
                    token.Clear();
                }
                token.Append(character);
                lastCharacter = character;
            }
            if (token.Length > 0)
                yield return TrimToken(token);
        }
        private static IEnumerable<string> SplitAndLower(string source)
        {
            var strings = new List<string>();
            var builder = new StringBuilder();

            foreach (var character in source)
            {
                if (IsSeparator(character))
                {
                    if (builder.Length > 0)
                    {
                        strings.Add(builder.ToString());
                    }

                    builder.Clear();
                    continue;
                }
                else if (char.IsUpper(character) && builder.Length > 0)
                {
                    strings.Add(builder.ToString());
                    builder.Clear();
                }

                builder.Append(char.ToLowerInvariant(character));
            }

            if (builder.Length > 0)
            {
                strings.Add(builder.ToString());
            }

            return strings;
        }
Beispiel #9
0
        public void TestEagerlyLoadingMultipleLevels()
        {
            using (var context = new TestDB2015Entities())
            {
                var databaseLog = new StringBuilder();
                context.Database.Log = commandLine =>
                {
                    databaseLog.AppendLine(commandLine);
                    Trace.Write(commandLine);
                };

                Trace.WriteLine("a normal query");
                var product1IncludeTags = context.Users
                                                 .Include(x => x.Products)
                                                 .Include(x => x.Products.Select(y => y.Tags))
                                                 .FirstOrDefault();
                Assert.IsNotNull(product1IncludeTags);

                Trace.WriteLine("1st query using Include method.");
                databaseLog.Clear();
                var debugInfo1 = new EFCacheDebugInfo();
                var firstPoductIncludeTags = context.Users
                                                    .Include(x => x.Products)
                                                    .Include(x => x.Products.Select(y => y.Tags))
                                                    .Cacheable(debugInfo1)
                                                    .FirstOrDefault();
                Assert.IsNotNull(firstPoductIncludeTags);
                Assert.AreEqual(false, debugInfo1.IsCacheHit);
                var hash1 = debugInfo1.EFCacheKey.KeyHash;
                var cacheDependencies1 = debugInfo1.EFCacheKey.CacheDependencies;

                Trace.WriteLine("same cached query using Include method.");
                databaseLog.Clear();
                var debugInfo11 = new EFCacheDebugInfo();
                var firstPoductIncludeTags11 = context.Users
                                                    .Include(x => x.Products)
                                                    .Include(x => x.Products.Select(y => y.Tags))
                                                    .Cacheable(debugInfo11)
                                                    .FirstOrDefault();
                Assert.IsNotNull(firstPoductIncludeTags11);
                Assert.AreEqual(true, debugInfo11.IsCacheHit);

                Trace.WriteLine(
                    @"2nd query looks the same, but it doesn't have the Include method, so it shouldn't produce the same queryKeyHash.
                 This was the problem with just parsing the LINQ expression, without considering the produced SQL.");
                databaseLog.Clear();
                var debugInfo2 = new EFCacheDebugInfo();
                var firstPoduct = context.Users.Cacheable(debugInfo2)
                                               .FirstOrDefault();
                Assert.IsNotNull(firstPoduct);
                Assert.AreEqual(false, debugInfo2.IsCacheHit);
                var hash2 = debugInfo2.EFCacheKey.KeyHash;
                var cacheDependencies2 = debugInfo2.EFCacheKey.CacheDependencies;

                Assert.AreNotEqual(hash1, hash2);
                Assert.AreNotEqual(cacheDependencies1, cacheDependencies2);
            }
        }
Beispiel #10
0
        private static string translate(string input)
        {
            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            System.Text.StringBuilder inputWord   = new System.Text.StringBuilder();                //Stringbuilder for holding current character of morse code
            List <string>             listOfInput = new List <string>();                            //collection of morse code entered by user
            bool boolcheck = false;                                                                 // used to count '|'
            int  pipeCount = 0;                                                                     // counter which count '|' for spacing

            for (int i = 0; i < input.Length; i++)                                                  // for iterating input
            {
                if (input[i] == '|')                                                                //checking first pipe
                {
                    pipeCount++;
                    if (boolcheck == false)
                    {
                        listOfInput.Add(inputWord.ToString());                                      //creats a collection of separeated morse code
                        inputWord.Clear();                                                          //flush out previous values after each break
                        boolcheck = true;
                        pipeCount = 0;                                                              // to start scanning input again after break
                    }
                    if (pipeCount >= 3)                                                             // to allocate space between two words
                    {
                        listOfInput.Add(inputWord.ToString());
                        inputWord.Append(" ");                                                      // adding space
                        inputWord.Clear();
                        listOfInput.Add(inputWord.ToString());
                        boolcheck = true;
                        pipeCount = 0;                                                              // to start scanning input again after break
                    }
                }
                else
                {
                    inputWord.Append(input[i]);
                    if (i + 1 == input.Length)                                                        //condition to check whether its last morse character or not?
                    {
                        listOfInput.Add(inputWord.ToString());
                        inputWord.Clear();
                    }
                    boolcheck = false;
                }
            }
            foreach (string item in listOfInput)                                                    //iteration to get single morse word separated by break
            {
                if (translator.ContainsKey(item))                                                   //verify with dictionary
                {
                    finalOutput.Append(translator[item] + "");                                      //Stringbuilder for holding decrypted character of morse code
                }
                else
                {
                    finalOutput.Append(" ");
                }
            }
            return(answer.ToString());
        }
        internal static IEnumerable<string> Split(string expression)
        {
            List<string> result = new List<string>();

            StringBuilder resultItemBuilder = new StringBuilder();
            List<char> charArray = expression.ToList();
            for (int i = 0; i < charArray.Count; i++)
            {
                string oneCharString = charArray[i].ToString(CultureInfo.InvariantCulture);
                string twoCharString = oneCharString;
                // 读取两个字符,判断是不是特殊双字符的操作符.etc: >=, <=, &&, ||
                if (i < charArray.Count - 1)
                {
                    twoCharString += charArray[i + 1].ToString(CultureInfo.InvariantCulture);
                }

                if (OperatorMethod.IsOperator(twoCharString) &&
                    twoCharString.Length == 2)
                {
                    if (resultItemBuilder.Length > 0)
                    {
                        result.Add(resultItemBuilder.ToString());
                        resultItemBuilder.Clear();
                    }

                    result.Add(twoCharString);
                    i++;
                }
                else if (OperatorMethod.IsOperator(oneCharString))
                {
                    if (resultItemBuilder.Length > 0)
                    {
                        result.Add(resultItemBuilder.ToString());
                        resultItemBuilder.Clear();
                    }

                    result.Add(oneCharString);
                }
                else
                {
                    resultItemBuilder.Append(oneCharString);
                }
            }

            if (resultItemBuilder.Length > 0)
            {
                result.Add(resultItemBuilder.ToString());
                resultItemBuilder.Clear();
            }

            return result;
        }
Beispiel #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    HtmlGenericControl DivProgramacion = (HtmlGenericControl)this.Master.FindControl("liprogramacion");
                    DivProgramacion.Attributes.Add("class", "dropdown active");

                    HtmlGenericControl DivInicio = (HtmlGenericControl)this.Master.FindControl("liinicio");
                    DivInicio.Attributes.Add("class", "");

                    this.CargaCombo();
                    this.CargaListado();
                }
                catch (Exception ex)
                {
                    lblmsg.Text = "Error interno en el sistema contacte a su administrador " + " Detalle:" + ex.Message;
                    msgError.Clear();
                    msgError.AppendLine("Fecha:" + DateTime.Now.ToString());
                    msgError.AppendLine("Descripción:" + ex.Message);
                    msgError.AppendLine("Detalle:" + ex.StackTrace);
                    log.Error(msgError.ToString());
                }
            }
        }
Beispiel #13
0
        public SelectModel GetContractOutStockSelect(int pageIndex, int pageSize, string orderStr, string stockName, DateTime beginDate, DateTime endDate, string stockIds = "")
        {
            NFMT.Common.SelectModel select = new NFMT.Common.SelectModel();

            select.PageIndex = pageIndex;
            select.PageSize = pageSize;
            if (string.IsNullOrEmpty(orderStr))
                select.OrderStr = "sto.StockId desc";
            else
                select.OrderStr = orderStr;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("sto.StockId,sn.RefNo,sto.AssetId,ass.AssetName,sto.BrandId,bra.BrandName,sto.Format,sto.OriginPlace,sto.CurNetAmount,sto.DeliverPlaceId");
            sb.Append(",dp.DPName,sto.StockDate,sto.UintId,mu.MUName,sto.CustomsType,ct.DetailName as CustomsTypeName,sto.CardNo,sto.StockStatus,ss.StatusName");
            sb.Append(",se.ExclusiveAmount, ISNULL(sto.CurNetAmount,0) - ISNULL(se.ExclusiveAmount,0) as NetAmount, ISNULL(sto.CurNetAmount,0) - ISNULL(se.ExclusiveAmount,0) as OutAmount,sto.Bundles,sto.Bundles as OutBundles");
            select.ColumnName = sb.ToString();

            int readyStatus = (int)Common.StatusEnum.已生效;

            sb.Clear();
            sb.Append(" dbo.St_Stock sto ");
            sb.Append("  inner join dbo.St_StockName sn on sto.StockNameId = sn.StockNameId ");

            sb.Append(" left join NFMT_Basic.dbo.Asset ass on sto.AssetId = ass.AssetId ");
            sb.Append(" left join NFMT_Basic.dbo.Brand bra on sto.BrandId = bra.BrandId ");
            sb.Append(" left join NFMT_Basic.dbo.DeliverPlace dp on sto.DeliverPlaceId = dp.DPId ");
            sb.Append(" left join NFMT_Basic.dbo.MeasureUnit mu on sto.UintId= mu.MUId ");
            sb.Append(" left join NFMT_Basic.dbo.BDStyleDetail ct on ct.StyleDetailId = sto.CustomsType ");
            sb.Append("  left join NFMT_Basic.dbo.BDStatusDetail ss on ss.DetailId = sto.StockStatus ");

            sb.AppendFormat("  left join (select Sum(ExclusiveAmount) as ExclusiveAmount,StockId from dbo.St_StockExclusive where ExclusiveStatus = {0} group by StockId ) as se on se.StockId = sto.StockId ", readyStatus);
            select.TableName = sb.ToString();

            sb.Clear();
            sb.AppendFormat(" sto.StockStatus in ({0},{1},{2}) ", (int)StockStatusEnum.预入库存, (int)StockStatusEnum.在库正常, (int)StockStatusEnum.新拆库存);
            sb.Append(" and ISNULL(sto.CurNetAmount,0) - ISNULL(se.ExclusiveAmount,0) >0 ");

            if (!string.IsNullOrEmpty(stockName))
                sb.AppendFormat(" and sn.RefNo like '%{0}%' ", stockName);
            if (beginDate > Common.DefaultValue.DefaultTime && endDate > beginDate)
                sb.AppendFormat(" and sto.StockDate between '{0}' and '{1}' ", beginDate.ToString(), endDate.AddDays(1).ToString());

            if (!string.IsNullOrEmpty(stockIds))
                sb.AppendFormat(" and sto.StockId in ({0})", stockIds);

            select.WhereStr = sb.ToString();

            return select;
        }
        public List<OperationElement> GetOperationElements(string expression)
        {
            if (string.IsNullOrEmpty(expression))
                throw new EmptyStringException();
            var operationElements = new List<OperationElement>();
            var builder = new StringBuilder();

            foreach (char character in expression)
            {
                if (char.IsDigit(character))
                {
                    builder.Append(character);
                }
                else if (IsOperator(character))
                {
                    if (builder.Length != 0)
                    {
                        operationElements.Add(new OperationElement(OperationElementType.Number, builder.ToString()));
                        builder.Clear();
                    }
                    operationElements.Add(new OperationElement(OperationElementType.Operator, character.ToString()));
                }
                else
                {
                    throw new IncorrectOperationStringException(expression);
                }
            }

            if (builder.Length != 0)
                operationElements.Add(new OperationElement(OperationElementType.Number, builder.ToString()));
            return operationElements;
        }
Beispiel #15
0
        public IEnumerable<string> tokenize(Stream stream)
        {
            StreamReader reader = new StreamReader(stream);
            StringBuilder token = new StringBuilder();
            while (!reader.EndOfStream)
            {
                char character = (char)reader.Read();
                if (ignoreList.Contains(character))
                {
                    if (token.Length > 0)
                    {
                        string result = token.ToString().ToLower();
                        token.Clear();
                        yield return result;
                    }
                }
                else
                {
                    token.Append(character);
                }
            }

            if (token.Length > 0)
            {
                yield return token.ToString().ToLower();
            }
        }
Beispiel #16
0
        /// <summary>
        /// Iterator that builds tokens from the inputted document, and returns them as they are built.
        /// </summary>
        /// <param name="document">The document to tokenize</param>
        /// <returns>Returns lowercase tokens, one at a time as soon as they are read</returns>
        public IEnumerable<string> Tokenize(string document)
        {
            StringBuilder token = new StringBuilder();
            foreach(char character in document)
            {
                if (ignoreList.Contains(character))
                {
                    if (token.Length > 0)
                    {
                        string result = token.ToString().ToLower();
                        token.Clear();
                        if (this.isValidTerm(result))    // dont return stop words
                        {
                            yield return result;
                        }

                    }
                }
                else
                {
                    token.Append(character);
                }
            }

            if (token.Length > 0)
            {
                yield return token.ToString().ToLower();
            }
        }
Beispiel #17
0
    void Invoke(RenderTexture texture)
    {
        isProcessing = true;

        compute.SetTexture(0, "InputTexture", texture);
        compute.SetBuffer(0, "OutputTensor", inputBuffer);
        compute.Dispatch(0, 28 / 4, 28 / 4, 1);
        inputBuffer.GetData(inputs);

        float startTime = Time.realtimeSinceStartup;

        interpreter.SetInputTensorData(0, inputs);
        interpreter.Invoke();
        interpreter.GetOutputTensorData(0, outputs);
        float duration = Time.realtimeSinceStartup - startTime;

        sb.Clear();
        sb.AppendLine($"Process time: {duration: 0.00000} sec");
        sb.AppendLine("---");
        for (int i = 0; i < outputs.Length; i++)
        {
            sb.AppendLine($"{i}: {outputs[i]: 0.00}");
        }
        outputTextView.text = sb.ToString();

        isProcessing = false;
    }
        /// <summary>
        /// 设置地址
        /// 2013/08/22
        /// </summary>
        /// <param name="list"></param>
        private void SetAscmReadingHead(List <Dal.SupplierPreparation.Entities.AscmContainer> list)
        {
            System.Text.StringBuilder sbSn = new System.Text.StringBuilder();
            sbSn.Clear();
            var t = list.Select(e => e.place).Distinct();

            foreach (string ascmTagLog in t)
            {
                if (!string.IsNullOrEmpty(ascmTagLog))
                {
                    if (sbSn.Length != 0)
                    {
                        sbSn.Append(",");
                    }
                    sbSn.AppendFormat("{0}", ascmTagLog);
                }
            }
            if (string.IsNullOrEmpty(sbSn.ToString()))
            {
                return;
            }
            IList <MideaAscm.Dal.Base.Entities.AscmReadingHead> ilist = YnDaoHelper.GetInstance().nHibernateHelper.Find <MideaAscm.Dal.Base.Entities.AscmReadingHead>("from AscmReadingHead where id in (" + sbSn.ToString() + ")");
            List <MideaAscm.Dal.Base.Entities.AscmReadingHead>  listAscmReadingHead = YnBaseClass2.Helper.ConvertHelper.ConvertIListToList(ilist);

            if (ilist.Count > 0)
            {
                foreach (Dal.SupplierPreparation.Entities.AscmContainer ascmTagLog in list)
                {
                    ascmTagLog.ascmReadingHead = listAscmReadingHead.Find(e => e.id.ToString() == ascmTagLog.place);
                }
            }
        }
Beispiel #19
0
    IEnumerator DoTextProcess()
    {
        if (textProcessActiveGO)
        {
            textProcessActiveGO.SetActive(true);
        }
        if (textProcessFinishGO)
        {
            textProcessFinishGO.SetActive(false);
        }

        mTextProcessSB.Clear();

        var waitDelay = new WaitForSeconds(textCharPerSecond);

        for (int i = 0; i < mTextDialog.Length; i++)
        {
            mTextProcessSB.Append(mTextDialog[i]);

            textLabel.text = mTextProcessSB.ToString();

            yield return(waitDelay);
        }

        mTextProcessRout = null;

        if (textProcessActiveGO)
        {
            textProcessActiveGO.SetActive(false);
        }
        if (textProcessFinishGO)
        {
            textProcessFinishGO.SetActive(true);
        }
    }
Beispiel #20
0
        /// <summary>
        /// like traceEvent except it uses a stopwatch 'timer' to write formatted time after the message [{1:0}ms].
        /// Usually used to signal in the log how long an operation took.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="elapsed"></param>
        /// <param name="eventType"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        static void traceEvent(this TraceSource trace, TimeSpan elapsed, LogEventType eventType, string message, params object[] args)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            var timespan = ShortTimeSpan.FromSeconds(elapsed.TotalSeconds);

            if (sb == null)
            {
                sb = new System.Text.StringBuilder();
            }
            sb.Clear();
            if (args.Length == 0)
            {
                sb.Append(message);
            }
            else
            {
                sb.AppendFormat(message, args);
            }
            sb.Append(" [");
            timespan.ToString(sb);
            sb.Append("]");
            trace.TraceEvent(eventType, 0, sb.ToString());
        }
Beispiel #21
0
        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            var DeviceToken = deviceToken.Description;

            if (!string.IsNullOrWhiteSpace(DeviceToken))
            {
                var temp = DeviceToken.Trim('<').Trim('>').Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                var builder = new System.Text.StringBuilder();

                for (int index = 0; index < temp.Length; index++)
                {
                    builder.Append(temp[index]);
                }


                DeviceToken = builder.ToString();
                builder.Clear();
            }

            var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");

            if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
            {
                // 上傳我們自己的 Server
            }

            Debug.WriteLine("DeviceToken:" + DeviceToken);

            NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
            NSUserDefaults.StandardUserDefaults.Synchronize();
        }
        public List<LogEntry> ParseFile(Stream file, string filename, List<LogEntry> existingEntries)
        {
            // TODO: error checking
            System.IO.StreamReader sr = new StreamReader(file);
            StringBuilder sb = new StringBuilder();

            List<LogEntry> entries = existingEntries??new List<LogEntry>();

            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                if (LogEntry.LogTimeStamp.IsMatch(line))
                {
                    if (sb.Length > 0)
                    {
                        // found a full log entry in sb, parse it and clear it out
                        LogEntry entry = null;
                        if (LogEntry.TryParse(sb.ToString(), filename, out entry))
                        {
                            // got one!
                            entries.Add(entry);
                        }
                        else
                        {
                            // what do I do with this error?
                        }
                        sb.Clear();
                    }
                }
                sb.AppendLine(line);

            }
            return entries;
        }
Beispiel #23
0
        static int ReturnLongestString(string abc, out string output)
        {
            string result = string.Empty;

            System.Text.StringBuilder builder = new System.Text.StringBuilder();


            foreach (var item in abc)
            {
                int val = (int)item;
                if (val >= 48 && val <= 57)
                {
                    if (result.Length < builder.Length)
                    {
                        result = builder.ToString();
                    }
                    if (builder.Length != 0)
                    {
                        builder.Clear();
                    }
                }
                else
                {
                    builder.Append(item);
                }
            }

            if (result == string.Empty)
            {
                result = builder.ToString();
            }
            output = result;
            return(result.Length);
        }
Beispiel #24
0
        public void Complex()
        {
            int cnt = 42;
            var sb  = new System.Text.StringBuilder();

            sb.Append("This invocation doesn't have syntax tree for Append");
            DoNothing(sb);
            for (int i = 0; i < cnt; i++)
            {
                DoNothing(sb);
                if (i % 2 == 0)
                {
                    sb.Append(i.ToString());
                    sb.Clear();
                    try
                    {
                        sb.Append("42");
                        DoTheWork(sb.ToString(), 42);
                    }
                    finally
                    {
                        DoNothing(null);
                    }
                }
                DoNothing(sb);
            }
        }
 public IList<string> FullJustify(string[] words, int maxWidth) {
     var result = new List<string>();
     var buffer = new List<string>();
     var sb = new StringBuilder();
     var len = 0;
     
     for (var i = 0; i < words.Length; ++i)
     {
         var newLen = words[i].Length + (len == 0 ? 0 : len + 1);
         if (newLen <= maxWidth)
         {
             buffer.Add(words[i]);
             len = newLen;
         }
         else
         {
             if (buffer.Count == 1)
             {
                 sb.Append(buffer[0]);
                 sb.Append(' ', maxWidth - buffer[0].Length);
             }
             else
             {
                 var spaceCount = maxWidth - len + buffer.Count - 1;
                 for (var j = 0; j < buffer.Count - 1; ++j)
                 {
                     sb.Append(buffer[j]);
                     var spaceToAdd = (spaceCount - 1) / (buffer.Count - j - 1) + 1;
                     sb.Append(' ', spaceToAdd);
                     spaceCount -= spaceToAdd;
                 }
                 sb.Append(buffer.Last());
             }
             result.Add(sb.ToString());
             buffer.Clear();
             buffer.Add(words[i]);
             sb.Clear();
             len = words[i].Length;
         }
     }
     
     if (buffer.Count > 0)
     {
         for (var j = 0; j < buffer.Count; ++j)
         {
             if (sb.Length > 0)
             {
                 sb.Append(' ');
             }
             sb.Append(buffer[j]);
         }
         if (sb.Length < maxWidth)
         {
             sb.Append(' ', maxWidth - sb.Length);
         }
         result.Add(sb.ToString());
     }
     
     return result;
 }
        static public string CombinePath(params string[] paths)
        {
            if (paths == null || paths.Length == 0)
            {
                return(null);
            }
            cCombineBuilder.Clear();
            for (int i = 0, length = paths.Length; i < length; i++)
            {
                bool   thavenext = i + 1 < length;
                string item      = paths[i];
                string next      = thavenext ? paths[i + 1] : "";
                bool   thv       = item.EndsWith("/");
                bool   tnexthv   = !thavenext || next.StartsWith("/");

                cCombineBuilder.Append(item);

                if (!thv && !tnexthv)
                {
                    cCombineBuilder.Append("/");
                }
            }

            return(cCombineBuilder.ToString());
        }
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Clear();
            sb.Append('[');

            sb.Append(this.Name);
            bool flag = true;
            foreach (var phone in this.Phones)
            {
                if (flag)
                {
                    sb.Append(": ");
                    flag = false;
                }
                else
                {
                    sb.Append(", ");
                }

                sb.Append(phone);
            }

            sb.Append(']');
            return sb.ToString();
        }
Beispiel #28
0
    private IEnumerator LevelUp(CharacterData characterData)
    {
        List <string> ms     = new List <string>();
        Status        growth = characterData.playerData.GrowthRate;

        characterData.lv++;
        characterData.status.maxHp    += growth.maxHp;
        characterData.status.maxMp    += growth.maxMp;
        characterData.status.attack   += growth.attack;
        characterData.status.deffence += growth.deffence;
        characterData.status.speed    += growth.speed;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append($"{characterData.GetName()}は レベル{characterData.lv}に あがった!");
        sb.Append($"\nさいだいHPが {growth.maxHp}ポイント あがった!");
        sb.Append($"\nさいだいMPが {growth.maxMp}ポイント あがった!");
        ms.Add(sb.ToString());

        sb.Clear();
        sb.Append($"こうげき+{growth.attack}  ぼうぎょ+{growth.deffence}\n");
        sb.Append($"すばやさ+{growth.speed}");
        ms.Add(sb.ToString());

        yield return(BattleMessage.GetWindow().ShowClick(ms));

        //呪文を覚える
        yield return(LearnSpell(characterData));

        //特技を覚える
        yield return(LearnSkill(characterData));

        yield break;
    }
Beispiel #29
0
    private static string[] GetBrowserNames()
    {
        List <string> browserNames = new List <string>();

        try
        {
            string fileContent = System.IO.File.ReadAllText("config.txt");
            fileContent = fileContent.Replace(",", "");
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            for (int i = 0; i < fileContent.Length; i++)
            {
                if (fileContent[i] == ' ')
                {
                    browserNames.Add(builder.ToString());
                    builder.Clear();
                }
                else
                {
                    builder.Append(fileContent[i]);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        return(browserNames.ToArray());
    }
Beispiel #30
0
        private void btnDraw_Click(object sender, RoutedEventArgs e)
        {
            int[][] tempTable;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            try {
                Console.WriteLine("kutsutaan drawia loton arvolla: " + selectedLotto);
                tempTable = lottoOlio.draw(Int32.Parse(drawsBox.Text), selectedLotto);
            }
            catch (Exception) {
                MessageBox.Show("Draws luukussa oltava numero.");
                throw;
            }

            Console.WriteLine("tempTable pituus on: " + tempTable.Length);

            for (int j = 0; j < tempTable.Length; j++)
            {
                sb.Clear();
                Console.WriteLine("Kierros: " + j);
                Console.WriteLine("tempTable indeksi " + j + " pituus on: " + tempTable[j].Length);
                for (int i = 0; i < tempTable[j].Length; i++)
                {
                    Console.WriteLine(" -Kierros: " + i);
                    sb.Append(Convert.ToString(tempTable[j][i])).Append(", ");
                }
                drawsArea.Items.Add(sb.ToString());
            }
        }
        protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse)
        {
            using (var content = httpResponse.Content.ReadAsStream())
            {
                if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage))
                    PopulateDocumentHeaderFromResponseStream(response, content);
                else
                {
                    PopulateMissingIdFromRequestUri(response, httpResponse);
                    PopulateMissingRevFromRequestHeaders(response, httpResponse);
                }

                content.Position = 0;

                var sb = new StringBuilder();
                using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding))
                {
                    while (!reader.EndOfStream)
                    {
                        sb.Append(reader.ReadLine());
                    }
                }
                response.Content = sb.ToString();
                sb.Clear();
            }
        }
Beispiel #32
0
        public void GetCommandString(UIntPtr idCmd, uint uFlags, IntPtr pReserved, System.Text.StringBuilder pszName, uint cchMax)
        {
            pszName.Clear();
            #region not_using_verb
            //if ((GCS)uFlags == GCS.GCS_HELPTEXTW) {
            //    if (idCmd.ToUInt32() < Devices.Count)
            //    {

            //        if (Properties.Resources.menu_comment_InstallToPhone.Length > cchMax - 1)
            //        {
            //            Marshal.ThrowExceptionForHR(WinError.STRSAFE_E_INSUFFICIENT_BUFFER);
            //        }
            //        else
            //        {
            //            pszName.Clear();
            //            pszName.Append(Properties.Resources.menu_comment_InstallToPhone);
            //        }

            //    }
            //    else if (idCmd.ToUInt32() == Devices.Count + 1)
            //    {
            //        if (Properties.Resources.menu_comment_ConnectViaWIFI.Length > cchMax -1){
            //            Marshal.ThrowExceptionForHR(WinError.STRSAFE_E_INSUFFICIENT_BUFFER);
            //        }
            //        else
            //        {
            //            pszName.Clear();
            //            pszName.Append(Properties.Resources.menu_comment_ConnectViaWIFI);
            //        }
            //    }
            //}
            #endregion
        }
Beispiel #33
0
        /// <summary>
        /// Execute any update statements required to clear data, followed by delete statements for all tables.
        /// </summary>
        /// <param name="updateCommands">Update commands to execute</param>
        /// <param name="tables">Tables to delete from</param>
        /// <param name="timeout">Maximum time for a statement</param>
        /// <param name="deleteBatch">Batch delete statements into groups, saves times on databases with large numbers of tables.</param>
        public void Zap(IEnumerable<string> updateCommands, IEnumerable<string> tables, int timeout = 30, int deleteBatch = 1)
        {
            foreach (var item in updateCommands)
            {
                dao.ExecuteNonQuery(item, timeout);
            }

            var sb = new StringBuilder();
            var count = 0;
            foreach (var item in tables)
            {
                sb.AppendLine(string.Format("DELETE FROM {0};", item));
                count++;
                if (count % deleteBatch != 0)
                {
                    continue;
                }

                dao.ExecuteNonQuery(sb.ToString(), timeout);
                sb.Clear();
            }

            var lastCmd = sb.ToString();
            if (!string.IsNullOrEmpty(lastCmd))
            {
                dao.ExecuteNonQuery(lastCmd, timeout);
            }
        }
        public override bool Execute()
        {
            HashSet<string> directoriesToRestore = new HashSet<string>();

            foreach (string rootDirectory in RootDirectories)
            {
                AddDirectoriesToRestore(rootDirectory, rootDirectory, directoriesToRestore);
            }

            List<string> resultBuilder = new List<string>();
            StringBuilder sb = new StringBuilder(directoryListLength);

            foreach (string directoryPath in directoriesToRestore)
            {
                sb.Append('"');
                sb.Append(directoryPath);
                sb.Append("\" ");

                if (sb.Length >= directoryListLength)
                {
                    resultBuilder.Add(sb.ToString());
                    sb.Clear();
                }
            }

            if (sb.Length > 0)
            {
                resultBuilder.Add(sb.ToString());
            }

            DirectoriesToRestore = resultBuilder.ToArray();

            return true;
        }
Beispiel #35
0
        public static EditProblemViewModel GetEditProblemViewModel(Problem problem)
        {
            var epvm = new EditProblemViewModel();
            epvm.Author = problem.Author.UserName;
            epvm.Name = problem.Name;
            epvm.Text = problem.Text;
            epvm.SelectedCategoryId = problem.CategoryId;
            epvm.IsBlocked = problem.IsBlocked;

            var sb = new StringBuilder();
            foreach (var tag in problem.Tags)
            {
                sb.Append(tag.Name);
                sb.Append(',');
            }

            epvm.TagsString = sb.ToString();

            sb.Clear();

            foreach (var ans in problem.CorrectAnswers)
            {
                sb.Append(ans.Text);
                sb.Append(';');
            }

            sb.Remove(sb.Length - 1, 1);
            epvm.Answers = sb.ToString();

            return epvm;
        }
Beispiel #36
0
    private void getCustomerList()
    {
        System.Text.StringBuilder sb  = new System.Text.StringBuilder();
        HYTD.BLL.Call_CustomerBLL bll = new HYTD.BLL.Call_CustomerBLL();
        string strKeyWord             = string.Empty;

        if (!string.IsNullOrEmpty(Request["keyword"]))
        {
            strKeyWord = Request["keyword"].ToString().Trim();
        }
        System.Collections.Generic.List <Models.Call_Customer> list = bll.GetCall_CustomerList(strKeyWord);
        foreach (var m in list)
        {
            sb.Append("{ \"name\":\"" + m.CC_Name + "\", \"to\": \"" + m.CC_ID + "\" },");
        }
        strCumstomers = "[" + sb.ToString().Trim(',') + "]";
        sb.Clear();
        UserInfoBLL            uBll     = new UserInfoBLL();
        List <Models.UserInfo> userList = new List <UserInfo>();

        userList = uBll.GetUserInfoList();
        foreach (var m in userList)
        {
            sb.Append("{ \"name\":\"" + m.UserName + "\", \"to\": \"" + m.UserCode + "\" },");
        }
        strUsers = "[" + sb.ToString().Trim(',') + "]";
    }
Beispiel #37
0
        private void OnSerialize()
        {
            if (mJsonText == null)
            {
                mJsonText = new System.Text.StringBuilder();
            }
            mJsonText.Clear();
            JsonSerializer serializer = new JsonSerializer();

            System.IO.StringWriter writer         = new System.IO.StringWriter(mJsonText);
            JsonTextWriter         jsonTextWriter = new JsonTextWriter(writer);

            serializer.Serialize(jsonTextWriter, Data);
            var charbuffer = System.Buffers.ArrayPool <Char> .Shared.Rent(mJsonText.Length);

            mJsonText.CopyTo(0, charbuffer, 0, mJsonText.Length);
            try
            {
                var bytes = System.Buffers.ArrayPool <byte> .Shared.Rent(mJsonText.Length * 6);

                var len = System.Text.Encoding.UTF8.GetBytes(charbuffer, 0, mJsonText.Length, bytes, 0);
                mJsonData = new ArraySegment <byte>(bytes, 0, len);
            }
            finally
            {
                System.Buffers.ArrayPool <char> .Shared.Return(charbuffer);
            }
        }
    public void RepaintWindowText()
    {
        const int SONGNAME_MAX_CHAR = 35;
        string    songName          = currentSong.name;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(currentSong.name);
        if (sb.Length <= 0)
        {
            sb.Append("Untitled");
        }

        if (sb.Length > SONGNAME_MAX_CHAR)
        {
            const string Ellipsis      = "...";
            int          charsToRemove = sb.Length - SONGNAME_MAX_CHAR + Ellipsis.Length;
            sb.Remove(sb.Length - charsToRemove, charsToRemove);
            sb.Append(Ellipsis);
        }

        windowHandleManager.SetProjectNameStr(sb.ToString());

        sb.Clear();
        sb.Append(currentChart.name);
        windowHandleManager.SetProjectStateStr(sb.ToString());
    }
Beispiel #39
0
        public string CountAndSay(int n)
        {
            var result = "1";
            char currentCh;
            int i, j, startNum;
            var builder = new StringBuilder();

            for (i = 1; i < n; i++)
            {
                currentCh = result[0];
                startNum = 0;
                for (j = 1; j < result.Length; j++)
                {
                    if (currentCh != result[j])
                    {
                        builder.Append(j - startNum);
                        builder.Append(currentCh);
                        currentCh = result[j];
                        startNum = j;
                    }
                }
                builder.Append(j - startNum);
                builder.Append(currentCh);

                result = builder.ToString();
                builder.Clear();
            }

            return result;
        }
Beispiel #40
0
        private void btnDraw_Click(object sender, RoutedEventArgs e) {

            int[][] tempTable;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            try {
                Console.WriteLine("kutsutaan drawia loton arvolla: " + selectedLotto);
                tempTable = lottoOlio.draw(Int32.Parse(drawsBox.Text), selectedLotto);
            }
            catch (Exception) {
                MessageBox.Show("Draws luukussa oltava numero.");
                throw;
            }

            Console.WriteLine("tempTable pituus on: " + tempTable.Length);

            for (int j = 0; j < tempTable.Length; j++) {
                sb.Clear();
                Console.WriteLine("Kierros: " + j);
                Console.WriteLine("tempTable indeksi " + j + " pituus on: " + tempTable[j].Length);
                for (int i = 0; i < tempTable[j].Length; i++) {
                    Console.WriteLine(" -Kierros: " + i);
                    sb.Append(Convert.ToString(tempTable[j][i])).Append(", ");
                }
                drawsArea.Items.Add(sb.ToString()); 
            }
        }
Beispiel #41
0
        public CipherDecoder(string secretCode, string cipher)
        {
            cipherItems = new List<CipherItem>();

            StringBuilder currentCipher = new StringBuilder();
            char lastChar = '\0';
            foreach (char ch in cipher)
            {
                if (ch >= 'A' && ch <= 'Z')
                {
                    if (currentCipher.Length > 0)
                    {
                        cipherItems.Add(new CipherItem(lastChar, currentCipher.ToString()));
                        currentCipher.Clear();
                    }
                    lastChar = ch;
                }
                else
                {
                    currentCipher.Append(ch);
                }
            }
            if (currentCipher.Length > 0)
            {
                cipherItems.Add(new CipherItem(lastChar, currentCipher.ToString()));
            }

            this.secretCode = secretCode;
        }
Beispiel #42
0
        public MainForm()
        {
            InitializeComponent();

            // PJL code
            this.MainOutputTextBox.Text += "This is a test.";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine("This is line number 1.");
            sb.AppendLine("This is line number 2.");
            this.MainOutputTextBox.Text += sb.ToString();
            int val = 123;

            sb.Clear();
            sb.AppendFormat("{0:X4} == {0}", val, val);
            sb.AppendLine();
            this.MainOutputTextBox.Text += sb.ToString();

            for (int x = 0; x < 32; x++)
            {
                this.MainOutputTextBox.Text += string.Format("{0,2}", x);
                this.MainOutputTextBox.Text += System.Environment.NewLine;
            }

            System.Diagnostics.Debug.WriteLine("This is a debug test.");
        }
Beispiel #43
0
    private void getCustomerList()
    {
        strCallWorkBillStatusDrop = PublicMethod.getWorkBillStatusCallCategory(2, false, false, 27);// PublicEnum.EnumBindList_Client<PublicEnum.CallWorkBillStatus>(false, false, intStatus);

        System.Text.StringBuilder sb  = new System.Text.StringBuilder();
        HYTD.BLL.Call_CustomerBLL bll = new HYTD.BLL.Call_CustomerBLL();
        string strKeyWord             = string.Empty;

        if (!string.IsNullOrEmpty(Request["keyword"]))
        {
            strKeyWord = Request["keyword"].ToString().Trim();
        }
        System.Collections.Generic.List <Models.Call_Customer> list = bll.GetCall_CustomerList(strKeyWord);
        foreach (var m in list)
        {
            sb.Append("{ \"name\":\"" + m.CC_Name + "\", \"to\": \"" + m.CC_ID + "\" },");
        }
        strCumstomers = "[" + sb.ToString().Trim(',') + "]";
        sb.Clear();
        UserInfoBLL            uBll     = new UserInfoBLL();
        List <Models.UserInfo> userList = new List <UserInfo>();

        userList = uBll.GetUserInfoList();
        foreach (var m in userList)
        {
            sb.Append("{ \"name\":\"" + m.UserName + "\", \"to\": \"" + m.UserCode + "\" },");
        }
        strUsers = "[" + sb.ToString().Trim(',') + "]";
    }
        public IEnumerable<string> GetEdgesCsv(IEnumerable<OnergeDetay> onergeDetays)
        {
            // SOURCE_NODE_TYPE, SOURCE_NODE_NAME, EDGE_TYPE, TARGET_NODE_TYPE, TARGET_NODE_NAME, WEIGHT
            var quote = "\"";

            var nodes = new HashSet<string>();
            int batchCount = 1;

            var ret = new StringBuilder();

            foreach (var detay in onergeDetays)
            {
                if (nodes.Count + 3 >= batchCount * 500)
                {
                    yield return ret.ToString();

                    batchCount++;
                    ret.Clear();
                }

                ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Milletvekili", detay.OnergeninSahibi, "UYE", "Parti", detay.Parti, 1);
                ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Milletvekili", detay.OnergeninSahibi, "SAHIP", "Soru Önergesi", detay.EsasNumarasi, 1);
                ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Soru Önergesi", quote + detay.EsasNumarasi + quote, "MUHATAP", "Bakan", quote + detay.OnergeninMuhatabi + quote, 1);

                nodes.Add(detay.OnergeninSahibi);
                nodes.Add(detay.Parti);
                nodes.Add(detay.EsasNumarasi);
                nodes.Add(detay.OnergeninMuhatabi);
            }

            yield return ret.ToString();
        }
        public static void extract_all_resources_to_relative_directory(IFileSystem fileSystem, IAssembly assembly, string directoryPath, IList<string> relativeDirectories, string resourcesToInclude, bool overwriteExisting = false, bool logOutput = false)
        {
            var resourceString = new StringBuilder();
            foreach (var resourceName in assembly.GetManifestResourceNames())
            {
                if (!resourceName.StartsWith(resourcesToInclude))
                {
                    continue;
                }
                resourceString.Clear();
                resourceString.Append(resourceName);

                //var fileExtensionLocation = resourceName.LastIndexOf('.');
                //resourceString.Remove(fileExtensionLocation, resourceString.Length - fileExtensionLocation);
                resourceString.Replace(resourcesToInclude + ".", "");
                foreach (var directory in relativeDirectories)
                {
                    resourceString.Replace("{0}".format_with(directory), "{0}{1}".format_with(directory, fileSystem.get_path_directory_separator_char()));
                }

                // replacing \. with \
                resourceString.Replace("{0}.".format_with(fileSystem.get_path_directory_separator_char()), "{0}".format_with(fileSystem.get_path_directory_separator_char()));

                var fileLocation = resourceString.ToString();
                //var fileLocation = fileSystem.combine_paths("", resourceString.ToString().Split('.')) + resourceName.Substring(fileExtensionLocation);

                var filePath = fileSystem.combine_paths(directoryPath, fileLocation);
                if (logOutput) "chocolatey".Log().Debug("Unpacking {0} to '{1}'".format_with(fileLocation,filePath));
                extract_binary_file_from_assembly(fileSystem, assembly, resourceName, filePath, overwriteExisting);
            }
        }
Beispiel #46
0
        private string BindingToString(Hugula.Databinding.Binding binding)
        {
            sb.Clear();
            var         property  = binding.propertyName;
            var         path      = binding.path;
            var         format    = binding.format;
            BindingMode mode      = binding.mode;
            var         converter = binding.converter;
            var         source    = binding.source;

            if (!string.IsNullOrEmpty(path))
            {
                sb.AppendFormat(".{0}=({1}) ", property, path);
            }
            if (!string.IsNullOrEmpty(format))
            {
                sb.AppendFormat("format({0}) ", format);
            }
            if (mode != BindingMode.OneWay)
            {
                sb.AppendFormat("mode({0}) ", mode);
            }
            if (!string.IsNullOrEmpty(converter))
            {
                sb.AppendFormat("converter({0}) ", converter);
            }
            if (source)
            {
                //sb.AppendLine();
                sb.AppendFormat("source={0}", source.name);
            }

            return(sb.ToString());
        }
Beispiel #47
0
        private string FindIndependentTree(List<CatalogEntity> catalogList, int parent, int offset)
        {
            string Ret = "";

            StringBuilder sb = new StringBuilder();

            for (int i = offset, count = catalogList.Count; i < count; i++)
            {
                if(catalogList[i].Parent == parent)
                {
                    // Resolve the sub-tree of this ordered catalog beginning with sepcial offset in the list
                    string child = FindIndependentTree(catalogList, i, i + 1);
                    // Give the bookmark of this catalog
                    string bookmarks = GetBookmarks(catalogList[i].BookmarkList);

                    sb.Clear();

                    if (child != null && child.Length > 0)
                    {
                        sb.AppendLine(child);
                    }

                    if(bookmarks != null)
                    {
                        sb.AppendLine(bookmarks);
                    }

                    Ret += bookmarkWrapper.CatalogWrapper(catalogList[i].Catalog.Name, sb.ToString());
                }
            }

            return Ret;
        }
Beispiel #48
0
        public IEnumerable<string> Wrap(string input)
        {
            var builder = new StringBuilder();
            int pos = 0;
            var result = new List<string>();
            foreach (var chr in input)
            {
                if (!(chr == ' ' && pos == 0))
                {
                    builder.Append(chr);
                    ++pos;
                    if (pos == rowLength)
                    {
                        result.Add(builder.ToString());
                        builder.Clear();
                        pos = 0;
                    }
                }
            }

            if(builder.Length > 0)
                result.Add(builder.ToString());

            return result.AsReadOnly();
        }
        public void ParseFile(string fileName)
        {
            using (StreamReader stream = File.OpenText(fileName))
            {
                var sb = new StringBuilder();

                while (!stream.EndOfStream)
                {
                    string line = stream.ReadLine();

                    if (line != Separator)
                    {
                        sb.AppendLine(line);
                    }
                    else
                    {
                        var highlight = new Highlight(sb.ToString());
                        highlight.Parse();
                        _highlights.Add(highlight);

                        sb.Clear();
                    }
                }
            }
        }
        public void BusinessTripCanBeFill()
        {
            BusinessTrip bt = emp.GetNewBT();

            FillBT(bt);

            XmlSerializer ser = new XmlSerializer(typeof(BusinessTrip));
            StringBuilder sb  = new System.Text.StringBuilder();
            string        serializedBT;

            using (var s = new System.IO.StringWriter(sb))
            {
                ser.Serialize(s, bt);
                serializedBT = sb.ToString();
            }

            BusinessTrip newBt;

            using (var r = new System.IO.StringReader(serializedBT))
            {
                newBt = (BusinessTrip)ser.Deserialize(r);
            }

            sb.Clear();
            string serializedNewBT;

            using (var s = new System.IO.StringWriter(sb))
            {
                ser.Serialize(s, bt);
                serializedNewBT = sb.ToString();
            }

            Assert.AreEqual(serializedBT, serializedNewBT);
        }
Beispiel #51
0
 public void DoWorkflow(Table replaceClass, ref List<string> fileName)
 {
   StringBuilder stringBuilder1 = new StringBuilder();
   foreach (Column column in replaceClass.Columns)
   {
     if (Common.IsWorkFlow(column.Comment))
     {
       StringBuilder stringBuilder2 = new StringBuilder();
       string oldValue = "<Compile Include=@Properties\\AssemblyInfo.cs@ />".Replace('@', '"');
       string str1 = column.Comment.Replace('【', '[').Replace('】', ']').Replace(',', ',');
       string[] strArray = str1.Substring(str1.IndexOf('[') + 1, str1.IndexOf(']') - str1.IndexOf('[') - 1).Split(',');
       string newValue1 = str1.Substring(0, str1.ToUpper().IndexOf("WORKFLOW"));
       for (int index = 0; index < strArray.Length; ++index)
       {
         string newValue2 = replaceClass.Code + column.Code + index.ToString();
         string content = Common.Read(BaseClass.m_DempDirectory + "/CodeActivity1.cs").Replace("DAL", replaceClass.NameSpace + "DAL").Replace("WFActivitys", replaceClass.NameSpace + "WFActivitys").Replace("CodeActivity1", newValue2).Replace(this.m_ReplaceClassCode, replaceClass.Code).Replace(this.m_ReplaceClassName, replaceClass.Name).Replace(this.m_ReplaceAttribute, strArray[index]).Replace("^State^", column.Code).Replace(this.m_Id, Common.GetFirstPrimaryKeyCode(replaceClass)).Replace("WF", newValue1);
         Common.Write(BaseClass.m_RootDirectory + "/WFActivitys/" + newValue2 + ".cs", content);
         string str2 = "    <Compile Include=@Framework@ />\r\n            ".Replace('@', '"');
         stringBuilder2.Append(str2.Replace("Framework", newValue2 + ".cs"));
       }
       stringBuilder2.Append(oldValue);
       string path = BaseClass.m_RootDirectory + "/WFActivitys/WFActivitys.csproj";
       Common.Write(path, Common.Read(path).Replace(oldValue, stringBuilder2.ToString()).Replace("<RootNamespace>WFActivitys</RootNamespace>", "<RootNamespace>" + replaceClass.NameSpace + "WFActivitys</RootNamespace>"));
       stringBuilder2.Clear();
     }
   }
 }
Beispiel #52
0
        public static IEnumerable<LogEntry> ParseLogLines(IEnumerable<string> lines)
        {
            var multilineMessage = new StringBuilder();

            LogEntry currentEntry = null;
            foreach (string line in lines)
            {
                LogEntry nextEntry = LogEntry.Parse(line);
                if (nextEntry != null)
                {
                    if (currentEntry != null)
                    {
                        if (multilineMessage.Length > 0)
                        {
                            currentEntry.Message = multilineMessage.ToString();
                            multilineMessage.Clear();
                        }

                        yield return currentEntry;
                    }
                    currentEntry = nextEntry;
                }
                else
                {
                    if (currentEntry != null)
                    {
                        if (multilineMessage.Length == 0)
                        {
                            multilineMessage.Append(currentEntry.Message);
                        }

                        multilineMessage.AppendLine(line);
                    }
                }
            }

            if (currentEntry != null)
            {
                if (multilineMessage.Length > 0)
                {
                    currentEntry.Message = multilineMessage.ToString();
                    multilineMessage.Clear();
                }

                yield return currentEntry;
            }
        }
Beispiel #53
0
    IEnumerator DoSpawnQueue()
    {
        var wait = new WaitForSeconds(spawnDelay);

        while (mSpawnQueue.Count > 0)
        {
            while (mBlobActives.IsFull) //wait for blobs to release
            {
                yield return(null);
            }

            yield return(wait);

            var spawnInfo = mSpawnQueue.Dequeue();

            //find valid spawn point
            Vector2 spawnPt = Vector2.zero;

            while (true)
            {
                var pt = mSpawnPts[mCurSpawnPtInd];
                mCurSpawnPtInd++;
                if (mCurSpawnPtInd == mSpawnPts.Length)
                {
                    mCurSpawnPtInd = 0;
                }

                //check if valid
                var coll = Physics2D.OverlapCircle(pt, spawnPointCheckRadius, spawnPointCheckMask);
                if (!coll)
                {
                    spawnPt = pt;
                    break;
                }

                //invalid, check next
                yield return(null);
            }

            //spawn
            mSpawnParms[JellySpriteSpawnController.parmPosition] = spawnPt;
            mSpawnParms[Blob.parmNumber] = spawnInfo.number;

            var template = templateGroups[spawnInfo.templateIndex].template;

            mBlobNameCache.Clear();
            mBlobNameCache.Append(template.name);
            mBlobNameCache.Append(' ');
            mBlobNameCache.Append(spawnInfo.number);

            var blob = mPool.Spawn <Blob>(template.name, mBlobNameCache.ToString(), null, mSpawnParms);

            blob.poolData.despawnCallback += OnBlobRelease;

            mBlobActives.Add(blob);
        }

        mSpawnRout = null;
    }
Beispiel #54
0
 /// <summary>
 ///     Fired by the item destroyer event prefab after items are destroyed.
 /// </summary>
 /// <returns>
 ///     The <see cref="string" />.
 /// </returns>
 protected override string OnPreDestroyItems()
 {
     var _floodPrompt = new StringBuilder();
     _floodPrompt.Clear();
     _floodPrompt.AppendLine("Severe hail storm");
     _floodPrompt.Append("results in");
     return _floodPrompt.ToString();
 }
Beispiel #55
0
 public override void Flush()
 {
     if (_buffer.Length > 0)
     {
         System.Diagnostics.Debug.WriteLine(_buffer);
         _buffer.Clear();
     }
 }
 void IDisposable.Dispose()
 {
     if (_sb != null)
     {
         _sb.Clear();
         _sb = null;
     }
     _plugin = null;
 }
Beispiel #57
0
        /// <summary>
        /// Get the organization name and on-line region from the Uri
        /// </summary>
        /// <param name="serviceUri">Service Uri to parse</param>
        /// <param name="isOnPrem">if OnPrem, will be set to true, else false.</param>
        /// <param name="onlineRegion">Name of the CRM on line Region serving this request</param>
        /// <param name="organizationName">Name of the Organization extracted from the Service URI</param>
        public static void GetOrgnameAndOnlineRegionFromServiceUri(Uri serviceUri, out string onlineRegion, out string organizationName, out bool isOnPrem)
        {
            isOnPrem         = false;
            onlineRegion     = string.Empty;
            organizationName = string.Empty;

            //support for detecting a Online URI in the path and rerouting to use that..
            if (IsValidOnlineHost(serviceUri))
            {
                try
                {
                    // Determine deployment region from Uri
                    List <string> elements = new List <string>(serviceUri.Host.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries));
                    organizationName = elements[0];
                    elements.RemoveAt(0);                     // remove the first ( org name ) from the Uri.


                    // construct Prospective CRM Online path.
                    System.Text.StringBuilder buildPath = new System.Text.StringBuilder();
                    foreach (var item in elements)
                    {
                        if (item.Equals("api"))
                        {
                            continue;                             // Skip the .api. when running via this path.
                        }
                        buildPath.AppendFormat("{0}.", item);
                    }
                    string crmKey = buildPath.ToString().TrimEnd('.').TrimEnd('/');
                    buildPath.Clear();
                    if (!string.IsNullOrEmpty(crmKey))
                    {
                        using (CdsDiscoveryServers discoSvcs = new CdsDiscoveryServers())
                        {
                            // drop in the discovery region if it can be determined.  if not, default to scanning.
                            var locatedDiscoServer = discoSvcs.OSDPServers.Where(w => w.DiscoveryServer != null && w.DiscoveryServer.Host.Contains(crmKey)).FirstOrDefault();
                            if (locatedDiscoServer != null && !string.IsNullOrEmpty(locatedDiscoServer.ShortName))
                            {
                                onlineRegion = locatedDiscoServer.ShortName;
                            }
                        }
                    }
                    isOnPrem = false;
                }
                finally
                { }
            }
            else
            {
                isOnPrem = true;
                //Setting organization for the AD/Onpremise Oauth/IFD
                if (serviceUri.Segments.Count() >= 2)
                {
                    organizationName = serviceUri.Segments[1].TrimEnd('/');                     // Fix for bug 294040 http://vstfmbs:8080/tfs/web/wi.aspx?pcguid=12e6d33f-1461-4da4-b3d9-5517a4567489&id=294040
                }
            }
        }
Beispiel #58
0
 public static string AppendToString(params object[] parts)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     sb.Clear();
     for (int i = 0, len = parts.Length; i < len; i++)
     {
         sb.Append(parts[i].ToString());
     }
     return(sb.ToString());
 }
        private void CreateOrAddSession(bool isCreate)
        {
            if (!isCreate)
            {
                fileLoggerStringBuilder.Append(Environment.NewLine).Append("~").
                Append(Environment.NewLine).Append(Environment.NewLine).Append(Environment.NewLine);
            }

            fileLoggerStringBuilder.Append("Session Number: ").Append(Guid.NewGuid()).Append("\n");
            fileLoggerStringBuilder.Append("Session Date: ").
            Append(DateTime.Now.Day).Append(".").
            Append(DateTime.Now.Month).Append(".").
            Append(DateTime.Now.Year).
            Append(" ").
            Append(DateTime.Now.Hour).Append(":").
            Append(DateTime.Now.Minute).Append(":").
            Append(DateTime.Now.Second).
            Append("\n");
            fileLoggerStringBuilder.Append("CustomLogger Version: ").Append(loggerVersion).Append("\n");
            fileLoggerStringBuilder.Append("@").Append("\n");
#if !UNITY_EDITOR
            AndroidJavaObject javaClass       = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = javaClass.GetStatic <AndroidJavaObject>("currentActivity");
            AndroidJavaObject unityContext    = currentActivity.Call <AndroidJavaObject>("getApplicationContext");
            string            packageName     = unityContext.Call <string>("getPackageName");

            AndroidJavaObject packageManager = currentActivity.Call <AndroidJavaObject>("getPackageManager");
            AndroidJavaObject packageInfo    = packageManager.Call <AndroidJavaObject>("getPackageInfo", packageName, 0);

            int    apiLevel   = new AndroidJavaClass("android.os.Build$VERSION").GetStatic <int>("SDK_INT");
            string deviceName = new AndroidJavaClass("android.os.Build").GetStatic <string>("MODEL");

            fileLoggerStringBuilder.Append("Build Version: ").Append(Application.version).Append("\n");
            fileLoggerStringBuilder.Append("Bundle Version Code: ").Append(packageInfo.Get <string>("versionName")).Append("\n");
            fileLoggerStringBuilder.Append("Package Name: ").Append(packageName).Append("\n");
            fileLoggerStringBuilder.Append("Android Version: ").Append(apiLevel).Append("\n");
            fileLoggerStringBuilder.Append("Device Name: ").Append(deviceName).Append("\n");
            fileLoggerStringBuilder.Append("@").Append("\n");
#endif
            File.AppendAllText(localLogFilePath, fileLoggerStringBuilder.ToString());
            fileLoggerStringBuilder.Clear();
            LogMessage("Setup log file success!");
        }
Beispiel #60
0
    public void Setup(GridLevelData.Goal goal)
    {
        icon.sprite    = goal.data.icon;
        titleText.text = M8.Localize.Get(goal.data.nameTextRef);

        mSB.Clear();

        mSB.Append("· ");
        mSB.Append(M8.Localize.Get(volumeReqTextRef));

        var editCtrl = GridEditController.instance;

        var goalVolume = goal.volume * editCtrl.levelData.unitVolume;

        //goalVolume.SimplifyImproper();
        //goalVolume.Simplify();
        goalVolume.FractionToWhole();

        var goalHeight = goal.unitHeightRequire * editCtrl.levelData.sideMeasure;

        goalHeight.SimplifyImproper();

        if (goalHeight.fValue > 0f)
        {
            mSB.Append('\n');
            mSB.Append("· ");
            mSB.Append(M8.Localize.Get(heightReqTextRef));
        }

        descText.text = mSB.ToString();

        mSB.Clear();

        mSB.Append(UnitMeasure.GetVolumeText(goal.measureType, goalVolume));

        if (goalHeight.fValue > 0f)
        {
            mSB.Append('\n');
            mSB.Append(UnitMeasure.GetMeasureText(goal.measureType, goalHeight));
        }

        valueText.text = mSB.ToString();
    }