/// <summary>
        /// 获取指定字符串的第一行内容,其方法是查找\r或\n的位置
        /// 如果只有一个,则直接依据其索引从0开始截取子串即可
        /// 如果找到两个,则取最小的那个作为索此截取子串
        /// 如果没有找到,返回整个字串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String getFirstLineOfString(String str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return null;
            }

            int indexOfR = str.IndexOf("\r");
            int indexOfN = str.IndexOf("\n");
            if (indexOfN == -1 && indexOfR == -1)
            {
                return str;
            }

            if (indexOfN != -1 && indexOfR != -1)
            {
                int length = (indexOfN < indexOfR ? indexOfR : indexOfN) - 1;
                return str.Substring(0, length);

            }

            if (indexOfN != -1 && indexOfR == -1)
            {
                return str.Substring(0, indexOfN - 1);

            }

            if (indexOfN == -1 && indexOfR != -1)
            {
                return str.Substring(0, indexOfR - 1);

            }
            return null;
        }
		protected override void AddMessage(String message)
		{
			if( message.IndexOf("AFC") == -1 && message.IndexOf("NFC") == -1 )
			{
				base.AddMessage (message);
			}
		}
Example #3
0
 /**
  *
  * @param decl a string from header or meta tag to detect encoding
  * @return encoding String
  */
 public static String GetDeclaredEncoding(String decl)
 {
     if (decl == null)
         return null;
     int idx = decl.IndexOf("encoding");
     if (idx < 0)
         return null;
     int idx1 = decl.IndexOf('"', idx);
     int idx2 = decl.IndexOf('\'', idx);
     if (idx1 == idx2)
         return null;
     if (idx1 < 0 && idx2 > 0 || idx2 > 0 && idx2 < idx1) {
         int idx3 = decl.IndexOf('\'', idx2 + 1);
         if (idx3 < 0)
             return null;
         return decl.Substring(idx2 + 1, idx3 - (idx2 + 1));
     }
     if (idx2 < 0 && idx1 > 0 || idx1 > 0 && idx1 < idx2) {
         int idx3 = decl.IndexOf('"', idx1 + 1);
         if (idx3 < 0)
             return null;
         return decl.Substring(idx1 + 1, idx3 - (idx1 + 1));
     }
     return null;
 }
Example #4
0
 public ContentType(String mime)
 {
     // this allows us to correctly process ctypes like "text/html; charset=utf-8"
     // todo. investigate the MIME spec and implement this thouroughly
     var sliceAt = mime.IndexOf(";") == -1 ? mime.Length : mime.IndexOf(";");
     Mime = mime.Substring(0, sliceAt); ;
 }
