Esempio n. 1
12
        public String cmd(String cnd)
        {

            cnd = cnd.Trim();
            String output = " ";
            Console.WriteLine(cnd);

            if ((cnd.Substring(0, 3).ToLower() == "cd_") && (cnd.Length > 2))
            {

                if (System.IO.Directory.Exists(cnd.Substring(2).Trim()))
                    cpath = cnd.Substring(2).Trim();

            }
            else
            {
                cnd = cnd.Insert(0, "/B /c ");
                Process p = new Process();
                p.StartInfo.WorkingDirectory = cpath;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.Arguments = cnd;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                output = p.StandardOutput.ReadToEnd();  // output of cmd
                output = (output.Length == 0) ? " " : output;
                p.WaitForExit();

            }
            return output;
        } // end cmd 
Esempio n. 2
0
        static void Main(string[] args)
        {
            //"Hello"
            System.String s = "Hello";
            Console.WriteLine(s);
            Console.WriteLine(s.GetHashCode()); //HashCode - как номер паспорта

            //---------------------
            //Immutable types - типы, которые невозможно изменить. Если мы пытаемся изменить, то у нас создается
            //новый экзампляр этого типа, а старый экземпляр НЕ ИЗМЕНЯЕТСЯ(или погибает в случае s = s + "a";
            s = s.Insert(2, "mmmmm"); //HashCod`ы будут разные т.к string - это immutable type и вместо старой s, теперь уже новая s.
            //s[2] индексаторов нету
            Console.WriteLine(s);
            Console.WriteLine(s.GetHashCode());

            //---------------------
            String s2 = new string('-', 20);

            //Hemmmmmlo------------------------------
            s += s2;

            //"5"
            //На экране есть ЗНАКОМЕСТА (alt + shift) и моно выделять знакоместа с рядов повыше и пониже
            string s4 = 5.ToString(); //по умолчанию ToString(); выводит полное квалифицированное имя класса.

            //"1 + 2 = 3";
            string s5 = String.Format("{0} + {1} = {2}", 1, 2, 1 + 2);


            //Delay
            Console.ReadKey();
        }
Esempio n. 3
0
 /// <summary>
 /// Get DateTime from string
 /// </summary>
 /// <param name="dateTimeString">String containing DateTime</param>
 /// <returns>Object of DateTime</returns>
 internal static DateTime getDateTime(String dateTimeString)
 {
     DateTime dateTime;
     dateTimeString = dateTimeString.Insert(10, " ");
     dateTime = Convert.ToDateTime(dateTimeString);
     return dateTime;
 }
Esempio n. 4
0
        static void Main()
        {
            // "Hello"
            System.String s = "Hello";
            Console.WriteLine(s);
            Console.WriteLine(s.GetHashCode());
            s = s.Insert(2, "mm");
            //s[2] = 'm';
            Console.WriteLine(s);
            Console.WriteLine(s.GetHashCode());
            // "-----------------------------------------------"
            String s2 = new string('-', 20);

            //"Hello-----------------------------------------------"
            s += s2;  //s = s + s2;

            //"5"
            string s4 = 5.ToString();

            //"1 + 2 = 3"
            string s5 = String.Format("{0} + {1} = {2}", 1, 2, 1 + 2);


            // Delay
            Console.ReadKey();
        }
Esempio n. 5
0
 /// <summary>
 /// Replace the document id in the given metadata
 /// </summary>
 /// <param name="metadata">A metadata string</param>
 /// <param name="documentid">The document id which should be inserted</param>
 /// <returns>Returns a metadata string with the new document id</returns>
 public static String ReplaceDocumentIDInMetadata(String metadata, int documentid)
 {
     int startIndex = metadata.IndexOf("docid") + 5;
     int endIndex = metadata.IndexOf("|");
     metadata = metadata.Remove(startIndex, endIndex - startIndex);
     metadata = metadata.Insert(startIndex, " " + documentid.ToString());
     return metadata;
 }
 private static string CheckForImplicitMultiplication(String expression)
 {
     for (var i = 1; i < expression.Count() - 1; i++)
         if ((expression[i] == ')' && Char.IsNumber(expression[i + 1])) ||
            (expression[i] == '(' && Char.IsNumber(expression[i - 1])))
             expression = expression.Insert(i + 1, "*");
     return expression;
 }
        private static String swapSecondAndThirdDigits(String str)
        {
            String tmp = str[1].ToString();
            str = str.Remove(1, 1);
            str = str.Insert(2, tmp);

            return str;
        }
