private void ConnectionAgent() { while (!_connectionEnd.WaitOne(0) && !Connected) try { URL url = new URL(_OpcSection.Server.Name); _Server = new Opc.Da.Server(new OpcCom.Factory(), null); _Server.Connect(url, new ConnectData(new NetworkCredential())); _groupRead = (Subscription)_Server.CreateSubscription(_GroupReadState); _groupWrite = (Subscription)_Server.CreateSubscription(_GroupWriteState); for (int i = 0; i < _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags.Count; i++) { _Items[i] = new Opc.Da.Item(); //_Items[i].ItemName = String.Format("{0}{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _Items[i].ItemName = _OpcSection.Server.Channel + "." + _OpcSection.Server.Device + "." + _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name; //string itmNam = String.Format("{0}]{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _logger.LogInfo(/*Mtd*/ ": recognized element " + _Items[i].ItemName); } _Items = _groupRead.AddItems(_Items); _groupRead.DataChanged += new DataChangedEventHandler(Group_DataChanged); } catch (Exception ex) { _logger.LogError(ex); } }
public static void TestConnection (string connection) { URL url = new URL(connection); Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), null); server.Connect(url, new ConnectData(new NetworkCredential())); }
public void TestURL() { URL file = new URL("http://www.google.com/"); URLTransform format = new URLTransform(); String value = format.write(file); URL copy = format.read(value); AssertEquals(file, copy); }
public TVSeriesEpisodesPage(string html, URL request, URL response, MovieId id) : base(html, request, response, id) { this.SeasonNumber = new ParsedInfo<int>(html, parseSeason); this.Episodes = new ParsedCollection<EpisodeInfo>(parseEpisodes(html)); this.episodePages = new Dictionary<int, TVEpisodeMainPage>(); }
internal FileNodeSocketProxy(URL url) { container = new ServiceContainer(); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(url.Host), url.Port); pool = new SocketPool(container, endPoint); chunkCache = new Cache<string, byte[]>(60000); //one minute }
public FileNodeSocketProxy GetProxy(URL url) { cacheLock.EnterUpgradeableReadLock(); try { FileNodeSocketProxy node; cache.TryGetValue(url, out node); if (node == null) { cacheLock.EnterWriteLock(); try { node = new FileNodeSocketProxy(url); cache.Add(url, node); } finally { cacheLock.ExitWriteLock(); } return node; } return node; } finally { cacheLock.ExitUpgradeableReadLock(); } }
public override bool Allow(URL url) { foreach (var f in filters) if (!f.Allow(url)) return true; return false; }
public void Add(URL item) { lock (emptyObject) empty = false; lock (tempQueue) tempQueue.Enqueue(item); }
/// <summary> /// Initializes a new instance of the <see cref="HTMLPage"/> class. /// </summary> /// <param name="html">The html-code associated with the <see cref="HTMLPage"/>.</param> /// <param name="request">The requested url that is associated with the <see cref="HTMLPage"/>.</param> /// <param name="response">The response url that is associated with the <see cref="HTMLPage"/>.</param> public HTMLPage(string html, URL request, URL response) { this.html = html; this.request = request; this.response = response; this.BufferLevel = 0; this.buffer = null; }
public TVEpisodeMainPage(string html, URL request, URL response, MovieId id, GenreCollection genreCollection) : base(html, request, response, id, genreCollection) { AirDate = new ParsedInfo<DateTime>(html, parseDate); Episode = new ParsedInfo<int>(html, parseEpisode); Season = new ParsedInfo<int>(html, parseSeason); this.EpisodeTitle = new ParsedInfo<string>(html, parseEpisodeTitle); this.SeriesTitle = new ParsedInfo<string>(html, parseSeriesTitle); seriesID = parseSeries(html); }
public override bool Allow(URL url) { int lastPeriod = url.Address.LastIndexOf('.'); if (lastPeriod == 0) return !allow; string ext = url.Address.Substring(lastPeriod + 1).ToLower(); for (int i = 0; i < extensions.Length; i++) if (extensions[i] == ext) return allow; return !allow; }
/// <summary> /// PING指定URL是否可用 /// </summary> /// <param name="address"> /// @return </param> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static boolean pingUrl(final String address) public static bool pingUrl(string address) { try { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.net.URL url = new java.net.URL("http://" + address); URL url = new URL("http://" + address); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.net.HttpURLConnection urlConn = (java.net.HttpURLConnection) url.openConnection(); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.ConnectTimeout = 1000 * 10; // mTimeout is in seconds //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long startTime = System.currentTimeMillis(); long startTime = DateTimeHelperClass.CurrentUnixTimeMillis(); urlConn.connect(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long endTime = System.currentTimeMillis(); long endTime = DateTimeHelperClass.CurrentUnixTimeMillis(); if (urlConn.ResponseCode == HttpURLConnection.HTTP_OK) { LOGGER.info("Time (ms) : " + (endTime - startTime)); LOGGER.info("Ping to " + address + " was success"); return true; } } //JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#: //ORIGINAL LINE: catch (final java.net.MalformedURLException e1) catch (MalformedURLException e1) { Console.WriteLine(e1.ToString()); Console.Write(e1.StackTrace); } //JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#: //ORIGINAL LINE: catch (final java.io.IOException e) catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } return false; }
private bool parsePosterURL(string html, out URL url) { html = html.CutToSection("<img", ">", true); html = html.CutToSection("src=\"", "\"", true); if (html.Contains("/nopicture/")) { url = new URL(html); return false; } html = html.CutToLast("SY", CutDirection.Right, false); url = new URL(html.ToString() + "5000_.jpg"); return true; }
public MainPage(string html, URL request, URL response, MovieId id, GenreCollection genreCollection) : base(html, request, response, id) { this.Title = new ParsedInfo<string>(html, parseTitle); this.Year = new ParsedInfo<int>(html, parseYear); this.PosterURL = new ParsedInfo<URL>(html, parsePosterURL); this.IMDbRating = new ParsedInfo<Rating>(html, parseIMDBRating); this.MetacriticRating = new ParsedInfo<Rating>(html, parseMetacriticRating); this.Tagline = new ParsedInfo<string>(html, parseTagline); this.Plot = new ParsedInfo<string>(html, parsePlot); this.Runtime = new ParsedInfo<TimeSpan>(html, parseRuntime); this.Genres = new ParsedInfo<GenreSet>(html, (input) => parseGenres(input, genreCollection)); }
private static IEnumerable<URL> GetLinks(URL origin, string html) { var matches = Regex.Matches(html, "<a[^>]+"); for (int i = 0; i < matches.Count; i++) { string url = matches[i].Value; url = getUrl(url); if (url != null) { try { yield return origin.GetURLFromLink(url); } finally { /* This is only here so that try is allowed */ } } } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public MessageList paymentRequest(DirectPaymentRequest directPaymentRequest, EasypayConfig config) throws java.net.MalformedURLException public virtual MessageList paymentRequest(DirectPaymentRequest directPaymentRequest, EasypayConfig config) { URL url = new URL("https://" + config.Host); string httpRequestMethod = "POST"; string contentHash = "xxx"; string contentType = "??"; string date = ""; string path = ""; HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.RequestMethod = httpRequestMethod; urlConnection.setRequestProperty("Content-Type", contentType); // urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); urlConnection.UseCaches = false; urlConnection.DoInput = true; urlConnection.DoOutput = true; System.IO.Stream @out = new BufferedOutputStream(urlConnection.OutputStream); // writeStream(out); System.IO.Stream @in = new BufferedInputStream(urlConnection.InputStream); // readStream(in); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return new MessageList(); }
public OPCServer(string serverName) { if (String.IsNullOrEmpty(serverName)) throw new ArgumentException("Server name is invalid."); _serverURL = new URL(serverName); _serverURL.Scheme = "opcda"; _server = new Opc.Da.Server(new OpcCom.Factory(), _serverURL); try { _server.Connect(); } catch (Opc.ConnectFailedException connectionExc) { Console.WriteLine("Connection to OPC server could not be established"); Console.WriteLine(connectionExc.ToString()); } }
public static PlainURL FromModel(URL url) { return new PlainURL { URLID = url.URLID, URL = url.URL1, At = url.At, SecondsElapsed = Convert.ToInt32((DateTime.UtcNow - url.At).TotalSeconds), AtTicks = url.At.Ticks, AtString = url.At.ToShortDateString() + " " + url.At.ToShortTimeString(), Nick = url.Nick, Type = url.Type, Thumbnail = url.Thumbnail, Title = url.Title, Description = url.Description, NSFW = url.NSFW ?? false, VoteCount = url.VoteCount }; }
public bool CanAccess(URL url) { string domain = Regex.Match(url.Address, "https?://[^/]*").Value; string path = url.Address.Substring(domain.Length); if (!records.ContainsKey(domain)) records.Add(domain, LoadDomain(url, this.agent)); var agent = records[domain]; foreach (var allow in agent.Allowed) if (matchesDisallow(path, allow)) return true; foreach (var disallow in agent.Disallowed) if (matchesDisallow(path, disallow)) return false; return true; }
private SearchResult[] parseResults(string html, URL request, URL response, string search) { List<SearchResult> results = new List<SearchResult>(); string title = html.CutToTag("title", true); if (html.Contains("No results found for ")) { // Do nothing, which will return an empty result set... } else if (title == "Find - IMDb") results.AddRange(from SearchResult s in ParseTable(html) select s); else if (request != response && response.Address.StartsWith("http://www.imdb.com/title/tt")) { MovieId id; if (MovieId.TryParse(response.Address, out id)) { MainPage mp = (base.Buffer as IMDBBuffer).ReadMain(id); results.Add(new SearchResult(id, mp.Title, mp.Year, mp.MediaType, MatchType.ExactMatch)); } } return results.ToArray(); }
public override bool Allow(URL url) { return url.Domain.Equals(domain); }
/// <summary> /// Creates, configures and processes an asynchronous request to the indicated resource. /// </summary> /// <returns>Task in which the request is executed</returns> /// <param name="request">Request provided by <see cref="System.Net.Http.HttpClient"/></param> /// <param name="cancellationToken">Cancellation token.</param> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { AssertSelf(); if (request == null) { throw new ArgumentNullException(nameof(request)); } if (!request.RequestUri.IsAbsoluteUri) { throw new ArgumentException("Must represent an absolute URI", "request"); } var redirectState = new RequestRedirectionState { NewUrl = request.RequestUri, RedirectCounter = 0, Method = request.Method }; while (true) { URL java_url = new URL(EncodeUrl(redirectState.NewUrl)); URLConnection java_connection; if (UseProxy) { java_connection = java_url.OpenConnection(); } else { java_connection = java_url.OpenConnection(Java.Net.Proxy.NoProxy); } var httpsConnection = java_connection as HttpsURLConnection; if (httpsConnection != null) { IHostnameVerifier hnv = GetSSLHostnameVerifier(httpsConnection); if (hnv != null) { httpsConnection.HostnameVerifier = hnv; } } if (ConnectTimeout != TimeSpan.Zero) { java_connection.ConnectTimeout = checked ((int)ConnectTimeout.TotalMilliseconds); } if (ReadTimeout != TimeSpan.Zero) { java_connection.ReadTimeout = checked ((int)ReadTimeout.TotalMilliseconds); } HttpURLConnection httpConnection = await SetupRequestInternal(request, java_connection).ConfigureAwait(continueOnCapturedContext: false);; HttpResponseMessage response = await ProcessRequest(request, java_url, httpConnection, cancellationToken, redirectState).ConfigureAwait(continueOnCapturedContext: false);; if (response != null) { return(response); } if (redirectState.NewUrl == null) { throw new InvalidOperationException("Request redirected but no new URI specified"); } request.Method = redirectState.Method; } }
public OpcIoDevice(string options) { _url = new URL(options); var fact = new OpcCom.Factory(); _server = new Server(fact, null); }
//[Route("Edit", Name ="CreateShortURL")] public ActionResult Edit() { var longUrl = new URL(); return(View(longUrl)); }
/// <summary> /// Initializes a new instance of the <see cref="SearchTitlePage"/> class. /// </summary> /// <param name="html">The html-code associated with the <see cref="SearchTitlePage"/>.</param> /// <param name="request">The requested url that is associated with the <see cref="SearchTitlePage"/>.</param> /// <param name="response">The response url that is associated with the <see cref="SearchTitlePage"/>.</param> /// <param name="search">The string that was searched for.</param> public SearchTitlePage(string html, URL request, URL response, string search) : base(html, request, response) { this.search = search; }
protected AbstractMessageFilter(TransportMessage transport, URL uri, Resources resources) { this.transport = transport; transport.SetSession(this); }
public void CopyFrom(URL copyUrl) { Scheme = copyUrl.Scheme; User = copyUrl.User; Password = copyUrl.Password; HostName = copyUrl.HostName; }
public string FormatBanner(int VendorId, int BannerId, int BannerTypeId, string BannerName, string ImageFile, string Description, string URL, int Width, int Height, string BannerSource, string HomeDirectory, string BannerClickthroughUrl) { string strBanner = ""; string strWindow = "_new"; if (Common.Globals.GetURLType(URL) == TabType.Tab) { strWindow = "_self"; } string strURL = ""; if (BannerId != -1) { if (string.IsNullOrEmpty(BannerClickthroughUrl)) { strURL = Common.Globals.ApplicationPath + BannerClickThroughPage + "?BannerId=" + BannerId.ToString() + "&VendorId=" + VendorId.ToString() + "&PortalId=" + Globals.GetPortalSettings().PortalId; } else { strURL = BannerClickthroughUrl.ToString() + "?BannerId=" + BannerId.ToString() + "&VendorId=" + VendorId.ToString() + "&PortalId=" + Globals.GetPortalSettings().PortalId; } } else { strURL = URL; } strURL = HttpUtility.HtmlEncode(strURL); switch (BannerTypeId) { case (int)BannerType.Text: strBanner += "<a href=\"" + strURL + "\" class=\"NormalBold\" target=\"" + strWindow + "\" rel=\"nofollow\"><u>" + BannerName + "</u></a><br>"; strBanner += "<span class=\"Normal\">" + Description + "</span><br>"; if (!String.IsNullOrEmpty(ImageFile)) { URL = ImageFile; } if (URL.IndexOf("://") != -1) { URL = URL.Substring(URL.IndexOf("://") + 3); } strBanner += "<a href=\"" + strURL + "\" class=\"NormalRed\" target=\"" + strWindow + "\" rel=\"nofollow\">" + URL + "</a>"; break; case (int)BannerType.Script: strBanner += Description; break; default: if (ImageFile.IndexOf("://") == -1 && ImageFile.StartsWith("/") == false) { if (ImageFile.ToLowerInvariant().IndexOf(".swf") == -1) { strBanner += "<a href=\"" + strURL + "\" target=\"" + strWindow + "\" rel=\"nofollow\">"; switch (BannerSource) { case "L": strBanner += FormatImage(HomeDirectory + ImageFile, Width, Height, BannerName, Description); break; case "G": strBanner += FormatImage(Common.Globals.HostPath + ImageFile, Width, Height, BannerName, Description); break; } strBanner += "</a>"; } else { switch (BannerSource) { case "L": strBanner += FormatFlash(HomeDirectory + ImageFile, Width, Height); break; case "G": strBanner += FormatFlash(Common.Globals.HostPath + ImageFile, Width, Height); break; } } } else { if (ImageFile.ToLowerInvariant().IndexOf(".swf") == -1) { strBanner += "<a href=\"" + strURL + "\" target=\"" + strWindow + "\" rel=\"nofollow\">"; strBanner += FormatImage(ImageFile, Width, Height, BannerName, Description); strBanner += "</a>"; } else { strBanner += FormatFlash(ImageFile, Width, Height); } } break; } return(strBanner); }
async Task <HttpResponseMessage> DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()"); } try { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connecting"); } await httpConnection.ConnectAsync().ConfigureAwait(false); if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connected"); } } catch (Java.Net.ConnectException ex) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Connection exception {ex}"); } // Wrap it nicely in a "standard" exception so that it's compatible with HttpClientHandler throw new WebException(ex.Message, ex, WebExceptionStatus.ConnectFailure, null); } if (httpConnection.DoOutput) { await request.Content.CopyToAsync(httpConnection.OutputStream).ConfigureAwait(false); } var statusCode = (HttpStatusCode)httpConnection.ResponseCode; var connectionUri = new Uri(httpConnection.URL.ToString()); // If the request was redirected we need to put the new URL in the request request.RequestUri = connectionUri; var ret = new AndroidHttpResponseMessage(javaUrl, httpConnection) { RequestMessage = request, ReasonPhrase = httpConnection.ResponseMessage, StatusCode = statusCode, }; if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code: {statusCode}"); } bool disposeRet; if (HandleRedirect(statusCode, httpConnection, redirectState, out disposeRet)) { if (disposeRet) { ret.Dispose(); ret = null; } return(ret); } switch (statusCode) { case HttpStatusCode.Unauthorized: case HttpStatusCode.ProxyAuthenticationRequired: // We don't resend the request since that would require new set of credentials if the // ones provided in Credentials are invalid (or null) and that, in turn, may require asking the // user which is not something that should be taken care of by us and in this // context. The application should be responsible for this. // HttpClientHandler throws an exception in this instance, but I think it's not a good // idea. We'll return the response message with all the information required by the // application to fill in the blanks and provide the requested credentials instead. // // We return the body of the response too, but the Java client will throw // a FileNotFound exception if we attempt to access the input stream. // Instead we try to read the error stream and return an default message if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, new StringContent("Unauthorized", Encoding.ASCII)); CopyHeaders(httpConnection, ret); if (ret.Headers.WwwAuthenticate != null) { ProxyAuthenticationRequested = false; CollectAuthInfo(ret.Headers.WwwAuthenticate); } else if (ret.Headers.ProxyAuthenticate != null) { ProxyAuthenticationRequested = true; CollectAuthInfo(ret.Headers.ProxyAuthenticate); } ret.RequestedAuthentication = RequestedAuthentication; return(ret); } if (!IsErrorStatusCode(statusCode)) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Reading..."); } ret.Content = GetContent(httpConnection, httpConnection.InputStream); } else { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code is {statusCode}, reading..."); } // For 400 >= response code <= 599 the Java client throws the FileNotFound exception when attempting to read from the input stream. // Instead we try to read the error stream and return an empty string if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, new StringContent(String.Empty, Encoding.ASCII)); } CopyHeaders(httpConnection, ret); IEnumerable <string> cookieHeaderValue; if (!UseCookies || CookieContainer == null || !ret.Headers.TryGetValues("Set-Cookie", out cookieHeaderValue) || cookieHeaderValue == null) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"No cookies"); } return(ret); } try { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Parsing cookies"); } CookieContainer.SetCookies(connectionUri, String.Join(",", cookieHeaderValue)); } catch (Exception ex) { // We don't want to terminate the response because of a bad cookie, hence just reporting // the issue. We might consider adding a virtual method to let the user handle the // issue, but not sure if it's really needed. Set-Cookie header will be part of the // header collection so the user can always examine it if they spot an error. if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Failed to parse cookies in the server response. {ex.GetType ()}: {ex.Message}"); } } if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Returning"); } return(ret); }
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] sparams) { string method = sparams[0].ToString(); if (method.Equals("register")) { try { URL url = new URL(register_url); HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection(); urlConn.RequestMethod = "POST"; urlConn.DoInput = true; urlConn.DoOutput = true; Stream oStream = urlConn.OutputStream; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8")); string name = sparams[1].ToString(); string email = sparams[2].ToString(); string phone = sparams[3].ToString(); string address = sparams[4].ToString(); string password = sparams[5].ToString(); // Log.e("LOG - NAME",name); //Log.e("LOG - email",email); string data = URLEncoder.Encode("name", "UTF-8") + "=" + URLEncoder.Encode(name, "UTF-8") + "&" + URLEncoder.Encode("email", "UTF-8") + "=" + URLEncoder.Encode(email, "UTF-8") + "&" + URLEncoder.Encode("phone", "UTF-8") + "=" + URLEncoder.Encode(phone, "UTF-8") + "&" + URLEncoder.Encode("address", "UTF-8") + "=" + URLEncoder.Encode(address, "UTF-8") + "&" + URLEncoder.Encode("password", "UTF-8") + "=" + URLEncoder.Encode(password, "UTF-8"); //Log.e("LOG","bw.write(data)"); bw.Write(data); bw.Flush(); bw.Close(); oStream.Close(); Stream iStream = urlConn.InputStream; BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); string line = ""; // Log.e("LOG","line=br.readLine("); while ((line = br.ReadLine()) != null) { stringBuilder.Append(line + "\n"); } urlConn.Disconnect(); // Log.e("LOG","result: "+stringBuilder.ToString().trim()); try { Thread.Sleep(3000); } catch (InterruptedException e) { // e.printStackTrace(); } return(stringBuilder.ToString().Trim()); } catch (System.Exception x) { } } if (method.Equals("login")) { URL url = new URL(login_url); HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection(); urlConn.RequestMethod = "POST"; urlConn.DoInput = true; urlConn.DoOutput = true; Stream oStream = urlConn.OutputStream; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8")); string email = sparams[1].ToString(); string password = sparams[2].ToString(); string data = URLEncoder.Encode("email", "UTF-8") + "=" + URLEncoder.Encode(email, "UTF-8") + "&" + URLEncoder.Encode("password", "UTF-8") + "=" + URLEncoder.Encode(password, "UTF-8"); //Log.e("LOG","bw.write(data)"); bw.Write(data); bw.Flush(); bw.Close(); oStream.Close(); try { Stream iStream = urlConn.InputStream; BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); string line = ""; // Log.e("LOG","line=br.readLine("); while ((line = br.ReadLine()) != null) { stringBuilder.Append(line + "\n"); } urlConn.Disconnect(); // Log.e("LOG","result: "+stringBuilder.ToString().trim()); try { Thread.Sleep(3000); } catch (InterruptedException e) { // e.printStackTrace(); } return(stringBuilder.ToString().Trim()); } catch (System.Exception x) { Toast.MakeText(ctx, x.Message, ToastLength.Short); } } return(null); }
/// <summary> /// 构造函数 /// </summary> /// <param name="handler">客户端Socket</param> public HttpRequest(Stream handler) { int length = 0; do { //缓存客户端请求报文 length = handler.Read(bytes, 0, MAX_SIZE - 1); content += Encoding.UTF8.GetString(bytes, 0, length); } while (length > 0 && !content.Contains("\r\n\r\n")); if (string.IsNullOrEmpty(content)) { return; } //按行分割请求报文 string[] lines = content.Split('\n'); //获取请求方法 var firstLine = lines[0].Split(' '); if (firstLine.Length > 0) { this.Method = firstLine[0]; } if (firstLine.Length > 1) { this.URL = Uri.UnescapeDataString(firstLine[1]); } //获取请求参数 if (this.Method == "GET" && this.URL.Contains('?')) { this.Params = GetRequestParams(URL.Split('?')[1]); } else if (this.Method == "POST") { this.Params = GetRequestParams(lines[lines.Length - 1]); } //获取各种请求报文参数 this.AcceptTypes = GetKeyValueArrayByKey(content, "Accept"); this.AcceptCharset = GetKeyValueArrayByKey(content, "Accept-Charset"); this.AcceptEncoding = GetKeyValueArrayByKey(content, "Accept-Encoding"); this.AcceptLanguage = GetKeyValueArrayByKey(content, "Accept-Langauge"); this.Authorization = GetKeyValueByKey(content, "Authorization"); this.If_Match = GetKeyValueByKey(content, "If-Match"); this.If_None_Match = GetKeyValueByKey(content, "If-None-Match"); this.If_Modified_Since = GetKeyValueByKey(content, "If-Modified-Since"); this.If_Unmodified_Since = GetKeyValueByKey(content, "If-Unmodified-Since"); this.If_Range = GetKeyValueByKey(content, "If-Range"); this.Range = GetKeyValueByKey(content, "Range"); this.Proxy_Authenticate = GetKeyValueByKey(content, "Proxy-Authenticate"); this.Proxy_Authorization = GetKeyValueByKey(content, "Proxy-Authorization"); this.Host = GetKeyValueByKey(content, "Host"); this.Referer = GetKeyValueByKey(content, "Referer"); this.User_Agent = GetKeyValueByKey(content, "User-Agent"); //设置HTTP通用头信息 this.Cache_Control = GetKeyValueByKey(content, "Cache-Control"); this.Pragma = GetKeyValueByKey(content, "Pragma"); this.Connection = GetKeyValueByKey(content, "Connection"); this.Date = GetKeyValueByKey(content, "Date"); this.Transfer_Encoding = GetKeyValueByKey(content, "Transfe-Encoding"); this.Upgrade = GetKeyValueByKey(content, "Upgrade"); this.Via = GetKeyValueByKey(content, "Via"); //设置HTTP实体头部信息 this.Allow = GetKeyValueByKey(content, "Allow"); this.Location = GetKeyValueByKey(content, "Location"); this.Content_Base = GetKeyValueByKey(content, "Content-Base"); this.Content_Encoding = GetKeyValueByKey(content, "Content-Encoidng"); this.Content_Language = GetKeyValueByKey(content, "Content-Language"); this.Content_Length = GetKeyValueByKey(content, "Content-Length"); this.Content_Location = GetKeyValueByKey(content, "Content-Location"); this.Content_MD5 = GetKeyValueByKey(content, "Content-MD5"); this.Content_Range = GetKeyValueByKey(content, "Content-Range"); this.Content_Type = GetKeyValueByKey(content, "Content-Type"); this.Etag = GetKeyValueByKey(content, "Etag"); this.Expires = GetKeyValueByKey(content, "Expires"); this.Last_Modified = GetKeyValueByKey(content, "Last-Modified"); }
public override async Task <IClusterResult <T> > DoInvoke <T>(IClientPool pool, ILoadBalance loadbalance, URL address, IList <URL> urls, IInvocation invocation) { var goodUrls = new List <URL>(); var badUrls = new List <BadUrl>(); var invokers = urls; var merger = address.GetMethodParameter(invocation.MethodInfo.Name, MERGER_KEY); // If a method doesn't have a merger, only invoke one Group if (string.IsNullOrEmpty(merger)) { foreach (var invoker in invokers) { try { var client = await pool.GetClient(invoker); try { var refer = await client.Refer(); _source.WriteConsumerBefore(refer.Instance, invoker, invocation); var invokeResult = await refer.Invoke <T>(invocation); _source.WriteConsumerAfter(invoker, invocation, invokeResult); await pool.Recovery(client); goodUrls.Add(invoker); return(new ClusterResult <T>(invokeResult, goodUrls, badUrls, null, false)); } catch (Exception ex) { _source.WriteConsumerError(invoker, invocation, ex); await pool.DestoryClient(client).ConfigureAwait(false); throw ex; } } catch (Exception e) { badUrls.Add(new BadUrl { Url = invoker, BadTime = DateTime.Now, CurrentException = e }); return(new ClusterResult <T>(new RpcResult <T>(e), goodUrls, badUrls, e, true)); } } var exMerger = new Exception($"merger: {merger} is null and the invokers is empty"); return(new ClusterResult <T>(new RpcResult <T>(exMerger), goodUrls, badUrls, exMerger, true)); } Type returnType = invocation.TargetType.GetMethod(invocation.MethodInfo.Name, invocation.ArgumentTypes).ReturnType; object resultValue = null; var watch = Stopwatch.StartNew(); try { var results = new Dictionary <string, Task <IResult <T> > >(); foreach (var invoker in invokers) { var task = Task.Run(async() => { try { var client = await pool.GetClient(invoker); try { var refer = await client.Refer(); _source.WriteConsumerBefore(refer.Instance, invoker, invocation); var invokeResult = await refer.Invoke <T>(invocation); _source.WriteConsumerAfter(invoker, invocation, invokeResult); await pool.Recovery(client); goodUrls.Add(invoker); return(invokeResult); } catch (Exception ex) { await pool.DestoryClient(client); _source.WriteConsumerError(invoker, invocation, ex); throw ex; } } catch (Exception e) { badUrls.Add(new BadUrl { Url = invoker, BadTime = DateTime.Now, CurrentException = e }); return(new RpcResult <T>(e)); } }); results.Add(invoker.ServiceKey, task); } var resultList = new List <IResult <T> >(results.Count); int timeout = address.GetMethodParameter(invocation.MethodInfo.Name, TIMEOUT_KEY, DEFAULT_TIMEOUT); Task.WaitAll(results.Values.ToArray(), timeout); foreach (var entry in results) { var r = await entry.Value; if (r.HasException) { Logger().LogError(r.Exception, $"Invoke {entry.Key} {getGroupDescFromServiceKey(entry.Key)} failed: {r.Exception.Message}"); return(new ClusterResult <T>(new RpcResult <T>(r.Exception), goodUrls, badUrls, r.Exception, true)); } else { resultList.Add(r); } } watch.Stop(); if (resultList.Count == 0) { return(new ClusterResult <T>(new RpcResult <T>(watch.ElapsedMilliseconds), goodUrls, badUrls, null, false)); } else if (resultList.Count == 1) { return(new ClusterResult <T>(resultList[0], goodUrls, badUrls, null, false)); } if (returnType == typeof(void)) { return(new ClusterResult <T>(new RpcResult <T>(watch.ElapsedMilliseconds), goodUrls, badUrls, null, false)); } if (merger.StartsWith(".")) { merger = merger.Substring(1); MethodInfo method; try { method = returnType.GetMethod(merger, new[] { returnType }); } catch (Exception e) { var ex = new RpcException($"Can not merge result because missing method [{merger}] in class [{returnType.Name}]{e.Message}", e); return(new ClusterResult <T>(new RpcResult <T>(ex), goodUrls, badUrls, ex, true)); } if (method == null) { var ex = new RpcException($"Can not merge result because missing method [ {merger} ] in class [ {returnType.Name} ]"); return(new ClusterResult <T>(new RpcResult <T>(ex), goodUrls, badUrls, ex, true)); } //if (!method.IsPublic) //{ //method.setAccessible(true); //} resultValue = resultList[0].Value; resultList.RemoveAt(0); try { if (method.ReturnType != typeof(void) && method.ReturnType.IsAssignableFrom(resultValue.GetType())) { foreach (var r in resultList) { resultValue = method.Invoke(resultValue, new object[] { r.Value }); } } else { foreach (var r in resultList) { method.Invoke(resultValue, new object[] { r.Value }); } } } catch (Exception e) { var ex = new RpcException($"Can not merge result: {e.Message}", e); return(new ClusterResult <T>(new RpcResult <T>(ex), goodUrls, badUrls, ex, true)); } } else { IMerger resultMerger; if (merger.ToLower() == "true" || merger.ToLower() == "default") { resultMerger = MergerFactory.GetMerger(returnType, _defaultMergers); } else { resultMerger = _mySelfMergers[merger]; } if (resultMerger != null) { var rets = new List <object>(resultList.Count); foreach (var r in resultList) { rets.Add(r.Value); } resultValue = resultMerger.GetType().GetMethod("Merge", new Type[] { returnType }).Invoke(resultMerger, new[] { rets }); } else { var ex = new RpcException("There is no merger to merge result."); return(new ClusterResult <T>(new RpcResult <T>(ex), goodUrls, badUrls, ex, true)); } } return(new ClusterResult <T>(new RpcResult <T>((T)resultValue.ChangeType(typeof(T)), watch.ElapsedMilliseconds), goodUrls, badUrls, null, false)); } catch (Exception ex) { Debug.Print(ex.StackTrace); throw ex; } finally { if (watch.IsRunning) { watch.Stop(); } } }
private async void FavoriteRepresentation_Load(object sender, EventArgs e) { btFinish.Text = Program.LocalizedString("Finish"); this.Text = Program.LocalizedString("FavoriteRepresentation"); this.Name = Program.LocalizedString("FavoriteRepresentation"); try { List <TeamResult> representations = null; lbTooltip.Text = Program.LocalizedString("Fetching"); string baseUrl = Program.userSettings.SavedLeague == UserSettings.League.Female ? URL.F_BASE_URL : URL.M_BASE_URL; string uri = Program.CACHE + baseUrl.Substring(7).Replace('\\', '-').Replace('/', '-') + "@TeamResult" + ".json"; // checked 1 if (File.Exists(uri)) { representations = await Fetch.FetchJsonFromFileAsync <List <TeamResult> >(uri); } else { representations = await Fetch.FetchJsonFromUrlAsync <List <TeamResult> >(URL.Teams(Program.userSettings.GenderedRepresentationUrl())); File.WriteAllText(uri, JsonConvert.SerializeObject(representations)); } teams = representations; cbRepresentation.DataSource = representations.OrderBy(x => x.FifaCode) .Select(x => $"{x.Country} ({x.FifaCode})") .ToList(); dataLoaded = true; lbTooltip.Text = Program.LocalizedString("Done"); if (Program.lastTeam != null) { cbRepresentation.SelectedItem = $"{Program.lastTeam.Country} ({Program.lastTeam.FifaCode})"; } } catch (HttpStatusException ex) { lbTooltip.Text = Program.LocalizedString("Aborting"); MessageBox.Show(ex.Message, ex.GetType().Name); Application.Exit(); } catch (JsonException ex) { lbTooltip.Text = Program.LocalizedString("Aborting"); MessageBox.Show(ex.Message, ex.GetType().Name); Application.Exit(); } catch (Exception ex) { lbTooltip.Text = Program.LocalizedString("Aborting"); MessageBox.Show(ex.Message, ex.GetType().Name); Application.Exit(); } }
public override void SetAudioFile(URL audioFileUrl, string streamName) { throw new InvalidOperationException(); }
protected void Page_Load(object sender, EventArgs e) { this.RegisterWorkareaCssLink(); this.RegisterDialogCssLink(); Ektron.Cms.API.JS.RegisterJS(this, "../ContentDesigner/ekxbrowser.js", "ekxbrowserJS"); Ektron.Cms.API.JS.RegisterJS(this, "../ContentDesigner/ekutil.js", "ekutilJS"); Ektron.Cms.API.JS.RegisterJS(this, "../ContentDesigner/RadWindow.js", "RadWindowJS"); this.ClientScript.RegisterClientScriptBlock(this.GetType(), "InitializeRadWindow", "InitializeRadWindow(); self.focus();", true); m_refMsg = m_refAPI.EkMsgRef; Utilities.ValidateUserLogin(); titlePage.Text = m_refMsg.GetMessage("lbl imagetool edit title"); if (!Page.IsPostBack) { // Information from the URL parameters if (null != Request.Params.Get("s")) { if (null != Session["ImageToolNewFile"]) { // save image clicked // update the thumbnail for the image Ektron.Cms.ImageTool.ImageTool imager = new Ektron.Cms.ImageTool.ImageTool(); string imagefilepath = (string) Session["ImageToolNewFile"]; string thumbfilepath = imagefilepath; if (thumbfilepath.ToLower().EndsWith(".gif")) { thumbfilepath = thumbfilepath.Substring(0, thumbfilepath.LastIndexOf(".")) + ".png"; } thumbfilepath = thumbfilepath.Substring(0, thumbfilepath.LastIndexOf("\\") + 1) + "thumb_" + thumbfilepath.Substring(thumbfilepath.LastIndexOf("\\") + 1); /**** THIS IS NOW DONE in ImageScore.aspx.cs on CommitPersistentCommand try { imager.Resize(125, -1, true, imagefilepath, thumbfilepath); } catch (IOException) { // the thumbnail service might be already updating the thumbnail // so just ignore any I/O exceptions } */ // copy image to any load balance locations Ektron.Cms.Library.EkLibrary refLib = m_refAPI.EkLibraryRef; foreach (Microsoft.VisualBasic.Collection libpath in refLib.GetAllLBPaths("images")) { string relLBpath = (string) libpath["LoadBalancePath"]; string realLBpath = Server.MapPath(relLBpath); string imgfilename = imagefilepath.Substring(imagefilepath.LastIndexOf("\\")+1); string thumbnailfname = thumbfilepath.Substring(thumbfilepath.LastIndexOf("\\")+1); try { File.Copy(imagefilepath, realLBpath + imgfilename); } catch (Exception) {} try { File.Copy(thumbfilepath, realLBpath + thumbnailfname); } catch (Exception) { } } // clear out the session variable holding the new filename Session["ImageToolNewFile"] = null; Session["ImageToolNewFileUrl"] = null; Session["ImageToolOldLibId"] = null; Session["ImageToolOldLibContentId"] = null; Session["ImageToolNewLibFileName"] = null; Session["ImageToolLibFolderId"] = null; Session["ImageToolAssetName"] = null; } } else if (null != Request.Params.Get("c")) { // cancel, so delete the new image file // then delete the session variable holding the new filename if (null != Session["ImageToolNewFile"]) { // get rid of library entry for image Ektron.Cms.ContentAPI refContApi = getContentAPI(); refContApi.DeleteLibraryItemForImageTool((string)Session["ImageToolNewFileUrl"]); if ((Session["ImageToolAssetName"] != null) && !((string)Session["ImageToolAssetName"]).StartsWith("thumb_")) { refContApi.DeleteAssetForImageTool((string)Session["ImageToolAssetName"]); } // get rid of image file string imagefilepath = (string)Session["ImageToolNewFile"]; if (File.Exists(imagefilepath)) { try { File.Delete(imagefilepath); } catch (IOException) { } } string thumbfilepath = imagefilepath; if (thumbfilepath.ToLower().EndsWith(".gif")) { thumbfilepath = thumbfilepath.Substring(0, thumbfilepath.LastIndexOf(".")) + ".png"; } thumbfilepath = thumbfilepath.Substring(0, thumbfilepath.LastIndexOf("\\") + 1) + "thumb_" + thumbfilepath.Substring(thumbfilepath.LastIndexOf("\\") + 1); // and the thumbnail if (File.Exists(thumbfilepath)) { try { File.Delete(thumbfilepath); } catch (IOException) { } } } Session["ImageToolNewFile"] = null; Session["ImageToolNewFileUrl"] = null; Session["ImageToolOldLibId"] = null; Session["ImageToolOldLibContentId"] = null; Session["ImageToolNewLibFileName"] = null; Session["ImageToolLibFolderId"] = null; Session["ImageToolAssetName"] = null; } else if (null != Request.Params.Get("i")) { string strValue = Page.Server.UrlDecode(Request.Params.Get("i")).Trim(); if (!strValue.Contains("://")) { // see if we're editing a thumbnailed image which comes in w/o a full URL strValue = Request.Url.Scheme + "://" + Request.Url.Host + ((((Request.Url.Scheme == "http") && (Request.Url.Port != 80)) || ((Request.Url.Scheme == "https") && (Request.Url.Port != 443))) ? (":" + Request.Url.Port) : "") + strValue; } if (strValue.Contains("://")) { URL url = new URL(strValue); URL myURL = new URL(Page.Request.Url.ToString()); strValue = url.Path; if (strValue.StartsWith(":")) { // work around asp.net bug where url.path includes port# for path strValue = strValue.Substring(strValue.IndexOf("/")); } // get info for old library item string origImagePath = strValue; bool fEditingThumbnail = false; bool fIsAssetImage = false; Ektron.Cms.ContentAPI refContApi = getContentAPI(); Ektron.Cms.LibraryData library_data = refContApi.GetLibraryItemByUrl(strValue); if ((library_data == null) && strValue.Contains("thumb_")) { // this is a thumbnail so try to locate the image associated with it // since we don't store the thumbnail path in the DB origImagePath = strValue.Replace("thumb_", ""); library_data = refContApi.GetLibraryItemByUrl(origImagePath); if (library_data == null) { // thumbnails are PNG files so see if the original was a JPEG or GIF string[] imageexts = { ".jpg", ".gif" }; foreach (string ext in imageexts) { string origImageGuess = origImagePath.Replace(".png", ext); library_data = refContApi.GetLibraryItemByUrl(origImageGuess); if (library_data != null) { origImagePath = origImageGuess; break; } } } fEditingThumbnail = true; } if (library_data == null) { panelMessage.Visible = true; lblMessage.Text = m_refMsg.GetMessage("err imagetool unable to find image") + strValue; imagetool.Visible = false; return; } long folderid = library_data.ParentId; if ((library_data.ParentId == 0) && (library_data.ContentId != 0)) { // this is a DMS asset, so look up the folder it belongs in folderid = refContApi.GetFolderIdForContentId(library_data.ContentId); fIsAssetImage = true; } Ektron.Cms.PermissionData security_data = refContApi.LoadPermissions(folderid, "folder", Ektron.Cms.ContentAPI.PermissionResultType.Common); Ektron.Cms.PermissionData usersecurity_data = refContApi.LoadPermissions(refContApi.UserId, "users", Ektron.Cms.ContentAPI.PermissionResultType.All); if (!security_data.CanAddToImageLib && !usersecurity_data.IsAdmin) { panelMessage.Visible = true; lblMessage.Text = m_refMsg.GetMessage("err imagetool no library permission"); imagetool.Visible = false; return; } // generate new filename if ((url.HostName == myURL.HostName) || (url.HostName.ToLower() == "localhost")) { string strFilePath = null; try { strFilePath = Server.MapPath(origImagePath); } catch (Exception) { panelMessage.Visible = true; lblMessage.Text = m_refMsg.GetMessage("err imagetool non site image"); imagetool.Visible = false; return; } string strNewFilePath = strFilePath; if (File.Exists(strFilePath)) { FileInfo fileinfo = new FileInfo(strFilePath); // name the file "<oldname>.N.<extension>" string origfname = fileinfo.Name; string fname = origfname; string newfname = fname; do { string[] fnamepieces = fname.Split(new char[] { '.' }); newfname = fname; if (fnamepieces.Length > 2) { // loop until we find one that doesn't exist string strCurVer = fnamepieces[fnamepieces.Length - 2]; string strExt = fnamepieces[fnamepieces.Length - 1]; int newVer = int.Parse(strCurVer) + 1; newfname = fname.Replace("." + strCurVer + "." + strExt, "." + newVer + "." + strExt); } else if (fnamepieces.Length == 2) { newfname = fnamepieces[0] + ".1." + fnamepieces[1]; } else { // not sure what to do w/ filename w/ no extension??? } strNewFilePath = strNewFilePath.Replace(fname, newfname); fileinfo = new FileInfo(strNewFilePath); if (fileinfo.Exists) { fname = fileinfo.Name; } } while (fileinfo.Exists); if (strFilePath != strNewFilePath) { File.Copy(strFilePath, strNewFilePath); strValue = origImagePath.Replace(origfname, newfname); // save new filename so we can clean it up when user clicks on "cancel" button Session["ImageToolNewFile"] = strNewFilePath; // save URL so we can delete it from the library Session["ImageToolNewFileUrl"] = strValue; // save asset filename if we it's an asset Session["ImageToolAssetName"] = null; if (fIsAssetImage) { Session["ImageToolAssetName"] = newfname; } if (library_data != null) { // save tags and metadata for original image Ektron.Cms.TagData[] oldtags = null; Ektron.Cms.Community.TagsAPI refTagsApi = new Ektron.Cms.Community.TagsAPI(); Ektron.Cms.ContentMetaData[] oldmeta = null; if (library_data.Id > 0) { Session["ImageToolOldLibId"] = library_data.Id; Session["ImageToolOldLibContentId"] = library_data.ContentId; oldtags = refTagsApi.GetTagsForObject(library_data.Id, Ektron.Cms.Common.EkEnumeration.CMSObjectTypes.Library, refContApi.ContentLanguage); if (library_data.ContentId != 0) { Ektron.Cms.ContentData content_data = refContApi.GetContentById(library_data.ContentId, Ektron.Cms.ContentAPI.ContentResultType.Published); if (content_data != null) { oldmeta = content_data.MetaData; } } else { oldmeta = library_data.MetaData; } } // create new image to edit library_data.Id = 0; if (fEditingThumbnail) { origfname = new FileInfo(origImagePath).Name; library_data.FileName = library_data.FileName.Replace(origfname, newfname); } else { library_data.FileName = library_data.FileName.Replace(origfname, newfname); } library_data.ParentId = folderid; Session["ImageToolNewLibFileName"] = library_data.FileName; Session["ImageToolLibFolderId"] = library_data.ParentId; long newLibId = refContApi.AddLibraryItemForImageTool(ref library_data); if (fIsAssetImage && !newfname.StartsWith("thumb_")) { // only need to add this for assets, not thumbnail of assets refContApi.AddAssetForImageTool(origfname, newfname); } // add original tags/metadata to new image if (oldtags != null) { foreach (Ektron.Cms.TagData tag in oldtags) { refTagsApi.AddTagToObject(tag.Id, newLibId, Ektron.Cms.Common.EkEnumeration.CMSObjectTypes.Library, -1, refContApi.ContentLanguage); } } if (oldmeta != null) { refContApi.UpdateLibraryMetadataByID(newLibId, oldmeta); } } // can't show filenames or it'll be too long and the DMS filenames are ugly //titlePage.Text = m_refMsg.GetMessage("lbl imagetool edit title") + ": " + origfname; } } imagetool.Edit(strValue); } else { panelMessage.Visible = true; lblMessage.Text = m_refMsg.GetMessage("err imagetool non site image"); imagetool.Visible = false; } } } } }
/// <summary> /// Loads the language model from the given location. /// </summary> /// <param name="location">The URL location of the model.</param> /// <param name="unigramWeightValue">The unigram weight.</param> /// <param name="dictionaryValue">The dictionary.</param> private void Load(URL location, float unigramWeightValue, IDictionary dictionaryValue) { string line; float logUnigramWeight = _logMath.LinearToLog(unigramWeightValue); float inverseLogUnigramWeight = _logMath .LinearToLog(1.0 - unigramWeightValue); Open(location); // look for beginning of data ReadUntil("\\data\\"); // look for ngram statements List <int> ngramList = new List <int>(); while ((line = ReadLine()) != null) { if (line.StartsWith("ngram")) { StringTokenizer st = new StringTokenizer(line, " \t\n\r\f="); if (st.countTokens() != 3) { Corrupt("corrupt ngram field " + line + ' ' + st.countTokens()); } st.nextToken(); int index = int.Parse(st.nextToken(), CultureInfo.InvariantCulture.NumberFormat); int count = int.Parse(st.nextToken(), CultureInfo.InvariantCulture.NumberFormat); ngramList.Insert(index - 1, count); MaxDepth = Math.Max(index, MaxDepth); } else if (line.Equals("\\1-grams:")) { break; } } int numUnigrams = ngramList[0] - 1; // -log(x) = log(1/x) float logUniformProbability = -_logMath.LinearToLog(numUnigrams); for (int index = 0; index < ngramList.Count; index++) { int ngram = index + 1; int ngramCount = ngramList[index]; for (int i = 0; i < ngramCount; i++) { StringTokenizer tok = new StringTokenizer(ReadLine()); int tokenCount = tok.countTokens(); if (tokenCount != ngram + 1 && tokenCount != ngram + 2) { Corrupt("Bad format"); } float log10Prob = float.Parse(tok.nextToken(), CultureInfo.InvariantCulture.NumberFormat); float log10Backoff = 0.0f; // construct the WordSequence for this N-Gram List <Word> wordList = new List <Word>(MaxDepth); for (int j = 0; j < ngram; j++) { string word = tok.nextToken(); _vocabulary.Add(word); Word wordObject = dictionaryValue.GetWord(word); if (wordObject == null) { wordObject = Word.Unknown; } wordList.Add(wordObject); } WordSequence wordSequence = new WordSequence(wordList); if (tok.hasMoreTokens()) { log10Backoff = float.Parse(tok.nextToken(), CultureInfo.InvariantCulture.NumberFormat); } float logProb = _logMath.Log10ToLog(log10Prob); float logBackoff = _logMath.Log10ToLog(log10Backoff); // Apply unigram weights if this is a unigram probability if (ngram == 1) { float p1 = logProb + logUnigramWeight; float p2 = logUniformProbability + inverseLogUnigramWeight; logProb = _logMath.AddAsLinear(p1, p2); // System.out // .println("p1 " + p1 + " p2 " + p2 + " luw " // + logUnigramWeight + " iluw " // + inverseLogUnigramWeight + " lup " // + logUniformProbability + " logprog " // + logProb); } Put(wordSequence, logProb, logBackoff); } if (index < ngramList.Count - 1) { string next = "\\" + (ngram + 1) + "-grams:"; ReadUntil(next); } } ReadUntil("\\end\\"); Close(); }
public TVSeriesMainPage(string html, URL request, URL response, MovieId id, GenreCollection genreCollection) : base(html, request, response, id, genreCollection) { LastYear = new ParsedInfo<int>(html, parseYear); }
/// <summary> /// the language model at the given location /// </summary> /// <param name="location">The path to the language model.</param> private void Open(URL location) { LineNumber = 0; FileName = location.Path; Reader = new StreamReader(FileName); }
protected override void WriteMetaToItem(string meta, ContactItem item) { Fonlow.VCard.VCard vcard = VCardReader.ParseText(meta); item.LastName = vcard.Surname; item.FirstName = vcard.GivenName; item.MiddleName = vcard.MiddleName; item.Title = vcard.Title; item.Suffix = vcard.Suffix; // item.FullName = vcard.FormattedName;//This must be after lastName to Suffix, otherwise, item.FullName will be recomposed by Outlook item.Body = vcard.Note; item.CompanyName = vcard.Org; item.Department = vcard.Department; item.JobTitle = vcard.Role; if (vcard.Birthday > DateTime.MinValue) { item.Birthday = vcard.Birthday; } PhoneNumber phoneNumber = vcard.Phones.GetItemsOfTypes(PhoneTypes.CELL).FirstOrDefault(); if (phoneNumber != null) { item.MobileTelephoneNumber = phoneNumber.Number; } //Home phones IEnumerable <PhoneNumber> numbers = vcard.Phones.GetItemsOfTypes(PhoneTypes.VOICE, HomeWorkTypes.HOME); phoneNumber = numbers.FirstOrDefault(); if (phoneNumber != null) { item.HomeTelephoneNumber = phoneNumber.Number; if (numbers.Count() > 1) { item.Home2TelephoneNumber = numbers.ElementAt(1).Number; } } //Home fax numbers = vcard.Phones.GetItemsOfTypes(PhoneTypes.FAX, HomeWorkTypes.HOME); phoneNumber = numbers.FirstOrDefault(); if (phoneNumber != null) { item.HomeFaxNumber = phoneNumber.Number; } //Work phones numbers = vcard.Phones.GetItemsOfTypes(PhoneTypes.VOICE, HomeWorkTypes.WORK); phoneNumber = numbers.FirstOrDefault(); if (phoneNumber != null) { item.BusinessTelephoneNumber = phoneNumber.Number; if (numbers.Count() > 1) { item.Business2TelephoneNumber = numbers.ElementAt(1).Number; } } //Work fax numbers = vcard.Phones.GetItemsOfTypes(PhoneTypes.FAX, HomeWorkTypes.WORK); phoneNumber = numbers.FirstOrDefault(); if (phoneNumber != null) { item.BusinessFaxNumber = phoneNumber.Number; } //Other phone numbers = vcard.Phones.GetItemsOfTypesExactly(PhoneTypes.VOICE, HomeWorkTypes.None); phoneNumber = numbers.FirstOrDefault(); if (phoneNumber != null) { item.OtherTelephoneNumber = phoneNumber.Number; } //Other fax numbers = vcard.Phones.GetItemsOfTypesExactly(PhoneTypes.FAX, HomeWorkTypes.None); phoneNumber = numbers.FirstOrDefault(); if (phoneNumber != null) { item.OtherFaxNumber = phoneNumber.Number; } phoneNumber = vcard.Phones.GetPreferredItems().FirstOrDefault(n => (n.HomeWorkTypes == HomeWorkTypes.HOME) || (n.HomeWorkTypes == HomeWorkTypes.None)); if (phoneNumber != null) { item.PrimaryTelephoneNumber = phoneNumber.Number; } phoneNumber = vcard.Phones.GetPreferredItems().FirstOrDefault(n => n.HomeWorkTypes == HomeWorkTypes.WORK); if (phoneNumber != null) { item.CompanyMainTelephoneNumber = phoneNumber.Number; } phoneNumber = vcard.Phones.GetItemsOfTypes(PhoneTypes.PAGER).FirstOrDefault(); if (phoneNumber != null) { item.PagerNumber = phoneNumber.Number; } EmailAddress email = vcard.Emails.FirstOrDefault(); if (email != null) { item.Email1Address = email.Address; if (vcard.Emails.Count() > 1) { item.Email2Address = vcard.Emails.ElementAt(1).Address; } if (vcard.Emails.Count() > 2) { item.Email3Address = vcard.Emails.ElementAt(2).Address; } } Address address = vcard.Addresses.FirstOrDefault(n => n.HomeWorkType == HomeWorkTypes.HOME); if (address != null) { item.HomeAddressCity = address.Locality; item.HomeAddressCountry = address.Country; item.HomeAddressPostalCode = address.Postcode; item.HomeAddressPostOfficeBox = address.POBox; item.HomeAddressState = address.Region; item.HomeAddressStreet = address.Street; } address = vcard.Addresses.FirstOrDefault(n => n.HomeWorkType == HomeWorkTypes.WORK); if (address != null) { item.BusinessAddressCity = address.Locality; item.BusinessAddressCountry = address.Country; item.BusinessAddressPostalCode = address.Postcode; item.BusinessAddressPostOfficeBox = address.POBox; item.BusinessAddressState = address.Region; item.BusinessAddressStreet = address.Street; } URL url = vcard.URLs.FirstOrDefault(n => n.HomeWorkTypes == HomeWorkTypes.HOME); if (url != null) { item.PersonalHomePage = url.Address; } url = vcard.URLs.FirstOrDefault(n => n.HomeWorkTypes == HomeWorkTypes.WORK); if (url != null) { item.BusinessHomePage = url.Address; } }
//====================================================================== // Construction /// <summary> /// Initializes the object with a factory and a default URL. /// </summary> /// <param name="factory">The Opc.Factory used to connect to remote servers.</param> /// <param name="url">The network address of a remote server.</param> public Server(Factory factory, URL url) : base(factory, url) { }
public HTTPRequest(string requestraw) { if (String.IsNullOrEmpty(requestraw)) { return; } Raw = requestraw.ToLower(); Headers = Raw.Split("\n"); string[] firstline = requestraw.Split("\n")[0].Split(' '); int contentLength = 0; if (firstline.Length == 3) { Method = new HttpMethod(firstline[0]); URL = firstline[1]; URLPath = URL.Split('?')[0]; if (firstline[2].Contains("1.1")) { Version = HttpVersion.Http11; } else if (firstline[2].Contains("1.0")) { Version = HttpVersion.Http10; } for (int h = 1; h < Headers.Length; h++) { Headers[h] = Regex.Replace(Headers[h], @"\t|\n|\r|\0", ""); if (!Headers[h].Contains(":")) { continue; } string pair0 = Headers[h].Substring(0, Headers[h].IndexOf(":")).Trim(); string pair1 = Headers[h].Substring(Headers[h].IndexOf(":") + 1).Trim(); HeaderPairs.TryAdd(pair0, pair1); } if (HeaderPairs.TryGetValue("host", out string hostValue) == false) { if (Version == HttpVersion.Http11) { throw new HTTPException(HttpStatusCode.BadRequest, "No host header was found on http/1.1 request : " + Raw); } } if (HeaderPairs.TryGetValue("connection", out string connectionValue)) { if (connectionValue == "close") { Persistent = false; } } if (HeaderPairs.TryGetValue("content-length", out string contentLengthValue)) { contentLength = int.Parse(contentLengthValue); } if (HeaderPairs.TryGetValue("content-type", out string contentTypeValue)) { Content = requestraw.Substring(requestraw.Length - contentLength); if (contentTypeValue.Contains("application/x-www-form-urlencoded")) { string[] keys = Content.Split("&"); for (int k = 0; k < keys.Length; k++) { string[] pair = keys[k].Split("="); if (pair.Length > 1) { KVPairs.TryAdd(pair[0], System.Web.HttpUtility.UrlDecode(pair[1])); } } } } if (Version == HttpVersion.Http20 || Version == HttpVersion.None) { throw new HTTPException(HttpStatusCode.HttpVersionNotSupported, "HTTP Version not supported"); } if (Version == HttpVersion.Http10) { Persistent = false; } } else { throw new HTTPException(HttpStatusCode.BadRequest, "HTTP Request was malformed : " + Raw); } }
public SuffixFSM(URL url) : base(url, false) { }
// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201403/20140322 // one of the jobs of any class loader is to protect the system name space. // The normal ClassLoader heirarchy does address this by always delegating to the parent ClassLoader first, // thus ensuring that duplicate classes are not loaded // If you use custom ClassLoader, do not give the system one a chance to come into play. // http://blog.cyberborean.org/2007/07/04/custom-classloaders-the-black-art-of-java public InternalURLClassLoader(URL[] u, ClassLoader parent) : base(u, parent) { }
/// <summary> /// This method performs the image recognition for specified image URL. /// Returns image recognition result as map with image labels as keys and /// recogition result as value /// </summary> /// <returns> image recognition result </returns> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public java.util.HashMap<String, Double> recognizeImage(java.net.URL imgURL) throws java.io.IOException, ImageSizeMismatchException public virtual Dictionary <string, double?> recognizeImage(URL imgURL) { Input = imgURL; processInput(); return(Output); }
async Task <HttpResponseMessage> DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()"); } if (cancellationToken.IsCancellationRequested) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, " cancelled"); } cancellationToken.ThrowIfCancellationRequested(); } try { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connecting"); } await ConnectAsync(httpConnection, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $" connected"); } } catch (Java.Net.ConnectException ex) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Connection exception {ex}"); } // Wrap it nicely in a "standard" exception so that it's compatible with HttpClientHandler throw new WebException(ex.Message, ex, WebExceptionStatus.ConnectFailure, null); } if (cancellationToken.IsCancellationRequested) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, " cancelled"); } await DisconnectAsync(httpConnection).ConfigureAwait(continueOnCapturedContext: false); cancellationToken.ThrowIfCancellationRequested(); } CancellationTokenRegistration cancelRegistration = default(CancellationTokenRegistration); HttpStatusCode statusCode = HttpStatusCode.OK; Uri connectionUri = null; try { cancelRegistration = cancellationToken.Register(() => { DisconnectAsync(httpConnection).ContinueWith(t => { if (t.Exception != null) { Logger.Log(LogLevel.Info, LOG_APP, $"Disconnection exception: {t.Exception}"); } }, TaskScheduler.Default); }, useSynchronizationContext: false); if (httpConnection.DoOutput) { await WriteRequestContentToOutput(request, httpConnection, cancellationToken); } statusCode = await Task.Run(() => (HttpStatusCode)httpConnection.ResponseCode).ConfigureAwait(false); connectionUri = new Uri(httpConnection.URL.ToString()); } finally { cancelRegistration.Dispose(); } if (cancellationToken.IsCancellationRequested) { await DisconnectAsync(httpConnection).ConfigureAwait(continueOnCapturedContext: false); cancellationToken.ThrowIfCancellationRequested(); } // If the request was redirected we need to put the new URL in the request request.RequestUri = connectionUri; var ret = new AndroidHttpResponseMessage(javaUrl, httpConnection) { RequestMessage = request, ReasonPhrase = httpConnection.ResponseMessage, StatusCode = statusCode, }; if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code: {statusCode}"); } if (!IsErrorStatusCode(statusCode)) { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Reading..."); } ret.Content = GetContent(httpConnection, httpConnection.InputStream); } else { if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Status code is {statusCode}, reading..."); } // For 400 >= response code <= 599 the Java client throws the FileNotFound exception when attempting to read from the input stream. // Instead we try to read the error stream and return an empty string if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, new StringContent(String.Empty, Encoding.ASCII)); } bool disposeRet; if (HandleRedirect(statusCode, httpConnection, redirectState, out disposeRet)) { if (disposeRet) { ret.Dispose(); ret = null; } else { CopyHeaders(httpConnection, ret); ParseCookies(ret, connectionUri); } return(ret); } switch (statusCode) { case HttpStatusCode.Unauthorized: case HttpStatusCode.ProxyAuthenticationRequired: // We don't resend the request since that would require new set of credentials if the // ones provided in Credentials are invalid (or null) and that, in turn, may require asking the // user which is not something that should be taken care of by us and in this // context. The application should be responsible for this. // HttpClientHandler throws an exception in this instance, but I think it's not a good // idea. We'll return the response message with all the information required by the // application to fill in the blanks and provide the requested credentials instead. // // We return the body of the response too, but the Java client will throw // a FileNotFound exception if we attempt to access the input stream. // Instead we try to read the error stream and return an default message if the error stream isn't readable. ret.Content = GetErrorContent(httpConnection, new StringContent("Unauthorized", Encoding.ASCII)); CopyHeaders(httpConnection, ret); if (ret.Headers.WwwAuthenticate != null) { ProxyAuthenticationRequested = false; CollectAuthInfo(ret.Headers.WwwAuthenticate); } else if (ret.Headers.ProxyAuthenticate != null) { ProxyAuthenticationRequested = true; CollectAuthInfo(ret.Headers.ProxyAuthenticate); } ret.RequestedAuthentication = RequestedAuthentication; return(ret); } CopyHeaders(httpConnection, ret); ParseCookies(ret, connectionUri); if (Logger.LogNet) { Logger.Log(LogLevel.Info, LOG_APP, $"Returning"); } return(ret); }
public override async Task <IClusterResult <T> > DoInvoke <T>(IClientPool pool, ILoadBalance loadbalance, URL address, IList <URL> urls, IInvocation invocation) { //IResult result = null; var goodUrls = new List <URL>(); var badUrls = new List <BadUrl>(); checkInvokers(urls, invocation, address); IList <URL> selected; int forks = address.GetParameter(FORKS_KEY, DEFAULT_FORKS); int timeout = address.GetParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); if (forks <= 0 || forks >= urls.Count) { selected = urls; } else { selected = new List <URL>(); for (int i = 0; i < forks; i++) { //在invoker列表(排除selected)后,如果没有选够,则存在重复循环问题.见select实现. var invoker = base.select(loadbalance, invocation, urls, selected); if (!selected.Contains(invoker)) {//防止重复添加invoker selected.Add(invoker); } } } RpcContext.GetContext().SetInvokers(selected); var count = new AtomicInteger(); var taskList = new Task <IResult <T> > [selected.Count]; var index = 0; foreach (var invoker in selected) { var task = Task.Run(async() => { try { var client = await pool.GetClient(invoker); try { var refer = await client.Refer(); _source.WriteConsumerBefore(refer.Instance, invoker, invocation); var resultInner = await refer.Invoke <T>(invocation); _source.WriteConsumerAfter(invoker, invocation, resultInner); await pool.Recovery(client); goodUrls.Add(invoker); return(resultInner); } catch (Exception ex) { await pool.DestoryClient(client).ConfigureAwait(false); _source.WriteConsumerError(invoker, invocation, ex); throw ex; } } catch (Exception e) { badUrls.Add(new BadUrl { Url = invoker, BadTime = DateTime.Now, CurrentException = e }); int value = count.IncrementAndGet(); if (value >= selected.Count) { return(new RpcResult <T>(e)); } } return(null); }); taskList[index++] = task; } try { var retIndex = Task.WaitAny(taskList, timeout); var ret = await taskList[retIndex]; if (ret.HasException) { Exception e = ret.Exception; throw new RpcException(e is RpcException exception ? exception.Code : 0, "Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.Message, e.InnerException != null ? e.InnerException : e); } return(new ClusterResult <T>(ret, goodUrls, badUrls, null, false)); } catch (Exception e) { var exception = new RpcException("Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. Last error is: " + e.Message, e); return(new ClusterResult <T>(new RpcResult <T>(exception), goodUrls, badUrls, exception, true)); } }
public DomainFilter(URL domain_page) : this(domain_page.Domain) { }
public override List <IRCResponse> GetResponse(BotMessage message) { if (!Regex.IsMatch(message.Command, "^(pf)$", RegexOptions.IgnoreCase)) { return(null); } if (message.ParameterList.Count == 0) { if (pfList.Count > 0) { // Return a random thing return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, pfList[rand.Next(pfList.Count)], message.ReplyTo) }); } else { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "There is currently no Pathfinder data!", message.ReplyTo) }); } } switch (message.ParameterList[0].ToLower()) { case "add": // Adding something to the list string msg = message.Parameters.Substring(message.ParameterList[0].Length + 1); int index; lock (fileLock) { index = pfList.Count + 1; pfList.Add(index + ". " + msg); } SaveList(); return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "Message added at index " + index, message.ReplyTo) }); case "list": // Post the list to pastebin, give link string list = ""; foreach (string item in pfList) { list += item + "\n"; } string url = URL.Pastebin(list, "DesertBus Survivors' Pathfinder List", "10M", "text", "1"); return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "DB Pathfinder list posted: " + url + " (link expires in 10 mins)", message.ReplyTo) }); default: int number = 0; if (Int32.TryParse(message.ParameterList[0], out number)) { number -= 1; if (number >= 0 && number < pfList.Count) { return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, pfList[number], message.ReplyTo) }); } } // Number too large or small, or not a number at all return(new List <IRCResponse>() { new IRCResponse(ResponseType.Say, "Invalid number, range is 1-" + pfList.Count, message.ReplyTo) }); } }
public URL(URL par1Str, string var3, object var4) { throw new System.NotImplementedException(); }
public EmbedURLPtr(ref URL URL = default) { this.m_URLRef = new ptr <URL>(ref URL); }
private void Window_Loaded(object sender, RoutedEventArgs e) { URL.Focus(); URL.Select(URL.Text.Length, 0); }
public PafUserService(URL url) : base(url) { }
public URL(URL copyUrl) { Reset(); CopyFrom(copyUrl); }
/// <summary>Prepends a base IRI to the given relative IRI.</summary> /// <remarks>Prepends a base IRI to the given relative IRI.</remarks> /// <param name="base">the base IRI.</param> /// <param name="iri">the relative IRI.</param> /// <returns> /// the absolute IRI. /// TODO: the URL class isn't as forgiving as the Node.js url parser, /// we may need to re-implement the parser here to support the /// flexibility required /// </returns> private static string PrependBase(JToken baseobj, string iri) { // already an absolute IRI if (iri.IndexOf(":") != -1) { return(iri); } // parse base if it is a string URL @base; if (IsString(baseobj)) { @base = URL.Parse((string)baseobj); } else { // assume base is already a URL @base = baseobj.Value <URL>(); } URL rel = URL.Parse(iri); // start hierarchical part string hierPart = @base.protocol; if (!string.Empty.Equals(rel.authority)) { hierPart += "//" + rel.authority; } else { if (!string.Empty.Equals(@base.href)) { hierPart += "//" + @base.authority; } } // per RFC3986 normalize string path; // IRI represents an absolute path if (rel.pathname.IndexOf("/") == 0) { path = rel.pathname; } else { path = @base.pathname; // append relative path to the end of the last directory from base if (!string.Empty.Equals(rel.pathname)) { path = JsonLD.JavaCompat.Substring(path, 0, path.LastIndexOf("/") + 1); if (path.Length > 0 && !path.EndsWith("/")) { path += "/"; } path += rel.pathname; } } // remove slashes anddots in path path = URL.RemoveDotSegments(path, !string.Empty.Equals(hierPart)); // add query and hash if (!string.Empty.Equals(rel.query)) { path += "?" + rel.query; } if (!string.Empty.Equals(rel.hash)) { path += rel.hash; } string rval = hierPart + path; if (string.Empty.Equals(rval)) { return("./"); } return(rval); }
protected virtual void addURL(URL prm1) { }
/// <summary>Removes a base IRI from the given absolute IRI.</summary> /// <remarks>Removes a base IRI from the given absolute IRI.</remarks> /// <param name="base">the base IRI.</param> /// <param name="iri">the absolute IRI.</param> /// <returns>the relative IRI if relative to base, otherwise the absolute IRI.</returns> private static string RemoveBase(JToken baseobj, string iri) { URL @base; if (IsString(baseobj)) { @base = URL.Parse((string)baseobj); } else { @base = baseobj.Value <URL>(); } // establish base root string root = string.Empty; if (!string.Empty.Equals(@base.href)) { root += (@base.protocol) + "//" + @base.authority; } else { // support network-path reference with empty base if (iri.IndexOf("//") != 0) { root += "//"; } } // IRI not relative to base if (iri.IndexOf(root) != 0) { return(iri); } // remove root from IRI and parse remainder URL rel = URL.Parse(JsonLD.JavaCompat.Substring(iri, root.Length)); // remove path segments that match IList <string> baseSegments = _split(@base.normalizedPath, "/"); IList <string> iriSegments = _split(rel.normalizedPath, "/"); while (baseSegments.Count > 0 && iriSegments.Count > 0) { if (!baseSegments[0].Equals(iriSegments[0])) { break; } if (baseSegments.Count > 0) { baseSegments.RemoveAt(0); } if (iriSegments.Count > 0) { iriSegments.RemoveAt(0); } } // use '../' for each non-matching base segment string rval = string.Empty; if (baseSegments.Count > 0) { // don't count the last segment if it isn't a path (doesn't end in // '/') // don't count empty first segment, it means base began with '/' if ([email protected]("/") || string.Empty.Equals(baseSegments[0])) { baseSegments.RemoveAt(baseSegments.Count - 1); } for (int i = 0; i < baseSegments.Count; ++i) { rval += "../"; } } // prepend remaining segments rval += _join(iriSegments, "/"); // add query and hash if (!string.Empty.Equals(rel.query)) { rval += "?" + rel.query; } if (!string.Empty.Equals(rel.hash)) { rval += rel.hash; } if (string.Empty.Equals(rval)) { rval = "./"; } return(rval); }
protected virtual global::java.lang.Package definePackage(global::java.lang.String prm1, global::java.util.jar.Manifest prm2, URL prm3) { return(default(global::java.lang.Package)); }
/// <summary> /// Loads the option description file /// </summary> /// <param name="url"> URL of the option description file </param> /// <exception cref="MaltChainedException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void loadOptionDescriptionFile(java.net.URL url) throws org.maltparser.core.exception.MaltChainedException public virtual void loadOptionDescriptionFile(URL url) { optionDescriptions.parseOptionDescriptionXMLfile(url); }
private string ParseForumRow(XmlNode fNode, string Template, string GroupName) { string sForum = Template; int lasttopicid; int lastreplyid; int fid; string lastpostdate = fNode.Attributes["lastpostdate"].Value; DateTime lastReadDate = DateTime.Parse(fNode.Attributes["lastread"].Value); string viewRoles = fNode.Attributes["viewroles"].Value; string readRoles = fNode.Attributes["readroles"].Value; string forumname = fNode.Attributes["name"].Value; string hidden = fNode.Attributes["hidden"].Value; lasttopicid = int.Parse(fNode.Attributes["lasttopicid"].Value); lastreplyid = int.Parse(fNode.Attributes["lastreplyid"].Value); fid = int.Parse(fNode.Attributes["forumid"].Value); //TODO: Validate can view //sForum = sForum.Replace("[FORUMNAME]", "<af:link id=""hypForumName" & fid & """ navigateurl=""" & Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & fid}) & """ text=""" & forumname & """ runat=""server"" />") 'GetForumLink(forumname, PageId, True)) sForum = sForum.Replace("[FORUMNAME]", "<af:link id=\"hypForumName" + fid + "\" navigateurl=\"" + URL.ForForum(PageId, fid, string.Empty, forumname) + "\" text=\"" + forumname + "\" runat=\"server\" />"); //GetForumLink(forumname, PageId, True)) sForum = sForum.Replace("[FORUMNAMENOLINK]", forumname); sForum = sForum.Replace("[FORUMDESCRIPTION]", fNode.Attributes["desc"].Value); sForum = sForum.Replace("[TOTALTOPICS]", fNode.Attributes["totaltopics"].Value); sForum = sForum.Replace("[TOTALREPLIES]", fNode.Attributes["totalreplies"].Value); sForum = sForum.Replace("[DISPLAYNAME]", "<i class=\"fa fa-user fa-fw fa-blue\"></i> " + fNode.Attributes["lastpostauthorname"].Value); sForum = sForum.Replace("[LASTPOST]", "<asp:placeholder id=\"plhLastPost" + fid + "\" runat=\"server\">"); sForum = sForum.Replace("[/LASTPOST]", "</asp:placeholder>"); int intLength = 0; if ((sForum.IndexOf("[LASTPOSTSUBJECT:", 0) + 1) > 0) { int inStart = (sForum.IndexOf("[LASTPOSTSUBJECT:", 0) + 1) + 17; int inEnd = (sForum.IndexOf("]", inStart - 1) + 1); string sLength = sForum.Substring(inStart - 1, inEnd - inStart); intLength = Convert.ToInt32(sLength); } string ReplaceTag = "[LASTPOSTSUBJECT:" + intLength.ToString() + "]"; string sSubject = fNode.Attributes["lastpostsubject"].Value; if (lastreplyid == 0) { lastreplyid = lasttopicid; } sSubject = GetLastPostSubject(lastreplyid, lasttopicid, fid, sSubject, intLength); sForum = sForum.Replace(ReplaceTag, sSubject); if (sSubject == string.Empty) { sForum = sForum.Replace("[RESX:BY]", string.Empty); sForum = sForum.Replace("[LASTPOSTDATE]", string.Empty); } else { sForum = sForum.Replace("[LASTPOSTDATE]", lastpostdate); } //TODO: Properly check "canview" string sIcon = TemplateUtils.ShowIcon(true, fid, UserId, DateTime.Parse(lastpostdate), lastReadDate, lastreplyid); string sIconImage = "<img alt=\"" + forumname + "\" src=\"" + ThemePath + "images/" + sIcon + "\" />"; //sForum = sForum.Replace("[FORUMICON]", sIconImage); sForum = sForum.Replace("[FORUMICON]", "<div style=\"height:30px;margin=right:10px;\"><i class=\"fa fa-folder fa-2x fa-blue\"></i></div>"); sForum = sForum.Replace("[CSS:FORUMICON]", "affoldernorm"); sForum = sForum.Replace("[CSS:FORUMICONSM]", "affoldersmnorm"); //sForum = sForum.Replace("[FORUMICONSM]", sIconImage.Replace("folder", "folder16")); sForum = sForum.Replace("[FORUMICONSM]", ""); var xNodeList = ForumData.SelectNodes("//forums/forum[@active='true' and @parentforumid='" + fid + "']"); string sSubs = string.Empty; if (xNodeList.Count > 0) { string sTemplate = TemplateUtils.GetTemplateSection(Template, "[SUBFORUMS]", "[/SUBFORUMS]"); foreach (XmlNode n in xNodeList) { sSubs += ParseForumRow(n, sTemplate, GroupName); } } sForum = TemplateUtils.ReplaceSubSection(sForum, sSubs, "[SUBFORUMS]", "[/SUBFORUMS]"); string fc = "<af:forumrow id=\"ctlFR" + fid + "\" Hidden=\"" + hidden + "\" ForumId=\"" + fid + "\" ReadRoles=\"" + readRoles + "\" ViewRoles=\"" + viewRoles + "\" runat=\"server\">"; fc += "<content>" + sForum + "</content>"; fc += "</af:forumrow>"; return(fc); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Org.Apache.Hadoop.Yarn.Exceptions.YarnException"/> /// <exception cref="System.Exception"/> public virtual void TestClearLocalDirWhenNodeReboot() { nm = new TestNodeManagerReboot.MyNodeManager(this); nm.Start(); ContainerManagementProtocol containerManager = nm.GetContainerManager(); // create files under fileCache CreateFiles(nmLocalDir.GetAbsolutePath(), ContainerLocalizer.Filecache, 100); localResourceDir.Mkdirs(); ContainerLaunchContext containerLaunchContext = Records.NewRecord <ContainerLaunchContext >(); // Construct the Container-id ContainerId cId = CreateContainerId(); URL localResourceUri = ConverterUtils.GetYarnUrlFromPath(localFS.MakeQualified(new Path(localResourceDir.GetAbsolutePath()))); LocalResource localResource = LocalResource.NewInstance(localResourceUri, LocalResourceType .File, LocalResourceVisibility.Application, -1, localResourceDir.LastModified()); string destinationFile = "dest_file"; IDictionary <string, LocalResource> localResources = new Dictionary <string, LocalResource >(); localResources[destinationFile] = localResource; containerLaunchContext.SetLocalResources(localResources); IList <string> commands = new AList <string>(); containerLaunchContext.SetCommands(commands); NodeId nodeId = nm.GetNMContext().GetNodeId(); StartContainerRequest scRequest = StartContainerRequest.NewInstance(containerLaunchContext , TestContainerManager.CreateContainerToken(cId, 0, nodeId, destinationFile, nm. GetNMContext().GetContainerTokenSecretManager())); IList <StartContainerRequest> list = new AList <StartContainerRequest>(); list.AddItem(scRequest); StartContainersRequest allRequests = StartContainersRequest.NewInstance(list); UserGroupInformation currentUser = UserGroupInformation.CreateRemoteUser(cId.GetApplicationAttemptId ().ToString()); NMTokenIdentifier nmIdentifier = new NMTokenIdentifier(cId.GetApplicationAttemptId (), nodeId, user, 123); currentUser.AddTokenIdentifier(nmIdentifier); currentUser.DoAs(new _PrivilegedExceptionAction_152(this, allRequests)); IList <ContainerId> containerIds = new AList <ContainerId>(); containerIds.AddItem(cId); GetContainerStatusesRequest request = GetContainerStatusesRequest.NewInstance(containerIds ); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Container.Container container = nm.GetNMContext().GetContainers()[request.GetContainerIds()[0]]; int MaxTries = 20; int numTries = 0; while (!container.GetContainerState().Equals(ContainerState.Done) && numTries <= MaxTries) { try { Sharpen.Thread.Sleep(500); } catch (Exception) { } // Do nothing numTries++; } NUnit.Framework.Assert.AreEqual(ContainerState.Done, container.GetContainerState( )); NUnit.Framework.Assert.IsTrue("The container should create a subDir named currentUser: "******"under localDir/usercache", NumOfLocalDirs(nmLocalDir.GetAbsolutePath( ), ContainerLocalizer.Usercache) > 0); NUnit.Framework.Assert.IsTrue("There should be files or Dirs under nm_private when " + "container is launched", NumOfLocalDirs(nmLocalDir.GetAbsolutePath(), ResourceLocalizationService .NmPrivateDir) > 0); // restart the NodeManager RestartNM(MaxTries); CheckNumOfLocalDirs(); Org.Mockito.Mockito.Verify(delService, Org.Mockito.Mockito.Times(1)).Delete((string )Matchers.IsNull(), Matchers.ArgThat(new TestNodeManagerReboot.PathInclude(this, ResourceLocalizationService.NmPrivateDir + "_DEL_"))); Org.Mockito.Mockito.Verify(delService, Org.Mockito.Mockito.Times(1)).Delete((string )Matchers.IsNull(), Matchers.ArgThat(new TestNodeManagerReboot.PathInclude(this, ContainerLocalizer.Filecache + "_DEL_"))); Org.Mockito.Mockito.Verify(delService, Org.Mockito.Mockito.Times(1)).ScheduleFileDeletionTask (Matchers.ArgThat(new TestNodeManagerReboot.FileDeletionInclude(this, user, null , new string[] { destinationFile }))); Org.Mockito.Mockito.Verify(delService, Org.Mockito.Mockito.Times(1)).ScheduleFileDeletionTask (Matchers.ArgThat(new TestNodeManagerReboot.FileDeletionInclude(this, null, ContainerLocalizer .Usercache + "_DEL_", new string[] { }))); // restart the NodeManager again // this time usercache directory should be empty RestartNM(MaxTries); CheckNumOfLocalDirs(); }