def serialize(self, document, indent=False, encoding=bridge.ENCODING, prefixes=None, omit_declaration=False): doc = XmlDocument() doc.LoadXml(self.__start_document(document)) if document.xml_text: doc.DocumentElement.AppendChild( doc.CreateTextNode(document.xml_text)) self.__serialize_element(doc, doc.DocumentElement, document) settings = XmlWriterSettings() settings.Indent = indent settings.Encoding = Encoding.GetEncoding(encoding) settings.OmitXmlDeclaration = omit_declaration ms = MemoryStream() xw = XmlWriter.Create(ms, settings) doc.Save(xw) sr = StreamReader(ms) ms.Seek(0, SeekOrigin.Begin) content = sr.ReadToEnd() ms.Close() return content
def table_text_writer(list_input): """Writes table input args: list_input (list of lists): input to be written returns: stream """ from System.IO import StreamWriter, MemoryStream, SeekOrigin list_input = controlled_list(list_input) LOGGER.debug(list_input) LOGGER.debug('--------') header = controlled_list(list_input.pop(0)) length_of_header = len(header) head_line = create_line(header) # if only a header line if not list_input: text = ' ' * (length_of_header) else: text ='' LOGGER.debug('Loop') for i, text_list in enumerate(list_input): text_list = controlled_list(text_list) LOGGER.debug(text_list) if len(text_list) != length_of_header: message = ('Line {} in text: [{}] does not have ' + ' same length as header [{}], will be ' + 'skipped').format(i, join_list(text_list), join_list(header)) ok_message(message) else: text += create_line(text_list) text = head_line + text stream = MemoryStream() writer = StreamWriter(stream) writer.Write(text) writer.Flush() stream.Seek(0, SeekOrigin.Begin) return stream
def csvToDataSource(csv, columnDataTypes): # Create memorystream to read from stream = MemoryStream() writer = StreamWriter(stream) writer.Write(csv) writer.Flush() stream.Seek(0, SeekOrigin.Begin) # Create text file data source readerSettings = TextDataReaderSettings() readerSettings.Separator = ',' readerSettings.AddColumnNameRow(0) print 'columnDataTypes ', columnDataTypes for i, columnDataType in enumerate(columnDataTypes): readerSettings.SetDataType(i, columnDataType) dataSource = TextFileDataSource(stream, readerSettings) dataSource.ReuseSettingsWithoutPrompting = True dataSource.IsPromptingAllowed = False return dataSource
# Create a web client client = WebClient() # Download the results of that URL results = client.DownloadString("http://localhost:8888/spotfireFramework/assetMarketPlace/customLibs/visTimeline/dxp/eventsGroup.csv") # print these results print results stream = MemoryStream() writer = StreamWriter(stream) writer.Write(results) writer.Flush() stream.Seek(0, SeekOrigin.Begin) readerSettings = TextDataReaderSettings() readerSettings.Separator = "," readerSettings.AddColumnNameRow(0) readerSettings.SetDataType(0, DataType.String) readerSettings.SetDataType(1, DataType.String) readerSettings.SetDataType(2, DataType.DateTime) readerSettings.SetDataType(3, DataType.DateTime) readerSettings.SetDataType(4, DataType.String) readerSettings.SetDataType(5, DataType.String) readerSettings.SetDataType(6, DataType.String) dSource = TextFileDataSource(stream, readerSettings) if Document.Data.Tables.Contains("timelineEvents"):
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)
except Exception, e: continue finally: if fs is not None: fs.Close() ms = None fs = None try: ms = MemoryStream() characters = Array.CreateInstance(Character, 1) characters[0] = characterList[Random(Environment.TickCount).Next( characterList.Count)] serializer = XmlSerializer(characters.GetType()) serializer.Serialize(ms, characters) ms.Seek(0, SeekOrigin.Begin) fs = FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read) buffer = ms.ToArray() fs.Write(buffer, 0, buffer.Length) fs.Flush() finally: if fs is not None: fs.Close() if ms is not None: ms.Close()
def onLoad(): streamList1 = List[MemoryStream]() streamList2 = List[MemoryStream]() for i in range(10): ms = None fs = None try: fs = FileStream( String.Format("Assets\\Number-{0}.png", i.ToString( CultureInfo.InvariantCulture)), 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) streamList1.Add(ms) except: if ms is not None: ms.Close() ms = None finally: if fs is not None: fs.Close() for path in [ "Assets\\Hour.png", "Assets\\Minute.png", "Assets\\Second.png" ]: ms = None 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) streamList2.Add(ms) except: if ms is not None: ms.Close() ms = None finally: if fs is not None: fs.Close() return KeyValuePair[List[MemoryStream], List[MemoryStream]](streamList1, streamList2)