Esempio n. 8
0
 private String capitalize(String text)
 {
     String first = text[0].ToString();
     text = text.Remove(0, 1);
     first = first.ToUpper();
     text = text.Insert(0, first);
     return text;
 }
 public void CleanString(String s)
 {
     if (s.Length != 0) {
         s.Replace(" ", "");
         while (s.Length < 8) {
             s.Insert(0, "0");
         }
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Reads matrix and branches (if exists) from specified file.
        /// </summary>
        /// <param name="filePath">File path.</param>
        /// <param name="networkSize">The size of the network (matrix, which represents the network).</param>
        /// <param name="matrixType">The type of given matrix (content of the specified file)</param>
        /// <returns>Matrix and branches (if exists).</returns>
        /// <throws>CoreException, MatrixFormatException.</throws>
        public static MatrixInfoToRead Read(String filePath, int networkSize, AdjacencyMatrixType matrixType)
        {
            MatrixInfoToRead result = new MatrixInfoToRead();

            result.Matrix = MatrixReader(filePath, networkSize, matrixType);
            result.Branches = BranchesReader(filePath.Insert(filePath.Length - 4, "_branches"));

            return result;
        }
Esempio n. 11
0
        /// <summary>
        /// Parse a rfc 2822 date and time specification. rfc 2822 section 3.3
        /// </summary>
        /// <param name="date">rfc 2822 date-time</param>
        /// <returns>A <see cref="System.DateTime" /> from the parsed header body</returns>
        public static System.DateTime parseDate(System.String date)
        {
            if (date == null || date.Equals(System.String.Empty))
            {
                return(System.DateTime.MinValue);
            }
            System.DateTime msgDateTime;
            date        = anmar.SharpMimeTools.SharpMimeTools.uncommentString(date);
            msgDateTime = new System.DateTime(0);
            try
            {
                // TODO: Complete the list
                date = date.Replace("UT", "+0000");
                date = date.Replace("GMT", "+0000");
                date = date.Replace("EDT", "-0400");
                date = date.Replace("EST", "-0500");
                date = date.Replace("CDT", "-0500");
                date = date.Replace("MDT", "-0600");
                date = date.Replace("MST", "-0600");
                date = date.Replace("EST", "-0700");
                date = date.Replace("PDT", "-0700");
                date = date.Replace("PST", "-0800");

                date = date.Replace("AM", System.String.Empty);
                date = date.Replace("PM", System.String.Empty);
                int rpos = date.LastIndexOfAny(new Char[] { ' ', '\t' });
                if (rpos > 0 && rpos != date.Length - 6)
                {
                    date = date.Substring(0, rpos + 1) + "-0000";
                }
                date        = date.Insert(date.Length - 2, ":");
                msgDateTime = DateTime.ParseExact(date,
                                                  _date_formats,
                                                  System.Globalization.CultureInfo.CreateSpecificCulture("en-us"),
                                                  System.Globalization.DateTimeStyles.AllowInnerWhite);
#if LOG
            } catch (System.Exception e) {
                if (log.IsErrorEnabled)
                {
                    log.Error(System.String.Concat("Error parsing date: [", date, "]"), e);
                }
#else
            }
            catch (System.Exception)
            {
#endif
                msgDateTime = new System.DateTime(0);
            }
            return(msgDateTime);
        }
Esempio n. 12
0
        public static string Tag(String rootRelativePath)
        {
            if (HttpRuntime.Cache[rootRelativePath] == null)
            {
                string absolute = HostingEnvironment.MapPath("~" + rootRelativePath);

                DateTime date = File.GetLastWriteTime(absolute);
                int index = rootRelativePath.LastIndexOf('/');

                string result = rootRelativePath.Insert(index, "/v-" + date.Ticks);
                HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute));
            }

            return HttpRuntime.Cache[rootRelativePath] as string;
        }
Esempio n. 13
0
        public static String _ConvertToStringFilePath(String _filePath)
        {
            char searchChar = '\\';
            Int32 index = new Int32();

            while((index = _filePath.IndexOf(searchChar, index)) != -1)
            {
                if ((index + 1) < _filePath.Length && _filePath[index + 1] != searchChar)
                {
                    _filePath.Insert(index, searchChar.ToString());
                    index++;
                }

                index++;
            }

            return _filePath;
        }