Example #5
0
 private void parse(String message)
 {
     int i = -1;
     int j = message.IndexOf(" :");
     String trailing = "";
     if (message.StartsWith(":"))
     {
         i = message.IndexOf(" ");
         prefix = message.Substring(1, i - 1);
     }
     if (j >= 0)
     {
         trailing = message.Substring(j + 2);
     }
     else
     {
         j = message.Length;
     }
     var commandAndParameters = message.Substring(i + 1, j - i - 1).Split(' ');
     command = commandAndParameters.First();
     if (commandAndParameters.Length > 1)
         parameters = commandAndParameters.Skip(1).ToArray();
     if (!String.IsNullOrEmpty(trailing))
     {
         parameters = parameters.Concat(new string[] { trailing }).ToArray();
     }
 }
        public override bool DoLogin()
        {
            Logout(true);
            String homePage = "http://www.myspace.com";
            String loginUrl = "http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken=";
            try
            {
                htmlResponse = httpUtils.GetHttpResponse(homePage, false);
                reffer = homePage;
                String tempStr = "MyToken=";
                int pos = htmlResponse.IndexOf(tempStr);
                myToken = htmlResponse.Substring(pos + tempStr.Length);
                myToken = myToken.Substring(0, myToken.IndexOf("\""));
                loginUrl += myToken;
                postString = "email=" + UserId + "&password=" + HttpUtility.UrlEncode(Password) + "&Submit22_x=33&Submit22_y=10";
                htmlResponse = httpUtils.GetHttpResponse(loginUrl, false, postString, reffer);
                if (htmlResponse.IndexOf("<input type=\"text\" name=\"email\"") == -1)
                {
                    // Begin Outer If
                    if (htmlResponse.IndexOf("Member Login") == -1)
                    {
                        // Begin 1st inner if
                        if (htmlResponse.IndexOf("Skip this Advertisement") > 1)
                        {
                            htmlResponse = htmlResponse.Substring(0, htmlResponse.IndexOf("Skip this Advertisement"));
                            tempStr = "<a href=\"";
                            String urlToFetch = htmlResponse.Substring(htmlResponse.IndexOf(tempStr) + tempStr.Length);
                            urlToFetch = urlToFetch.Substring(0, urlToFetch.IndexOf("\""));
                            htmlResponse = httpUtils.GetHttpResponse(urlToFetch, false, "", loginUrl);

                        }
                        //End 1st inner if.

                        // Begin of 2nd inner if
                        if (htmlResponse.IndexOf("You have\n <span><a href=\"") == -1)
                        {
                            htmlResponse = httpUtils.GetHttpResponse("http://home.myspace.com/index.cfm?fuseaction=user", false);

                        }
                        // End of 2nd inner if
                        tempStr = "<span><a href=\"";
                        String fPage = htmlResponse.Substring(htmlResponse.IndexOf(tempStr) + tempStr.Length);
                        fPage = fPage.Substring(0, fPage.IndexOf("\""));

                        IsLoggedIn = true;
                    }
                }
                else
                {
                    IsLoggedIn = false;
                }
            }
            //Outer if close
            // End of outer if
            catch (Exception)
            {
                IsLoggedIn = false;
            }
            return IsLoggedIn;
        }
        public static DateTime W3CDateTimeToDateTime(String w3cDateTime)
        {
            DateTime dt;

            if (w3cDateTime.IndexOf('T') != -1) {
                if (w3cDateTime.IndexOf('Z') != -1) {
                    dt = DateTime.ParseExact(w3cDateTime,
                                             W3CDateTimePatternsUTC,
                                             DateTimeFormatInfo.InvariantInfo,
                                             DateTimeStyles.NoCurrentDateDefault);
                    dt = dt.ToLocalTime();
                } else {
                    dt = DateTime.ParseExact(w3cDateTime,
                                             W3CDateTimePatternsTZ,
                                             DateTimeFormatInfo.InvariantInfo,
                                             DateTimeStyles.NoCurrentDateDefault);
                }
            } else {
                dt = DateTime.ParseExact(w3cDateTime,
                                         W3CDateTimePatternsBasic,
                                         DateTimeFormatInfo.InvariantInfo,
                                         DateTimeStyles.NoCurrentDateDefault);
                dt = dt.ToLocalTime();
            }
            return dt;
        }
        public Wall(String Name, String ModelName, Model SentModel, Vector3 ModelPosition, Vector3 ModelRotation, GraphicsDevice device, Boolean moveable, Boolean pickup, float bounciness, Boolean levitating, String ActionInfo)
            : base(Name, ModelName, SentModel, ModelPosition, ModelRotation, device, moveable, pickup, bounciness, levitating)
        {
            String Dimensions = ActionInfo.Substring(ActionInfo.IndexOf("Wall{") + 5, ActionInfo.IndexOf("}") - ActionInfo.IndexOf("Wall{") - 5);
            this.Length = float.Parse(Dimensions.Substring(Dimensions.IndexOf("Length:") + 7, Dimensions.IndexOf(';', Dimensions.IndexOf("Length:")) - Dimensions.IndexOf("Length:") - 7));
            this.Width = float.Parse(Dimensions.Substring(Dimensions.IndexOf("Width:") + 6, Dimensions.IndexOf(';', Dimensions.IndexOf("Width:")) - Dimensions.IndexOf("Width:") - 6));
            this.Height = float.Parse(Dimensions.Substring(Dimensions.IndexOf("Height:") + 7, Dimensions.IndexOf(';', Dimensions.IndexOf("Height:")) - Dimensions.IndexOf("Height:") - 7));
            int storeSpot = 0;
            try
            {
                wallColor = new Color(
                int.Parse(Dimensions.Substring(storeSpot = (Dimensions.IndexOf("R:", Dimensions.IndexOf("Color(")) + 2), Dimensions.IndexOf(",", Dimensions.IndexOf("R:", Dimensions.IndexOf("Color("))) - storeSpot)),
                int.Parse(Dimensions.Substring(storeSpot = (Dimensions.IndexOf("G:", Dimensions.IndexOf("Color(")) + 2), Dimensions.IndexOf(",", Dimensions.IndexOf("G:", Dimensions.IndexOf("Color("))) - storeSpot)),
                int.Parse(Dimensions.Substring(storeSpot = (Dimensions.IndexOf("B:", Dimensions.IndexOf("Color(")) + 2), Dimensions.IndexOf(",", Dimensions.IndexOf("B:", Dimensions.IndexOf("Color("))) - storeSpot)),
                int.Parse(Dimensions.Substring(storeSpot = (Dimensions.IndexOf("A:", Dimensions.IndexOf("Color(")) + 2), Dimensions.IndexOf(")", Dimensions.IndexOf("A:", Dimensions.IndexOf("Color("))) - storeSpot)));
            }
            catch (Exception e) { }

            //VerticesMasterList.Add(new List<VertexPositionNormalColor>(0));

            this.LastPosition = this.Position;
            this.LastRotation = this.modelRotation;
            this.CalculateBoundingBox();
            this.CalculateBox();

            //Walls should not be moveable or pickupable by default - LIES!!!!
            /*
            this.Moveable = false;
            this.PickUpable = false;
            this.IsLevitating = true;
             */
        }
