def ExecuteFileInScope(self, filename, moduleEO): try: f = StreamReader(filename) runtime.DynamicObjectHelpers.SetMember(moduleEO, "__file__", Path.GetFullPath(filename)) ASTs = parser.ParseFile(f) self.dbgASTs = ASTs scope = etgen.AnalysisScope( None, #parent filename, self, Exprs.Expression.Parameter(Sympl, "symplRuntime"), Exprs.Expression.Parameter(ExpandoObject, "fileModule")) self.dbgascope = scope body = [] self.dbgbody = body for e in ASTs: body.append(etgen.AnalyzeExpr(e, scope)) ## Use ftype with void return so that lambda ignores body result. ftype = Exprs.Expression.GetActionType( System.Array[System.Type]([Sympl, ExpandoObject])) ## Due to .NET 4.0 co/contra-variance, IPy's binding isn't picking ## the overload with just IEnumerable<Expr>, so pick it explicitly. body = Exprs.Expression.Block.Overloads[IEnumerable[ Exprs.Expression]](body) modulefun = Exprs.Expression.Lambda(ftype, body, scope.RuntimeExpr, scope.ModuleExpr) dbgmodfun = modulefun modulefun.Compile()(self, moduleEO) finally: f.Close()
def get_html_string(url): ''' This method takes a url (string) of a webpage, and connects to the URL, then downloads, htmldecodes, and returns the contents of that page as an html string. This method will throw an WebException or IOException if anything goes wrong, including if the response code is not valid (i.e. 200). ''' try: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 request = WebRequest.Create(url) request.UserAgent = "[ComicVineScraper, version " + \ Resources.SCRIPT_VERSION + "]" response = request.GetResponse() # if the response code is not "OK", throw a web exception immediately. # this stops red-herring errors later on as we try to parse bad results. # usually this only happens if the CV server is temporarily down. if response.StatusCode != HttpStatusCode.OK: raise WebException("server response code " + sstr(int(response.StatusCode)) + " (" + sstr(response.StatusCode) + ")") responseStream = response.GetResponseStream() reader = StreamReader(responseStream, Encoding.UTF8) page = reader.ReadToEnd() with StringWriter() as writer: HttpUtility.HtmlDecode(page, writer) page = writer.ToString() return page finally: if 'reader' in vars(): reader.Close() if 'responseStream' in vars(): responseStream.Close() if 'response' in vars(): response.Close()
def onUpdate(): shortenedUri = None if NetworkInterface.GetIsNetworkAvailable(): try: request = WebRequest.Create(Uri(String.Concat("http://nazr.in/api/shorten.json?url=", urlEncode(uri.ToString())))) response = None stream = None streamReader = None try: response = request.GetResponse() stream = response.GetResponseStream() streamReader = StreamReader(stream) jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd()) if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("url"): shortenedUri = Uri(jsonDictionary["url"]) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def LoadFile(filename): store = IsolatedStorageFile.GetUserStoreForApplication() isolatedStream = IsolatedStorageFileStream(filename, FileMode.Open, store) reader = StreamReader(isolatedStream) data = reader.ReadToEnd() reader.Close() isolatedStream.Close() return data
def getNumberOfSpeakers(): vm = ViewModel(Application.Current.MainWindow.DataContext.Speakers.Length) stream = Application.Current.GetType().Assembly.GetManifestResourceStream( "IronPython.UI.Scripts.ResultWindow.xaml") reader = StreamReader(stream) window = XamlReader.Parse(reader.ReadToEnd()) reader.Close() stream.Close() window.DataContext = vm window.FindName("CloseButton").Click += lambda s, e: window.Close() window.Show()
def alternateLoadMasterPluginIndex(): import System, System.Windows.Forms from System.IO import Path, File, StreamReader from System import Environment p = [] r = StreamReader(file) while 1: t = r.ReadLine() if t == None: break p.append(t) r.Close()
def rsnrequest(): request = WebRequest.Create(file_link) request.Method = "GET" request.UserAgent = "Anything" # Token scenario for closed repositories #token = '' #request.Headers["OAUTH-TOKEN"] = token rsp = request.GetResponse() stream_reader = StreamReader(rsp.GetResponseStream()) jsonData = stream_reader.ReadToEnd() stream_reader.Close() json = JavaScriptSerializer().DeserializeObject(jsonData) return json
def create_user_control(filename): userControl = None try: s = None if filename: s = StreamReader(filename) userControl = XamlReader.Load(s.BaseStream) except Exception as e: CommonUtil.sprint("Failed to Create UserControl: {}".format(e)) finally: if s: s.Close() s.Dispose() return userControl
def onSave(): try: fs = None sr = None sw = None try: fs = FileStream(__file__, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) encoding = UTF8Encoding(False) sr = StreamReader(fs, encoding, True) lines = Regex.Replace( Regex.Replace( sr.ReadToEnd(), "username\\s*=\\s*\"\"", String.Format("username = \"{0}\"", username), RegexOptions.CultureInvariant), "password\\s*=\\s*\"\"", String.Format("password = \"{0}\"", password), RegexOptions.CultureInvariant) fs.SetLength(0) sw = StreamWriter(fs, encoding) sw.Write(lines) finally: if sw is not None: sw.Close() if sr is not None: sr.Close() if fs is not None: fs.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def load_regex_from_file(regex_file): """Loads the regex from the specified xml file""" file = StreamReader(regex_file) xml = XmlDocument() xml.Load(file) file.Close() nodes = xml.SelectNodes("WebComicHelper/ImageRegex") images = [] for node in nodes: images.append(ImageRegex(node.InnerText)) nodes = xml.SelectNodes("WebComicHelper/LinkRegex") links = [] for node in nodes: links.append(LinkRegex(node.InnerText)) nodes = xml.SelectNodes("WebComicHelper/Site") sites = [] for node in nodes: sites.append( SiteRegex( node.SelectSingleNode("ImageRegex").InnerText, node.SelectSingleNode("LinkRegex").InnerText, node.SelectSingleNode("Domain").InnerText)) return images, links, sites
def get_html_string(url): ''' This method takes a url (string) of a webpage, and connects to the URL, then downloads, htmldecodes, and returns the contents of that page as an html string. This method will throw an WebException or IOException if anything goes wrong, including if the response code is not valid (i.e. 200). ''' try: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 request = WebRequest.Create(url) # latest version of comicvine api insists on a user agent (see bug #484). # previously, it didn't like my non-standard user agent, I think (see bug #471). # now, I have a standard user agent, which comicvine api seems to like. request.UserAgent = "ComicVineScraper/" + \ Resources.SCRIPT_VERSION + " (https://github.com/cbanack/comic-vine-scraper/)" response = request.GetResponse() # if the response code is not "OK", throw a web exception immediately. # this stops red-herring errors later on as we try to parse bad results. # usually this only happens if the CV server is temporarily down. if response.StatusCode != HttpStatusCode.OK: raise WebException("server response code " + sstr(int(response.StatusCode))+" ("+sstr(response.StatusCode)+")" ) responseStream = response.GetResponseStream() reader = StreamReader(responseStream, Encoding.UTF8) page = reader.ReadToEnd() with StringWriter() as writer: HttpUtility.HtmlDecode(page, writer) page = writer.ToString() return page finally: if 'reader' in vars(): reader.Close() if 'responseStream' in vars(): responseStream.Close() if 'response' in vars(): response.Close()
def onUpdate(): temp = 0 windSpeed = 0 windDeg = 0 weatherIdList = List[Double]() weatherPathHashSet = HashSet[String]() weatherStreamList = List[MemoryStream]() weatherConditionList = List[String]() if NetworkInterface.GetIsNetworkAvailable(): try: request = WebRequest.Create(Uri(String.Concat("http://api.openweathermap.org/data/2.5/find?q=", urlEncode(location), "&units=metric&cnt=1"))) response = None stream = None streamReader = None try: nowDateTime = DateTime.Now response = request.GetResponse() stream = response.GetResponseStream() streamReader = StreamReader(stream) jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd()) if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("list") and jsonDictionary["list"] is not None and clr.GetClrType(Array).IsInstanceOfType(jsonDictionary["list"]): for obj in jsonDictionary["list"]: if obj is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj): if obj.ContainsKey("main") and obj["main"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["main"]) and obj["main"].ContainsKey("temp"): temp = obj["main"]["temp"] if obj.ContainsKey("wind") and obj["wind"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["wind"]): if obj["wind"].ContainsKey("speed"): windSpeed = obj["wind"]["speed"] if obj["wind"].ContainsKey("deg"): windDeg = obj["wind"]["deg"] if obj.ContainsKey("weather") and obj["weather"] is not None and clr.GetClrType(Array).IsInstanceOfType(obj["weather"]): for o in obj["weather"]: if o is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(o) and o.ContainsKey("id") and o["id"] is not None: weatherIdList.Add(o["id"]) for id in weatherIdList: digit = Convert.ToInt32(id / 100) path = None s = None if digit == 2: path = "Assets\\Cloud-Lightning.png" weatherConditionList.Add("Thunderstorm") elif digit == 3: path = "Assets\\Cloud-Drizzle.png" weatherConditionList.Add("Drizzle") elif digit == 5: d = Convert.ToInt32(id / 10) if d == 0: if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18: path = "Assets\\Cloud-Rain-Sun.png" else: path = "Assets\\Cloud-Rain-Moon.png" else: path = "Assets\\Cloud-Rain.png" weatherConditionList.Add("Rain") elif digit == 6: path = "Assets\\Cloud-Snow.png" weatherConditionList.Add("Snow") elif digit == 7: path = "Assets\\Cloud-Fog.png" if Convert.ToInt32(id) == 701: weatherConditionList.Add("Mist") elif Convert.ToInt32(id) == 711: weatherConditionList.Add("Smoke") elif Convert.ToInt32(id) == 721: weatherConditionList.Add("Haze") elif Convert.ToInt32(id) == 731: weatherConditionList.Add("Dust") elif Convert.ToInt32(id) == 741: weatherConditionList.Add("Fog") elif digit == 8: if Convert.ToInt32(id) == 800: if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18: path = "Assets\\Sun.png" weatherConditionList.Add("Sunny") else: path = "Assets\\Moon.png" weatherConditionList.Add("Clear") elif Convert.ToInt32(id) >= 801 and Convert.ToInt32(id) <= 803: if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18: path = "Assets\\Cloud-Sun.png" else: path = "Assets\\Cloud-Moon.png" weatherConditionList.Add("Cloudy") elif Convert.ToInt32(id) == 804: path = "Assets\\Cloud.png" weatherConditionList.Add("Overcast") else: if Convert.ToInt32(id) == 900: path = "Assets\\Tornado.png" weatherConditionList.Add("Tornado") elif Convert.ToInt32(id) == 905: path = "Assets\\Wind.png" weatherConditionList.Add("Windy") elif Convert.ToInt32(id) == 906: path = "Assets\\Cloud-Hail.png" weatherConditionList.Add("Hail") if path is not None and weatherPathHashSet.Contains(path) == False: fs = None try: fs = FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read) ms = MemoryStream() buffer = Array.CreateInstance(Byte, fs.Length) bytesRead = fs.Read(buffer, 0, buffer.Length) while bytesRead > 0: ms.Write(buffer, 0, bytesRead) bytesRead = fs.Read(buffer, 0, buffer.Length) ms.Seek(0, SeekOrigin.Begin) weatherStreamList.Add(ms) finally: if fs is not None: fs.Close() weatherPathHashSet.Add(path) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def onDispatch(task): global httpListener if task.Exception is None: httpListener.GetContextAsync().ContinueWith[List[Entry]]( Func[Task[HttpListenerContext], List[Entry]](onDispatch), TaskContinuationOptions.LongRunning).ContinueWith( Action[Task[List[Entry]]](onCompleted), context) try: if task.Result.Request.HttpMethod.Equals( WebRequestMethods.Http.Post ) and task.Result.Request.Url.AbsolutePath.Equals( "/alert"): if task.Result.Request.ContentType.Equals( "application/json"): stream = None streamReader = None try: stream = task.Result.Request.InputStream streamReader = StreamReader(stream) jsonArray = JsonDecoder.decode( streamReader.ReadToEnd()) if jsonArray is not None and clr.GetClrType( Array).IsInstanceOfType(jsonArray): entryList = List[Entry]() for obj in jsonArray: if clr.GetClrType(Dictionary[ String, Object]).IsInstanceOfType(obj): entry = Entry() if obj.ContainsKey( "resource" ) and clr.GetClrType( String).IsInstanceOfType( obj["resource"]): entry.Resource = Uri( obj["resource"]) if obj.ContainsKey( "title" ) and clr.GetClrType( String).IsInstanceOfType( obj["title"]): entry.Title = obj["title"] if obj.ContainsKey( "description" ) and clr.GetClrType( String).IsInstanceOfType( obj["description"]): entry.Description = obj[ "description"] if obj.ContainsKey( "author" ) and clr.GetClrType( String).IsInstanceOfType( obj["author"]): entry.Author = obj["author"] if obj.ContainsKey( "created" ) and clr.GetClrType( String).IsInstanceOfType( obj["created"]): entry.Created = DateTime.Parse( obj["created"]) if obj.ContainsKey( "modified" ) and clr.GetClrType( String).IsInstanceOfType( obj["modified"]): entry.Modified = DateTime.Parse( obj["modified"]) if obj.ContainsKey( "image" ) and clr.GetClrType( String).IsInstanceOfType( obj["image"]): entry.Image = Uri(obj["image"]) if obj.ContainsKey( "tags") and clr.GetClrType( Array ).IsInstanceOfType( obj["tags"]): for o in obj["tags"]: if clr.GetClrType( String ).IsInstanceOfType(o): entry.Tags.Add(o) entryList.Add(entry) else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.BadRequest) return None return entryList else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.BadRequest) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.UnsupportedMediaType) else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.Forbidden) except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace) finally:
except (ArgumentNullException, System.Security.SecurityException), ex: self._exception = ex return False try: responsestream = request.GetResponse() except (System.Security.SecurityException, WebException), ex: self._exception = ex return False try: streamreader = StreamReader(responsestream.GetResponseStream()) self._source = streamreader.ReadToEnd() except (ArgumentException, ProtocolViolationException), ex: self._exception = ex success = False finally: responsestream.Close() streamreader.Close() return success