Esempio n. 14
0
        private string ParseANSI(String s)
        {
            //統一用\n換行
            s = s.Replace( "\r\n", "\n" ).Replace( "\r", "\n" );

            //htmlspecialchars()
            s = s.Replace( "&", "&amp;" ).Replace( "<", "&lt;" ).Replace( ">", "&gt;" );

            /* TODO: 目前取時間有誤 */
            //解析作者、看板、標題、時間等資訊
            //s = Regex.Replace( s, "^(?:作者|發信人):\\s([^\\s]*)\\s\\(([^\\)]*)\\)\\s(站內|看板):\\s([^(\\r|\\n)]*)(?:\\r\\n|\\r|\\n)(?:標題|標  題):\\s([^(\\r|\\n)]*)(?:\\r\\n|\\r|\\n)(?:時間|發信站):\\s([^(\\r|\\n)]*)?\\s?\\(?(d{4}\\/\\d{2}\\/\\d{2}\\s(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\\s\\d{2}:\\d{2}:\\d{2})\\)?"
            s = Regex.Replace( s, "^(?:作者|發信人):\\s([^\\s]*)\\s\\(([^\\)]*)\\)\\s(站內|看板):\\s([^\\n]*)\\n(?:標題|標  題):\\s([^\\n]*)\\n(?:時間|發信站):\\s([^\\n]*)"
                , "<div class=\"entry-meta\"><div class=\"author vcard\"><span class=\"label\">作者</span> <span class=\"nickname\">$1</span> (<span class=\"fn n\">$2</span>)</div><div class=\"board\"><span class=\"label\">$3</span> <span class=\"board-title\">$4</span></div><div class=\"entry-title\"><span class=\"label\">標題</span> <h1>$5</h1></div><div class=\"entry-date\"><span class=\"label\">時間</span> <span class=\"published\">$6</span></div></div>"
                , RegexOptions.Compiled );

            //找地方插入 <pre class="entry-content">
            int content_pos = s.Contains( "</div>\n" ) ? s.LastIndexOf( "</div>\n" ) + 7 : 0;
            s = s.Insert( content_pos, "<pre class=\"entry-content\">" );

            //解析「※」開頭文字
            s = Regex.Replace( s, "^※.*$", "<span class=\"quote\">$&</span>", RegexOptions.Multiline );

            /* TODO: 要作巢狀引文嗎? */
            //解析引文
            s = Regex.Replace( s, "^(?:&gt;|:)\\s.*$", "<blockquote>$&</blockquote>", RegexOptions.Multiline )
                .Replace( "</blockquote>\n<blockquote>", "\n" ); //移除多餘標注

            //取出控制碼,執行ANSI轉HTML
            s = Regex.Replace( s, "\u001B\\[([0-7;]*)m", new MatchEvaluator( this._ParseANSI ), RegexOptions.Compiled );

            //如果前面有未關閉的標籤,先關閉之
            s += opened == true ? "</span>" : "";

            //處理超連結
            s = Regex.Replace( s, "(https?|ftps?|telnet|mms|rtsp|ircs?|ed2k|ssh|svn|svn+ssh)://[0-9a-zA-Z/?|@:%&#~=$-_.+!*'()\\,]+", "<a href=\"$&\">$&</a>", RegexOptions.Compiled );
            s = Regex.Replace( s, "[0-9a-zA-Z.!#$%*/?|^{}`~&'+-=_]+@[0-9a-zA-Z-.]+", "<a href=\"mailto:$&\">$&</a>", RegexOptions.Compiled );

            s += "</pre>";

            return s;
        }