Example #9
0
        public Pascal(String operation, String filePath, String flags)
        {
            try{
                bool intermediate = flags.IndexOf('i') > 1;
                bool xref = flags.IndexOf('x') > 1;
                source = new Source(new StreamReader(filePath));
                source.AddMessageListener(new SourceMessageListener());

                parser = FrontEndFactory.CreateParser("pascal","top-down",source);
                parser.AddMessageListener(new ParserMessageListener());

                backend = BackendFactory.CreateBackend("compile");
                backend.AddMessageListener(new BackendMessageListener());

                parser.Parse();
                source.close();

                intermediateCode = parser.IntermediateCode;
                symbolTable = Parser.SymbolTable;

                backend.Process(intermediateCode,symbolTable);
            }
            catch(Exception ex){
                Console.WriteLine ("Internal translation error");
                Console.WriteLine (ex.StackTrace);
            }
        }
Example #10
0
        IEnumerable<City> GetCitiesFromPageHtml(String html)
        {
            var startRegionMarker = "<select id=\"filterAddressTown\"";
            var endRegionMarker = "</select>";

            var startIndex = html.IndexOf(startRegionMarker);
            var endIndex = html.IndexOf(endRegionMarker, startIndex) + endRegionMarker.Length;

            var citiesXml = html.Substring(startIndex, endIndex - startIndex);

            var cities = new List<City>();

            var parsed = XDocument.Parse(citiesXml);
            foreach (var elem in parsed.Elements().First().Elements())
            { 
                var city = new City()
                {
                    Id = elem.Attribute("value").Value.Trim(),
                    Name = elem.Value.Trim()
                };

                if (city.Id == "0")
                    continue;

                cities.Add(city);
            }

            return cities;
        }
Example #11
0
        IEnumerable<Shop> GetShops(String html, IEnumerable<City> cities)
        {
            var start = "var myLoadYMapsItemsVar=";
            var end = "};";
            var startIndex = html.IndexOf(start) + start.Length;
            var endIndex = html.IndexOf(end, startIndex) + 1;

            var shopsJsonText = html.Substring(startIndex, endIndex - startIndex);
            var shopsJson = JsonConvert.DeserializeObject<ShopsJson>(shopsJsonText);

            var shops = new List<Shop>();
            var citiesDict = cities.ToDictionary(c => c.Id);
            foreach (var shopJson in shopsJson.items)
            {
                String shirota, dolgota;
                ParseHelper.GetCoordinates(shopJson.gps, out shirota, out dolgota);
                
                var shop = new Shop() 
                {
                    Address = shopJson.name,
                    Dolgota = dolgota,
                    Shirota = shirota,
                    City = citiesDict[shopJson.per_id].Name,
                    TimeWork = shopJson.time
                };

                shops.Add(shop);
            }

            return shops;
        }