Esempio n. 15
0
        /// <summary>
        ///     Parse a rfc 2822 date and time specification. rfc 2822 section 3.3
        /// </summary>
        /// <param name="date">rfc 2822 date-time</param>
        /// <returns>A <see cref="System.DateTime" /> from the parsed header body</returns>
        public static DateTime parseDate( String date )
        {
            if ( date==null || date.Equals(String.Empty) )
                return DateTime.MinValue;
            DateTime msgDateTime;
            date = SharpMimeTools.SharpMimeTools.uncommentString (date);
            msgDateTime = new DateTime (0);
            try {
                // TODO: Complete the list
                date = date.Replace("UT", "+0000");
                date = date.Replace("GMT", "+0000");
                date = date.Replace("EDT", "-0400");
                date = date.Replace("EST", "-0500");
                date = date.Replace("CDT", "-0500");
                date = date.Replace("MDT", "-0600");
                date = date.Replace("MST", "-0600");
                date = date.Replace("EST", "-0700");
                date = date.Replace("PDT", "-0700");
                date = date.Replace("PST", "-0800");

                date = date.Replace("AM", String.Empty);
                date = date.Replace("PM", String.Empty);
                int rpos = date.LastIndexOfAny(new Char[]{' ', '\t'});
                if (rpos>0 && rpos != date.Length - 6)
                    date = date.Substring(0, rpos + 1) + "-0000";
                date = date.Insert(date.Length-2, ":");
                msgDateTime = DateTime.ParseExact(date,
                    _date_formats,
                    CultureInfo.CreateSpecificCulture("en-us"),
                    DateTimeStyles.AllowInnerWhite);
            #if LOG
            } catch ( System.Exception e ) {
                if ( log.IsErrorEnabled )
                    log.Error(System.String.Concat("Error parsing date: [", date, "]"), e);
            #else
            } catch ( Exception ) {
            #endif
                msgDateTime = new DateTime (0);
            }
            return msgDateTime;
        }
        static StackObject *Insert_16(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @value = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Int32 @startIndex = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.String instance_of_this_method = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.Insert(@startIndex, @value);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
        private void parseLine(String parsedLine)
        {
            if (modeCountOnly)
            {
                if (parsedLine.StartsWith("  ") && parsedLine.Length != 2) numTests++;
            }
            else
            {
                if (TEST_START.IsMatch(parsedLine))
                {
                    currentTestName = TEST_START.Match(parsedLine).Groups[1].Value;
                    potentialErrorText = "";
                }
                else if (currentTestName != null)
                {
                    if (parsedLine.StartsWith("[       OK ] " + currentTestName))
                    {
                        notifyTestComplete(currentTestName, null);
                        currentTestName = null;
                    }
                    else if (parsedLine.StartsWith("[  FAILED  ] " + currentTestName))
                    {
                        notifyTestComplete(currentTestName, potentialErrorText);
                        currentTestName = null;
                    }
                    else if (!parsedLine.StartsWith("["))
                    {
                        int errorStringIndex = parsedLine.IndexOf(": error:");
                        if (errorStringIndex != -1)
                        {
                            int errorStringStartsAt = errorStringIndex + 8;
                            parsedLine = parsedLine.Remove(errorStringStartsAt, 1);
                            parsedLine = parsedLine.Insert(errorStringStartsAt, "\r\n");
                        }
                        potentialErrorText += parsedLine + "\r\n";
                    }
                }
            }

        }
Esempio n. 18
0
        public void RSA_SendString(String _TxData)
        {
            //Pad the string length with whitespace to make a size evenly divisible into blocks:
            int toAdd = _TxData.Length % BlockSize;
            for(int i = 0; i < toAdd; i++)
            {
                _TxData = _TxData.Insert(_TxData.Length, " ");
            }

            //Figure out how many blocks need to be transmitted:
            int numBlocks = _TxData.Length / BlockSize;

            //Start the message transmit:
            m_CommStack.StartEncryptedMessage(numBlocks);

            //Encrypt the blocks and dump into the output stream:
            for (int i = 0; i < numBlocks; i++)
            {
                char[] temp = _TxData.ToCharArray(i * BlockSize, BlockSize);
                byte[] bytes = new byte[BlockSize];

                int j = 0;
                foreach (char c in temp)
                {
                    bytes[j++] = Convert.ToByte(c);
                }

                byte[] encrypted = m_RSAEncryptSvc.Encrypt(bytes, false);

                //Transmit the encrypted block.
                m_CommStack.TransmitEncryptedBlock(BlockSize, encrypted);
            }

            //Transmit end encrypted message
            m_CommStack.EndEncryptedMessage();
        }
Esempio n. 19
0
  private String InsertInterestingChars(String strText){
  //We should return the same length string back after inserting the problematic characters, 
  String strInteresting = RetrieveSectionInfo( enuDataSectionTypes.CHARS_TO_INCLUDE_IN_STRING, false );
            
  String strLine = GetRandomLine( strInteresting );

  if ( strLine == String.Empty ) 
    return strText ;

  // Remove strLine.Length number of characters from the string to include the strLine.
  if ( strText.Length > strLine.Length) {
  strText = strText.Remove( rand.Next(0, strText.Length - strLine.Length) , strLine.Length );
  strText = strText.Insert( rand.Next(0, strText.Length), strLine );
  }

  return strText; 
  }
Esempio n. 20
0
        internal unsafe static String AddLongPathPrefix(String path)
        {
            if (path.StartsWith(LongPathPrefix, StringComparison.Ordinal))
                return path;

            if (path.StartsWith(UNCPathPrefix, StringComparison.Ordinal))
                return path.Insert(2, UNCLongPathPrefixToInsert); // Given \\server\share in longpath becomes \\?\UNC\server\share  => UNCLongPathPrefix + path.SubString(2); => The actual command simply reduces the operation cost.

            return LongPathPrefix + path;
        }
Esempio n. 21
0
 private bool replaceHighASCII()
 {
     bool found = false;
     for (int i = 0; i < _modifiedClip.Length; ++i)
     {
         char c = _modifiedClip[i];
         if (c > 0x9F)
         {
             found = true;
             String entityCode = "&#" + (int)(c) + ";";
             _modifiedClip = _modifiedClip.Remove(i, 1);
             _modifiedClip = _modifiedClip.Insert(i, entityCode);
             // we could increment i here but there's no real need since anything we add won't be bad
         }
     }
     return found;
 }
Esempio n. 22
0
        private void saveFile(XmlDocument doc, String path, String fileName, String type)
        {
            if(path.EndsWith("\\"))
            {
                if (!Directory.Exists(path + "PP-Nx"))
                {
                    Directory.CreateDirectory(path + "PP-Nx");
                }

                if (!Directory.Exists(path + "PP-Ny"))
                {
                    Directory.CreateDirectory(path + "PP-Ny");
                }

                if (!Directory.Exists(path + "PP-I"))
                {
                    Directory.CreateDirectory(path + "PP-I");
                }

                switch(type)
                {
                    case "TP1a":
                        {
                            int i=1;
                            while(File.Exists(path + "PP-Nx\\" + fileName)){
                                if (fileName.Substring(fileName.Length - 6, 2).Contains("Nx"))
                                {
                                    fileName = fileName.Insert(fileName.Length - 4, "_" + i);
                                }
                                else
                                {
                                    fileName = fileName.Substring(0, fileName.Length - 6) + "_" + i + ".xml";

                                }
                                i++;
                            }

                            doc.Save(path + "PP-Nx\\" + fileName);
                            break;
                        }
                    case "TP1b":
                        {
                            int i = 1;
                            while (File.Exists(path + "PP-Ny\\" + fileName))
                            {
                                if (fileName.Substring(fileName.Length - 6, 2).Contains("Ny"))
                                {
                                    fileName = fileName.Insert(fileName.Length - 4, "_" + i);
                                }
                                else
                                {
                                    fileName = fileName.Substring(0, fileName.Length - 6) + "_" + i + ".xml";

                                }
                                i++;
                            }

                            doc.Save(path + "PP-Ny\\" + fileName);
                            break;
                        }
                    case "TP3":
                        {
                            int i = 1;
                            while (File.Exists(path + "PP-I\\" + fileName))
                            {
                                if (fileName.Substring(fileName.Length - 6, 2).Contains("I_"))
                                {
                                    fileName = fileName.Insert(fileName.Length - 4, "_" + i);
                                }
                                else
                                {
                                    fileName = fileName.Substring(0, fileName.Length - 6) + "_" + i + ".xml";
                                }
                                i++;
                            }

                            doc.Save(path + "PP-I\\" + fileName);
                            break;
                        }
                }

            }
            else
            {
                if (!Directory.Exists(path + "\\" + "PP-Nx"))
                {
                    Directory.CreateDirectory(path + "\\" + "PP-Nx");
                }

                if (!Directory.Exists(path + "\\" + "PP-Ny"))
                {
                    Directory.CreateDirectory(path + "\\" + "PP-Ny");
                }

                if (!Directory.Exists(path + "\\" + "PP-I"))
                {
                    Directory.CreateDirectory(path + "\\" + "PP-I");
                }

                switch (type)
                {
                    case "TP1a":
                        {
                            int i = 1;

                            while (File.Exists(path + "\\" + "PP-Nx\\" + fileName))
                            {

                                if (fileName.Substring(fileName.Length - 6, 2).Contains("Nx"))
                                {
                                    fileName = fileName.Insert(fileName.Length - 4, "_" + i);
                                }
                                else
                                {
                                    fileName = fileName.Substring(0, fileName.Length - 6) + "_" + i + ".xml";

                                }

                                i++;
                            }

                            doc.Save(path + "\\" + "PP-Nx\\" + fileName);
                            break;
                        }
                    case "TP1b":
                        {
                            int i = 1;
                            while (File.Exists(path + "\\" + "PP-Ny\\" + fileName))
                            {
                                if (fileName.Substring(fileName.Length - 6, 2).Contains("Ny"))
                                {
                                    fileName = fileName.Insert(fileName.Length - 4, "_" + i);
                                }
                                else
                                {
                                    fileName = fileName.Substring(0, fileName.Length - 6) + "_" + i + ".xml";

                                }
                                i++;
                            }

                            doc.Save(path + "\\" + "PP-Ny\\" + fileName);
                            break;
                        }
                    case "TP3":
                        {
                            int i = 1;
                            while (File.Exists(path + "\\" + "PP-I\\" + fileName))
                            {

                                if (fileName.Substring(fileName.Length - 6, 2).Contains("I_"))
                                {
                                    fileName = fileName.Insert(fileName.Length - 4, "_" + i);
                                }
                                else
                                {
                                    fileName = fileName.Substring(0, fileName.Length - 6)+"_"+i+".xml";

                                }
                                i++;
                            }

                            doc.Save(path + "\\" + "PP-I\\" + fileName);
                            break;
                        }
                }
            }
        }
Esempio n. 23
0
        private String ToPlainText(String text)
        {
            text = RemoveCodes1(text);

            while (true)
            {
                int i1 = text.IndexOf("[g");
                if (i1 < 0)
                {
                    break;
                }

                int i2 = text.IndexOf("[t", i1 + 2);
                int i3 = text.IndexOf("[g", i1 + 2);

                if ((i2 < 0) && (i3 < 0))
                {
                    text = text.Remove(i1);
                }
                else
                {
                    int i4 = Math.Min(i2, i3);
                    if (i2 < 0)
                    {
                        i4 = i3;
                    }
                    else if (i3 < 0)
                    {
                        i4 = i2;
                    }

                    text = text.Remove(i1, i4 - i1);
                    text = text.Insert(i1, new String(' ', i4 - i1 - 5));
                }
            }

            return RemoveCodes(text).PadRight(40);
        }
Esempio n. 24
0
        /// <summary>Encode a 32bit integer according to the Seaman-Pence proposal.</summary>
        /// <param name="c">The checksum previously calculated.</param>
        /// <return>The encoded string of 16 bytes.</param>
        private static String ChecksumEnc(long c, bool compl)
        {
            byte[] asc = new byte[16];
            int[] exclude = { 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60 };
            long[] mask = { 0xff000000L, 0xff0000L, 0xff00L, 0xffL};
            int offset = 0x30;	/* ASCII 0 (zero */
            long value = compl ? ~c: c;
            for (int i=0 ; i < 4 ; i++)
            {
                int byt = (int) ((value & mask[i]) >> (24 - 8*i)) ;	// each byte becomes four
                int quotient = byt /4 + offset;
                int remainder = byt % 4;
                int[] ch = new int[4];
                for (int j=0 ; j < 4 ; j++)
                    ch[j] = quotient;

                ch[0] += remainder;
                bool check = true;
                for(; check ; )	// avoid ASCII punctuation
                {
                    check= false;

                    for (int k=0; k < exclude.Length ; k++)
                        for (int j=0; j < 4 ; j +=2)
                            if ( ch[j] == exclude[k] || ch[j+1] == exclude[k])
                            {
                                ch[j]++;
                                ch[j+1]--;
                                check = true;
                            }
                }

                for (int j=0; j < 4 ; j++)	// assign the bytes
                    asc[4*j+i] = (byte)(ch[j]);
            }

            // shift the bytes 1 to the right circularly.
            String resul = new String(SupportClass.ToCharArray(asc), 15, 1) ;
            return resul.Insert(resul.Length, new String(SupportClass.ToCharArray(asc), 0, 15)) ;
        }
Esempio n. 25
0
	public void cmd(String cnd)
	{
        cnd.Insert("/c ", 0); 

	}
Esempio n. 26
0
        /// <summary>
        /// Capitalize the first letter of the word
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public static String Capitalize(String word)
        {
            Log.Debug(word);
            if (String.IsNullOrEmpty(word))
            {
                return word;
            }

            // find the first non-whitespace character
            int index = 0;
            while (index < word.Length)
            {
                if (!Char.IsWhiteSpace(word[index]))
                {
                    break;
                }

                index++;
            }

            char c = word[index];
            Log.Debug("index: " + index + "c: " + c.ToString());

            if (!Char.IsLetter(c) || Char.IsUpper(c))
            {
                return null;
            }

            word = word.Remove(index, 1);
            c = Char.ToUpper(c);
            word = word.Insert(index, c.ToString());
            Log.Debug("returning " + word);
            return word;
        }
Esempio n. 27
0
 private String convertImageURL(String url)
 {
     int index = url.LastIndexOf("/");
     url = url.Insert(index, "/d");
     return url;        
 }
Esempio n. 28
0
        //This function parses a string of numbers and operations and treats it as a single level of order of operations (no nested parentheses)
        //-It essentially just performs the multiplication/divided operations on the first pass condensing the string as it goes, and on the second pass it does addition/subtraction
        private static String solveString(String equation)
        {
            Stack<double> total = new Stack<double>();
            char[] symbol = { '+', '-', '*', '/' };
            char[] plusOrMinus = { '+', '-' };
            char[] timesOrDivide = { '*', '/' };
            char[] charEquation = equation.ToCharArray();
            for (int i = 0; i < charEquation.Length; i++)
            {
                if (equation.IndexOfAny(symbol, i, 1) > -1 && charEquation.GetValue(i + 1).Equals('-'))
                {
                    charEquation.SetValue('!', i + 1);
                }
            }
            equation = "";
            foreach (char i in charEquation)
            {
                equation += Convert.ToString(i);
            }
            equation = "0+" + equation + "+0";
            int num1_Start = 0;
            int num1_End = 0;
            int num2_Start = 0;
            int num2_End = 0;
            String num1_str = "";
            String num2_str = "";
            String answer = "";
            double num1 = 0;
            double num2 = 0;
            int pos = 0; //Position of last + or - operator before current * or / operator
            double numBuffer = 0;

            while (equation.IndexOfAny(timesOrDivide) > -1)
            {
                pos = LastIndexOfAny(equation, plusOrMinus, 0, equation.IndexOfAny(timesOrDivide));
                num1_Start = pos + 1;
                num1_End = equation.IndexOfAny(timesOrDivide) - 1;
                num2_Start = equation.IndexOfAny(timesOrDivide) + 1;
                num2_End = equation.IndexOfAny(symbol, equation.IndexOfAny(timesOrDivide) + 1) - 1;

                num1_str = equation.Substring(num1_Start, num1_End - num1_Start + 1);
                num2_str = equation.Substring(num2_Start, num2_End - num2_Start + 1);
                if (num1_str.IndexOf("!") > -1)
                {
                    num1_str = num1_str.Replace("!", "-");
                }
                if (num2_str.IndexOf("!") > -1)
                {
                    num2_str = num2_str.Replace("!", "-");
                }
                num1 = Convert.ToDouble(num1_str);
                num2 = Convert.ToDouble(num2_str);

                if (equation.Substring(equation.IndexOfAny(timesOrDivide), 1) == "*")
                {
                    answer = Convert.ToString(num1 * num2);
                }
                else
                {
                    answer = Convert.ToString(num1 / num2);
                }
                if (answer.IndexOf("-") > -1)
                {
                    answer = answer.Replace("-", "!");
                }
                if (answer.IndexOf("-") > -1)
                {
                    answer = answer.Replace("-", "!");
                }
                equation = equation.Substring(0, num1_Start) + answer + equation.Substring(num2_End + 1, equation.Length - num2_End - 1);
            }
            equation = equation.Insert(0, "+");
            while (equation.IndexOfAny(plusOrMinus) > -1)
            {
                if (equation.Substring(1, 1).Equals("!"))
                {
                    if (equation.Substring(0, 1).Equals("+"))
                    {
                        total.Push(Convert.ToDouble("-" + equation.Substring(2, equation.IndexOfAny(plusOrMinus, 1) - 2)));
                        equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1));
                    }
                    else
                    {
                        total.Push(Convert.ToDouble(equation.Substring(2, equation.IndexOfAny(plusOrMinus, 2) - 2)));
                        equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1));
                    }
                }
                else if (equation.Length > 2)
                {
                    if (equation.Substring(0, 1).Equals("+"))
                    {
                        total.Push(Convert.ToDouble(equation.Substring(1, equation.IndexOfAny(plusOrMinus, 1) - 1)));
                        equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1));
                    }
                    else
                    {
                        total.Push(Convert.ToDouble("-" + equation.Substring(1, equation.IndexOfAny(plusOrMinus, 1) - 1)));
                        equation = equation.Remove(0, equation.IndexOfAny(plusOrMinus, 1));
                    }
                }
                else
                {
                    equation = "";
                }

            }
            while (total.Count > 0)
            {
                numBuffer += total.Pop();
            }
            return Convert.ToString(numBuffer);
        }
        protected String GetAvailableTitle(String requestTitle, ICloudDirectoryEntry parentFolderID, Func<string, ICloudDirectoryEntry, bool> isExist)
        {
            if (!isExist(requestTitle, parentFolderID)) return requestTitle;

            var re = new Regex(@"( \(((?<index>[0-9])+)\)(\.[^\.]*)?)$");
            var match = re.Match(requestTitle);

            if (!match.Success)
            {
                var insertIndex = requestTitle.Length;
                if (requestTitle.LastIndexOf(".") != -1)
                {
                    insertIndex = requestTitle.LastIndexOf(".");
                }
                requestTitle = requestTitle.Insert(insertIndex, " (1)");
            }

            while (isExist(requestTitle, parentFolderID))
            {
                requestTitle = re.Replace(requestTitle, MatchEvaluator);
            }
            return requestTitle;
        }
 public Int32 KelownaPayMonthInfo(String yearMonth)
 {
     DateTime dt = DateTime.Parse(yearMonth.Insert(4, "-").Insert(7, "-01")).AddMonths(1);
     String yearMonthD = String.Concat(dt.Year.ToString(), dt.Month.ToString());
     using (TransactionScope scope = TransactionScopeFactory.Create(TransactionScopeOption.Required))
     {
         StringBuilder sql = new StringBuilder();
         WhereSqlClauseBuilder builder = new WhereSqlClauseBuilder();
         foreach (PersonBaseFeeMonthInfo PersonBaseFeeMonthInfo in PersonBaseFeeInfoAdapter.Instance.GetPersonBaseFeeInfoList(PersonBaseFeeTarget.PersonBaseFeeMonth, yearMonth))
         {
             PersonBaseFeeMonthInfo.YearMonth = yearMonthD;
             sql.Append(ORMapping.GetInsertSql(PersonBaseFeeMonthInfo, BuilderEx.TSqlBuilderInstance));
             sql.Append(";");
         }
         //工资月表
         builder.AppendItem(PayMonthInfoDBConst.YearMonth, yearMonth);
         foreach (PayMonthInfo PayMonthInfo in PayMonthInfoAdapter.Instance.GetPayMonthInfoList(builder))
         {
             PayMonthInfo.YearMonth = yearMonthD;
             sql.Append(ORMapping.GetInsertSql(PayMonthInfo, BuilderEx.TSqlBuilderInstance));
             sql.Append(";");
         }
         //人员基本工资项目部门分摊月表
         builder.Clear();
         builder.AppendItem(PersonBaseFeeDepartmentProjectMonthInfoDBConst.YearMonth, yearMonth);
         foreach (PersonBaseFeeDepartmentProjectMonthInfo personFeeDepartmentProjectMonthInfo in PersonBaseFeeDepartmentProjectInfoAdapter.Instance.GetPersonBaseFeeDepartmentProjectInfoList(yearMonth, builder))
         {
             personFeeDepartmentProjectMonthInfo.YearMonth = yearMonthD;
             sql.Append(ORMapping.GetInsertSql(personFeeDepartmentProjectMonthInfo, BuilderEx.TSqlBuilderInstance));
             sql.Append(";");
         }
         //工资项目月表
         builder.Clear();
         builder.AppendItem(FeeMonthInfoDBConst.YearMonth, yearMonth);
         foreach (FeeMonthInfo feeMonthInfo in FeeInfoAdapter.Instance.GetFeeInfoList(yearMonth, builder))
         {
             feeMonthInfo.YearMonth = yearMonthD;
             sql.Append(ORMapping.GetInsertSql(feeMonthInfo, BuilderEx.TSqlBuilderInstance));
             sql.Append(";");
         }
         //税率月表
         builder.Clear();
         builder.AppendItem(TaxMonthInfoDBConst.YearMonth, yearMonth);
         foreach (TaxMonthInfo taxMonthInfo in TaxInfoAdapter.Instance.GetTaxInfoList(yearMonth, builder))
         {
             taxMonthInfo.YearMonth = yearMonthD;
             sql.Append(ORMapping.GetInsertSql(taxMonthInfo, BuilderEx.TSqlBuilderInstance));
             sql.Append(";");
         }
         int result = _DataHelper.ExecuteSql(sql.ToString());
         scope.Complete();
         return result;
     }
 }
        /// <summary>
        /// Returns the equation text with literals appended "M" to indicate a Decimal literal
        /// </summary>
        public static String ConvertLiteralsToDecimal( String strEquationTxt )
        {
            char[]	caNumbers	= "0123456789".ToCharArray();
            int	iPos	= strEquationTxt.IndexOfAny( caNumbers );
            while( iPos >= 0 )
            {
                // if found number at the end of equation, append "M" to it
                // and finish
                if( iPos.Equals( strEquationTxt.Length - 1 ) )
                {
                    strEquationTxt	= strEquationTxt + "M";
                    break;
                }

                // if found space or operators after a number, append "M" to it
                if( strEquationTxt.Substring( iPos + 1, 1 ).Equals( " " ) )
                {
                    // try to detect if this number is a variable name (has closing
                    // brackets) or a literal (is outside of any brackets)
                    int	iPosClosing	= strEquationTxt.IndexOf( "]", iPos + 1 );
                    if( iPosClosing < 0 )
                        iPosClosing	= strEquationTxt.Length;
                    int	iPosOpening	= strEquationTxt.IndexOf( "[", iPos + 1 );
                    if( iPosOpening < 0 )
                        iPosOpening	= strEquationTxt.Length;
                    // if closing bracket is preceeded by an opening bracket
                    // or there is no closing bracket, then this is a literal
                    if( iPosClosing >= iPosOpening )
                        strEquationTxt	= strEquationTxt.Insert( iPos + 1, "M" );
                }

                foreach( char caOperator in caOPERATOR_LIST )
                {
                    if( strEquationTxt.Substring( iPos + 1, 1 ).Equals( caOperator ) )
                    {
                        strEquationTxt	= strEquationTxt.Insert( iPos + 1, "M" );
                        break;
                    }
                }

                // search for the next number
                iPos	= strEquationTxt.IndexOfAny( caNumbers, iPos + 1 );
            }

            return strEquationTxt;
        }
        // Escape '&' in XML if it hasn't been
        internal String EscapeAmpersand(String url)
        {
            const char ampersand = '&';
            const String ampEscaped = "amp;";

            if (url == null)
            {
                return null;
            }

            int ampPos = url.IndexOf(ampersand);
            while (ampPos != -1)
            {
                if (url.Length - ampPos <= ampEscaped.Length ||
                    url.Substring(ampPos + 1, ampEscaped.Length) != ampEscaped)
                {
                    url = url.Insert(ampPos + 1, ampEscaped);
                }
                ampPos = url.IndexOf(ampersand, ampPos + ampEscaped.Length + 1);
            }

            return url;
        }
        // Calculates the query string to output for the postback. Other
        // writers may override.

        internal String ReplaceFormsCookieWithVariable(String queryString)
        {
            String formsAuthCookieName = FormsAuthentication.FormsCookieName;
            if(!String.IsNullOrEmpty(formsAuthCookieName))
            {
                int index = queryString.IndexOf(formsAuthCookieName + "=", StringComparison.Ordinal);
                if(index != -1)
                {
                    int valueStart = index + formsAuthCookieName.Length + 1;
                    int valueEnd = queryString.IndexOf('&', valueStart);
                    if(valueStart < queryString.Length)
                    {
                        int length = ((valueEnd != -1) ? valueEnd : queryString.Length) - valueStart;
                        queryString = queryString.Remove(valueStart, length);
                        queryString = queryString.Insert(valueStart, "$(" + MapClientIDToShortName("__facn", false) + ")");
                    }
                }
            }
            return queryString;
        }
        public static string AddMarkOfTheWeb(String html, String webUrl)
        {
            Regex docType = new Regex("<!DOCTYPE[^>]*>");
            Regex savedFrom = new Regex("<!-- saved from url.* -->");

            //remove the existing savedFrom
            Match m = savedFrom.Match(html);
            if (m.Success)
            {
                html = html.Remove(m.Index, m.Length);
            }

            int markOffset = 0;
            m = docType.Match(html);
            if (m.Success && html.Substring(0, m.Index).Trim() == String.Empty)
            {
                markOffset = m.Index + m.Length;
            }

            String markOfTheWeb = UrlHelper.GetSavedFromString(webUrl);
            html = html.Insert(markOffset, markOfTheWeb);

            if (markOffset == 0)
            {
                //prepend a default docType declaration (fixes bug 487389)
                html = DEFAULT_MOTW_DOCTYPE + "\r\n" + html;
            }

            return html;
        }