Example #12
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="ob"></param>
 /// <param name="fieldPath"></param>
 /// <param name="fieldValue"></param>
 public static void modifyRecursively(Object ob, String fieldPath, String fieldValue)
 {
     if (ob == null)
     {
         return;
     }
     if (!fieldPath.Contains("."))
     {
         modifyValueOfFieldAccordingToTable(ob, fieldPath, fieldValue);
     }
     else
     {
         String prefix = fieldPath.Substring(0, fieldPath.IndexOf('.'));
         Object o;
         o = ob.GetType().GetProperty(prefix, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
         if (o != null)
         {
             PropertyInfo myProp = (PropertyInfo)o;
             Object subObject = myProp.GetValue(ob, null);
             String toPass = fieldPath.Substring(fieldPath.IndexOf('.') + 1);
             modifyRecursively(subObject, toPass, fieldValue);
         }
         else
         {
             o = ob.GetType().GetField(prefix, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
             FieldInfo myField = (FieldInfo)o;
             Object subObject = myField.GetValue(ob);
             String toPass = fieldPath.Substring(fieldPath.IndexOf('.') + 1);
             modifyRecursively(subObject, toPass, fieldValue);
         }
     }
 }
 /// <summary>
 /// Constructor with UNC
 /// </summary>
 /// <param name="path">The share name - UNC</param>
 public NetworkShare( String path )
 {
     String hostName = "";
     // check if the UNC is valid
     unc = (String) path.Clone();
     if( path.StartsWith( @"\\" ) )
     {
         path = path.Remove( 0, 2 );
         int i = path.IndexOf( @"\" );
         if( i < 0 )
         {
             goto _abort;
         }
         hostName = path.Substring( 0, path.IndexOf( @"\" ) );
         path = path.Remove( 0, i );
         if( path == null || path.Length < 1 )
         {
             goto _abort;
         }
         // remove the first "\"
         remotePath = (String) path.Remove( 0, 1 );
         if( remotePath == null || remotePath.Length < 1 )
         {
             goto _abort;
         }
         goto _ok;
     }
     _abort:
     throw new Exception( "Invalid UNC path: " + unc );
     _ok:
     {
         host = new NetworkHost( hostName, 0 /* dummy */ );
     }
 }
Example #14
0
 private String imgtext(String imgs)
 {
     String img = "";
     int ps = imgs.IndexOf("<IMG");
     if (ps >= 0)
     {
         imgs = imgs.Substring(ps);
         ps = imgs.IndexOf(">");
         if (ps >= 0)
         {
             img = imgs.Substring(0, ps + 1);
             ps = img.IndexOf("src=");
             img = img.Substring(ps + 5);
             ps = img.IndexOf(" ");
             if (ps >= 0)
             {
                 img = img.Substring(0, ps - 1);
             }
         }
     }
     if (img.Length > 0)
         if (!img.ToLower().StartsWith("http://"))
         {
             JpSite site = new JpSite();
             img = "http://" + site.host + img;
         }
     return img;
 }
Example #15
0
        public WhoLine(IrcLine baseLine)
            : base(baseLine)
        {
            if(baseLine.Numeric != 352)
                throw new ArgumentOutOfRangeException("baseLine", "RPL_WHOREPLY 352 expected");
            if(Parameters.Length < 8)
                throw new ArgumentOutOfRangeException("baseLine", "Need a minimum of 8 parameters");

            UserValue = new UserInfo(Parameters[5], Parameters[2], Parameters[3], Client);
            List<Mode> modes = new List<Mode>();
            int i = 1;

            IsAwayValue = Parameters[6][0] == 'G';
            IsOperValue = Parameters[6][i] == '*';

            if(IsOper)
                i++;

            for(; i < Parameters[6].Length; i++)
            {
                if(Client.Standard.UserPrefixFlags.ContainsKey(Parameters[6][i]))
                {
                    modes.Add(new Mode(Client.Standard.UserPrefixFlags[Parameters[6][i]], FlagArt.Set, User.NickName));
                }
            }

            ModesValue = modes.ToArray();

            RealNameValue = Parameters[7];

            if(!int.TryParse(RealNameValue.Substring(1, RealNameValue.IndexOf(" ")), out HopCountValue))
                throw new ArgumentOutOfRangeException("baseLine", "Invalid hop count, integer expected");

            RealNameValue = RealNameValue.Substring(RealNameValue.IndexOf(" ") + 1);
        }
 public override bool DoLogin()
 {
     Logout(true);
     String loginUrl = "https://www.linkedin.com/secure/login";
     try
     {
         htmlResponse = httpUtils.GetHttpResponse(loginUrl, true);
         this.jsessionid = htmlResponse.Substring(htmlResponse.IndexOf("JSESSIONID=") + "JSESSIONID=".Length);
         this.jsessionid = this.jsessionid.Substring(0, this.jsessionid.IndexOf(";"));
         postString = "session_key=" + UserId + "&session_password=" + HttpUtility.UrlEncode(Password) + "&session_login=Sign In&session_login=&session_rikey=invalid key&session_login.x=0&session_login.y=0";
         reffer = loginUrl;
         htmlResponse = httpUtils.GetHttpResponse(loginUrl, true, postString, reffer);
         if (htmlResponse.IndexOf("<input type=\"text\" name=\"session_key\"") == -1)
         {
             IsLoggedIn = true;
             String homePage = htmlResponse.Substring(htmlResponse.IndexOf("window.location.replace('") + "window.location.replace('".Length);
             homePage = homePage.Substring(0, homePage.IndexOf("'"));
             htmlResponse = httpUtils.GetHttpResponse(homePage, true);
         }
         else
         {
             IsLoggedIn = false;
         }
     }
     catch (Exception)
     {
         Logout();
         IsLoggedIn = false;
     }
     return IsLoggedIn;
 }
Example #17
0
        public void Work()
        {
            while (_stream.CanRead)
            {
                try
                {
                    int bytes_read = _stream.Read(bytemessage, 0, bytemessage.Length);
                    client_message += Encoding.UTF8.GetString(bytemessage, 0, bytes_read);

                    if (client_message.Contains('\n'))
                    {
                        string tmp = client_message.Substring(0, client_message.IndexOf('\n'));
                        client_message = client_message.Remove(0, client_message.IndexOf('\n') + 1);

                        if (dialogue.interpretMessage(tmp))
                        {
                            dialogue = dialogue.getNextDialogue();
                        }

                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception in Work:"+e.Message);
                    return;
                }

            }
        }
Example #18
0
        private void GetPic()
        {
            htmlText = ghtml.html(address);

            if (htmlText.IndexOf(@"Фото:", 19) != -1)
            {

                text = htmlText.Substring(htmlText.IndexOf(@"Фото:"));

                Int32 startP = text.IndexOf("SRC", 0);
                if (startP < 300 && startP != -1)
                {
                    startP += 5;

                    //День рождения
                    text = text.Substring(text.IndexOf("Дата рождения"));
                    Int32 startD = text.IndexOf("ms-formbody", 70);
                    tBirthDay.Add(text.Substring(startD + 13, 10));

                    //Дата прихода в Элком+
                    text = text.Substring(text.IndexOf("Дата прихода"));
                    startD = text.IndexOf("ms-formbody", 70);
                    tStartDay.Add(text.Substring(startD + 13, 10));

                    tBirthID.Add(idTemp);

                }

            }
        }
Example #19
0
        private void getFlightAbout(String html)
        {
            int iTableStart = html.IndexOf("stage flights", 0);
            int iTableEnd = html.IndexOf("</ul>", iTableStart);
            string strtable = html.Substring(iTableStart, iTableEnd - iTableStart + 5);
            while (true)
            {
                RS_FlightRoute flightAbout = new RS_FlightRoute();
                flightAbout.FlightType = "直达";
                RS_FlightDetail flightDetail = new RS_FlightDetail();
                int startLi = strtable.IndexOf("<li", 0);
                int endLi = strtable.IndexOf("</li", startLi);

                int flightStart = strtable.IndexOf("<p class=\"n\">", 0);
                int flightEnd = strtable.IndexOf("</p>", flightStart);
                String flight = strtable.Substring(flightStart + 13, flightEnd - flightStart - 13);
                for (int i = 0; i < flight.Length; i++)
                {
                    if (flight[i] >= 'A' && flight[i] <= 'Z')
                    {
                        String agency = flight.Substring(0, i);
                        String flightNum = flight.Substring(i);
                        flightDetail.Airline = agency.Trim();
                        flightDetail.FlightNum = flightNum.Trim();
                        break;
                    }
                }
                int timeStart = strtable.IndexOf("<p class=\"i\">", flightEnd);
                int timeEnd = strtable.IndexOf("<br", timeStart);
                String time = strtable.Substring(timeStart + 13, timeEnd - timeStart - 13);
                String TakeOffTime = time.Substring(0, time.IndexOf("-") - 1);
                String ArriveTime = time.Substring(time.IndexOf("-") + 2);
                flightDetail.TakeOffTime = TakeOffTime.Trim(); ;
                flightDetail.ArriveTime = ArriveTime.Trim();
                int portEnd = strtable.IndexOf("</p>", timeEnd);
                String port = strtable.Substring(timeEnd + 6, portEnd - timeEnd - 6).Trim();
                String DPort = port.Substring(0, port.IndexOf("-") - 1);
                String APort = port.Substring(port.IndexOf("-") + 2);
                if (APort.IndexOf("<span") > 0)
                {
                    APort = APort.Substring(0, APort.IndexOf("<span") - 1) + "(经停)";
                }
                flightDetail.DPort = DPort.Trim();
                flightDetail.APort = APort.Trim();

                String agencyUrl = "http://touch.qunar.com/flightDetail.jsp?flightType=oneWay&startCity=" + startCity + "&destCity=" + destCity + "&startDate=" + startDate + "&code=" + flightDetail.FlightNum + "&minPrice=&bd_source=qunar";
                String agencyHtml = getWebHtml(agencyUrl);
                int priceStart = agencyHtml.IndexOf("&yen;", 0);
                int priceEnd = agencyHtml.IndexOf("</em>", priceStart);
                flightDetail.MinPrice = agencyHtml.Substring(priceStart + 5, priceEnd - priceStart - 5);
                flightDetail.AgencyList = getFlightAgency(agencyHtml);

                flightAbout.addDetail(flightDetail);
                flightInfo.addAbout(flightAbout);
                if (strtable.IndexOf("<li", portEnd) > 0)
                    strtable = strtable.Substring(strtable.IndexOf("<li", portEnd));
                else
                    break;
            }
        }
Example #20
0
        public static bool CheckParenthesis(String str)
        {
            bool result = true;

            if(str != null)
            {
                int open = 0;
                int closed = 0;

                int i = 0;
                while((i = str.IndexOf('(', i)) >= 0)
                {
                    i++;
                    open++;
                }

                i = 0;
                while((i = str.IndexOf(')', i)) >= 0)
                {
                    i++;
                    closed++;
                }

                result = (open == closed);
            }

            return result;
        }
 /// <summary>
 /// Gets whether a string matches the IRI production
 /// </summary>
 /// <param name="value">String</param>
 /// <returns></returns>
 public static bool IsIri(String value)
 {
     if (!value.Contains(':')) return false;
     String scheme = value.Substring(0, value.IndexOf(':'));
     String rest = value.Substring(value.IndexOf(':') + 1);
     if (rest.Contains("?"))
     {
         String part = rest.Substring(0, rest.IndexOf('?'));
         String queryAndFragment = rest.Substring(rest.IndexOf('?') + 1);
         String query, fragment;
         if (queryAndFragment.Contains('#'))
         {
             query = queryAndFragment.Substring(0, queryAndFragment.IndexOf('#'));
             fragment = queryAndFragment.Substring(queryAndFragment.IndexOf('#') + 1);
             return IsScheme(scheme) && IsIHierPart(part) && IsIQuery(query) && IsIFragment(fragment);
         }
         else
         {
             query = queryAndFragment;
             return IsScheme(scheme) && IsIHierPart(part) && IsIQuery(query);
         }
     } 
     else if (rest.Contains('#'))
     {
         String part = rest.Substring(0, rest.IndexOf('#'));
         String fragment = rest.Substring(rest.IndexOf('#') + 1);
         return IsScheme(scheme) && IsIHierPart(part) && IsIFragment(fragment);
     }
     else
     {
         return IsScheme(scheme) && IsIHierPart(rest);
     }
 }
Example #22
0
        void PrepareScriptCall(String expression)
        {
            int pos1 = expression.IndexOf("(");
            int pos2 = expression.IndexOf(")");
            _module = "";
            _func = expression.Substring(1, pos1 - 1);
            String[] arr = _func.Split('.');
            if (arr.Length > 2)
                throw new Exception(String.Format("Invalid expression '{0}'", expression));
            if (arr.Length == 2)
            {
                _module = arr[0];
                _func = arr[1];
            }

            String[] args = expression.Substring(pos1 + 1, pos2 - pos1 - 1).Split(',');
            _parameters = new object[args.Length];
            int i = 0;
            foreach (String arg in args)
            {                
                if (IsLazy(arg))
                    _parameters[i] = new Func<object>(() => _valueStack.Evaluate(arg));
                else
                    _parameters[i] = _valueStack.Evaluate(arg);
                i++;
            }
        }
Example #23
0
        private static readonly String staticPageSeparator = "<hr>"; //---page---

        #endregion Fields

        #region Methods

        private static String getPageSeparator( String content )
        {
            if (content.IndexOf( staticPageSeparator ) > 20) return staticPageSeparator;
            if (content.IndexOf( staticPageSeparator.ToUpper() ) > 20) return staticPageSeparator.ToUpper(); //¾ÀÕýIEµÄbug
            if (content.IndexOf( "<hr />" ) > 20) return "<hr />";
            return null;
        }
Example #24
0
        public const char OD_SET_WATCHING = 'K'; //����

        #endregion Fields

        #region Methods

        //�������յ������ݣ����ض�λ��Ϣ�б�
        public static List<Position> Analyze(String src, bool gprs)
        {
            if(src.IndexOf(HEAD) >= 0)
            {
                while(src.IndexOf(HEAD) != 0)
                    src = src.Substring(src.IndexOf(HEAD));
                if(src.IndexOf(FOOT) <= 0)
                    return null;
                List<Position> list = new List<Position>();

                String[] lines = src.Split(new string[] { HEAD }, StringSplitOptions.RemoveEmptyEntries);
                foreach(String line in lines)
                    if(line != "")
                    {
                        Position pos = null;
                        if(gprs)
                        {
                            pos = GetGPRSPos(line.Substring(0, line.Length - 1));
                        }
                        else
                        {
                            pos = GetSMSPos(line.Substring(0, line.Length - 1));
                        }
                        if(pos != null)
                            list.Add(pos);
                    }
                return list;
            }
            return null;
        }
Example #25
0
	static String process(String s){
		//analyze parens
		int bidx=s.IndexOf("(");
		while(bidx!=-1){
			int count=1,eidx=bidx+1;
			for(;count!=0;eidx++){
				if(s[eidx]=='(')count++;
				if(s[eidx]==')')count--;
			}
			s=s.Substring(0,bidx)+process(s.Substring(bidx+1,eidx-1-(bidx+1)))+s.Substring(eidx);
			bidx=s.IndexOf("(");
		}

		//calc without parens
		MatchCollection m=muldiv.Matches(s);
		while(m.Count>0){
			if(m[0].Groups[3].Value=="*")
				s=m[0].Groups[1].Value+(int.Parse(m[0].Groups[2].Value)*int.Parse(m[0].Groups[4].Value))+m[0].Groups[5].Value;
			else
				s=m[0].Groups[1].Value+(int.Parse(m[0].Groups[2].Value)/int.Parse(m[0].Groups[4].Value))+m[0].Groups[5].Value;
			m=muldiv.Matches(s);
		}

		m=addsub.Matches(s);
		while(m.Count>0){
			if(m[0].Groups[3].Value=="+")
				s=m[0].Groups[1].Value+(int.Parse(m[0].Groups[2].Value)+int.Parse(m[0].Groups[4].Value))+m[0].Groups[5].Value;
			else
				s=m[0].Groups[1].Value+(int.Parse(m[0].Groups[2].Value)-int.Parse(m[0].Groups[4].Value))+m[0].Groups[5].Value;
			m=addsub.Matches(s);
		}
		return s;
	}
        private static void validateRequestUri(String requestUri)
        {
            log.debug(requestUri, "requestUri");

            if ('/' != requestUri[0])
            {

                log.errorFormat("'/' != requestUri.charAt(0); requestUri = '{0}'", requestUri);
                throw HttpErrorHelper.forbidden403FromOriginator(typeof(FileGetRequestHandler));
            }

            if (-1 != requestUri.IndexOf("/."))
            { // UNIX hidden files

                log.errorFormat("-1 != requestUri.indexOf( \"/.\"); requestUri = '{0}'", requestUri);
                throw HttpErrorHelper.forbidden403FromOriginator(typeof(FileGetRequestHandler));

            }

            if (-1 != requestUri.IndexOf(".."))
            { // parent directory

                log.errorFormat("-1 != requestUri.indexOf( \"..\"); requestUri = '{0}'", requestUri);
                throw HttpErrorHelper.forbidden403FromOriginator(typeof(FileGetRequestHandler));

            }
		
        }
        private static ArrayList CreateSeparatedSite(String site)
        {
            if (site == null || site.Length == 0)
            {
                throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
            }
            Contract.EndContractBlock();

            ArrayList list = new ArrayList();
            int braIndex = -1;
            int ketIndex = -1;
            braIndex = site.IndexOf('[');
            if (braIndex == 0)
                ketIndex = site.IndexOf(']', braIndex+1);

            if (ketIndex != -1)
            {
                // Found an IPv6 address. Special case that
                String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1);
                list.Add(ipv6Addr);
                return list;
            }

            // Regular hostnames or IPv4 addresses
            // We dont need to do this for IPv4 addresses, but it's easier to do it anyway
            String[] separatedArray = site.Split( m_separators );
            
            for (int index = separatedArray.Length-1; index > -1; --index)
            {
                if (separatedArray[index] == null)
                {
                    throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                }
                else if (separatedArray[index].Equals( "" )) 
                {
                    if (index != separatedArray.Length-1) 
                    {
                        throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                    }
                }
                else if (separatedArray[index].Equals( "*" ))
                {
                    if (index != 0)
                    {
                        throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                    }
                    list.Add( separatedArray[index] );
                }
                else if (!AllLegalCharacters( separatedArray[index] ))
                {
                    throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                }
                else
                {
                    list.Add( separatedArray[index] );
                }
            }
            
            return list;
        }
Example #28
0
        /// <summary>
        /// Get this resource
        /// </summary>
        /// <param name="resource">
        /// A String with SubResources.
        /// If this is simply '/' then return the collection as returned by the get command.
        /// If it's a path like '/elementName' then return the element.
        /// </param>
        public IRestNode getResource(String resource)
        {
            resource = resource.TrimStart('/');
            int param = resource.IndexOf(' ');
            if (param > 0)
            {
                resource = resource.Substring(0, param);
            }
            IRestNode pNode = m_root;
            while (pNode != null && resource.Length > 0)
            {
                int index = resource.IndexOf('/');

                if (index > 0)
                {
                    // test for data
                    String test = resource.Substring(0, index);
                    int end = test.IndexOf(' ');
                    //if (end != -1)
                    //{
                    //    index = end;
                    //}
                    pNode = pNode.OnElement(resource.Substring(0, index));
                    resource = resource.Substring(index, resource.Length - index).TrimStart('/').Trim();
                }
                else
                {
                    pNode.OnElement(resource);
                    return pNode;
                }
            }
            return pNode;
        }
Example #29
0
        public Dictionary<string, string> JsonToDictionary(String input, String firstCol)
        {
            //if(input.IndexOf("{"
            //input = input.Replace('\"','');
            /*
            input = input.Substring(input.IndexOf("{" + firstCol) + 1);
            input = input.Substring(0, input.IndexOf("}"));
            */
            /*
            while (input.IndexOf('\\') >= 0)
            {
                int index = input.IndexOf('\\');
                input = input.Substring(0, index) + input.Substring(index + 1);
            }
            */

            input = input.Substring(1);
            input = input.Substring(0,input.Length-1);

            while (input.IndexOf('\"') >= 0)
            {
                int index = input.IndexOf('\"');
                input = input.Substring(0, index) + input.Substring(index + 1);
            }
            /*
            input.Replace(':', '=');
            input.Replace(',', ';');
            */
            return input.TrimEnd(',').Split(',').ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
        }
 public static Pair<int, int> Between(String str, Pair<int, int> indexes, String header, String footer)
 {
     int head = str.IndexOf(header, indexes.First);
     int foot = str.IndexOf(footer, head);
     int startIndex = head + header.Length;
     return new Pair<int, int>(startIndex, foot);
 }