def __init__(self, **kwargs): super(NewFocus6700, self).__init__() # Load usb ddl Newport try: # dllpath = 'C:\\ProgramData\\Anaconda3\\DLLs\\' # dllpath = 'C:\\Users\\Greg\\Anaconda3\\DLLs\\' dllpath = 'C:\\ProgramData\\Anaconda3\\DLLs\\' Assembly.LoadFile(dllpath + 'UsbDllWrap.dll') clr.AddReference(r'UsbDllWrap') import Newport self._dev = Newport.USBComm.USB() except Exception as err: print(err) self._dev = None # Laser state self._open = False self._DeviceKey = kwargs.get('key', None) self._idLaser = kwargs.get('id', 4106) # Laser properties self._lbd = '0' self._cc = 0 self._scan_lim = [] self._scan_speed = 0 self._scan = 0 self._beep = 0 self._output = 0 self._is_scaning = False # self._is_changing_lbd = False self._no_error = '0,"NO ERROR"' self._haserr = False # Miscs self._buff = StringBuilder(64) self._err_msg = ''
def __init__(self, maxsize): self._maxsize = maxsize self._data = Array.CreateInstance(System.Byte, self._maxsize) Random().NextBytes(self._data) self._log = StringBuilder() self._currentoffset = 0 self._currentlength = 0
def __serialize_to_xml__(iaddin_custom_frame_instance, file_full_name): done = False try: sb = StringBuilder() xml_writer_settings = XmlWriterSettings() xml_writer_settings.Indent = True xml_writer_settings.ConformanceLevel = ConformanceLevel.Fragment xml_writer_settings.OmitXmlDeclaration = True writer = None try: writer = XmlWriter.Create(sb, xml_writer_settings) if writer: mgr = XamlDesignerSerializationManager(writer) if mgr: mgr.XamlWriterMode = XamlWriterMode.Expression XamlWriter.Save(iaddin_custom_frame_instance, mgr) filewriter = None try: filewriter = File.CreateText(file_full_name) if filewriter: filewriter.Write(sb.ToString()) done = True finally: if filewriter: filewriter.Dispose() filewriter = None finally: if writer: writer.Dispose() writer = None except Exception as e: CommonUtil.sprint("Failed to serialize: {}".format(e)) done = False return done
def showOutPut(self): if outPuts.Count != 0: sb = StringBuilder() for s in outPuts: sb.Append(s) TaskDialog.Show("Name Updated", sb.ToString()) else: TaskDialog.Show("Name Updated", "nothing updated")
def GetExceptionDetails(exception): exceptionDetails = StringBuilder() def output(message=""): exceptionDetails.AppendLine(message) return LogOutputErrorDetails(exception, output) return exceptionDetails.ToString()
def CmdOutputDataHandler(process, outline): strOutput = StringBuilder() strOutput.Append(outline.Data) if not outline.Data: print(0, " ") wtr.WriteLine(" ") else: print(outline.Data.Length, outline.Data) wtr.WriteLine(outline.Data)
def urlEncode(value): unreserved = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~" sb = StringBuilder() bytes = Encoding.UTF8.GetBytes(value) for b in bytes: if b < 0x80 and unreserved.IndexOf(Convert.ToChar(b)) != -1: sb.Append(Convert.ToChar(b)) else: sb.Append('%' + String.Format("{0:X2}", Convert.ToInt32(b))) return sb.ToString()
def parseNumber(json, index, success): index = JsonDecoder.skipWhitespace(json, index) lastIndex = JsonDecoder.getLastIndexOfNumber(json, index) charLength = (lastIndex - index) + 1 sb = StringBuilder() for i in range(charLength): sb.Append(json[index + i]) success, number = Double.TryParse(sb.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture) index = lastIndex + 1 return number, index, success
def modifyNPCWeights(records): """ Modify NPC Weight to lower with distribution around 35% """ from System import Predicate from System.Text import StringBuilder from System.Text.RegularExpressions import Regex sb = StringBuilder() #types = set(('NPC_',)) masterIdx = loadMasterPluginIndex() # build dictionary of masters #matchType = Predicate[BaseRecord](lambda rec: (isinstance(rec, Plugin) or isinstance(rec,GroupRecord) or (isinstance(rec,Record) and rec.Name in types))) for plugin in records: lowerName = plugin.Name.lower() pluginIdMap = buildPluginMasterIndexMap( plugin, masterIdx) # build dictionary of masters. invalid map to 0xFF pluginidx = masterIdx.get(lowerName, 255) & 0xFF first = True pluginID = plugin.GetMasters().Length for rec in plugin.GetRecordList('NPC_'): itemMaster = (rec.FormID & 0xFF000000) >> 24 formid = translateRecordID(rec, pluginIdMap) if first: sb.AppendFormat("\n; [{0:X2}] {1}\n", pluginidx, plugin.DescriptiveName) first = False try: fullname = getTrimFullName(rec) weight = getWeight(rec) print weight if not weight or weight >= 10: # leave alone newweight = rnorminv( 35, 20, 0, 100 ) # generate random value between 0 and 100 centered around 35 with sigma of 20 if not newweight: newweight = rnorminv(35, 20, 0, 100) # try again setWeight(rec, newweight) sb.AppendFormat( "{0:X8}.SetNPCWeight {4} ; {3} \t{1} \t{2} \n", formid, rec.DescriptiveName, fullname, weight, newweight) except Exception, e: print str(e) pass
def doc_to_text(filename): word_application = Word.ApplicationClass() word_application.visible = False document = word_application.Documents.Open(filename) result = StringBuilder() for p in document.Paragraphs: result.Append(clean_text(p.Range.Text)) document.Close() document = None word_application.Quit() word_application = None return result.ToString()
def listNPCWeights(records): from System import Predicate from System.Text import StringBuilder from System.Text.RegularExpressions import Regex sb = StringBuilder() masterIdx = loadMasterPluginIndex() # build dictionary of masters #types = set(('NPC_',)) #matchType = Predicate[BaseRecord](lambda rec: (isinstance(rec, Plugin) # or isinstance(rec,GroupRecord) or (isinstance(rec,Record) and rec.Name in types))) for plugin in records: lowerName = plugin.Name.lower() # Build master map with invalid masters mapping to 0xFF pluginIdMap = buildPluginMasterIndexMap(plugin, masterIdx) pluginidx = masterIdx.get(lowerName, 255) & 0xFF first = True pluginID = plugin.GetMasters().Length for rec in plugin.GetRecordList('NPC_'): itemMaster = (rec.FormID & 0xFF000000) >> 24 formid = translateRecordID(rec, pluginIdMap) if first: sb.AppendFormat("\n; [{0:X2}] {1}\n", pluginidx, plugin.DescriptiveName) first = False try: fullname = getTrimFullName(rec) weight = getWeight(rec) scale = getScale(rec) sb.AppendFormat("{0:X8}.SetNPCWeight {3} ; {1} \t{2}\n", formid, rec.DescriptiveName, fullname, weight) # if scale <> 1.0 and scale <> None: # sb.AppendFormat("{0:X8}.SetScale {3} ; {1} \t{2}\n", # formid, rec.DescriptiveName, fullname, weight # ) except Exception, e: print str(e) pass
def generateItemList(records): from System.Text import StringBuilder reWhite = Regex( r"[\n\t\r]" ) # can probably use re but user might not have full IronPython sb = StringBuilder() masterIdx = loadMasterPluginIndex() types = set(("ARMO", "WEAP", "MISC", "AMMO", "KEYM")) #matchType = Predicate[BaseRecord](lambda rec: (isinstance(rec, Plugin) or isinstance(rec,GroupRecord) or (isinstance(rec,Record) and rec.Name in types))) for plugin in records: lowerName = plugin.Name.lower() if lowerName == 'rbs.esp': continue # skip this mod since its huge and not very interesting here pluginidx = masterIdx.get(lowerName, 255) & 0xFF first = True pluginID = plugin.GetMasters().Length for rec in plugin.GetRecordList(types): itemMaster = (rec.FormID & 0xFF000000) >> 24 if itemMaster != pluginID: # not interested in overrides continue if first: sb.AppendFormat("\n; [{0:X2}] {1}\n", pluginidx, plugin.DescriptiveName) first = False fullname = getTrimFullName(rec) sb.AppendFormat("player.additem {0:X2}{1:X6} 1 ; {2} \t{3}\n", pluginidx, rec.FormID & 0x00FFFFFF, rec.DescriptiveName, fullname) return sb.ToString()
def GetObservedTimeseries(dictObsSensors, startDate, endDate, outputPath, log): try: key = 0 connection = SqlClient.SqlConnection(strObservedDB) connection.Open() for key, value in dictObsSensors.iteritems(): strSQL = 'SELECT SAMPLES.DT, SAMPLES.SAMPLEVALUE, SAMPLES.POINT ' strSQL = strSQL + ' FROM HydroTel.dbo.SAMPLES SAMPLES ' strSQL = strSQL + ' WHERE (SAMPLES.DT>=CONVERT(DATETIME,\'' + startDate.strftime( pyDTFormat) + '\',102)) ' strSQL = strSQL + ' AND (SAMPLES.DT<=CONVERT(DATETIME,\'' + endDate.strftime( pyDTFormat) + '\',102)) ' strSQL = strSQL + ' AND (SAMPLES.POINT=' + key.ToString( ) + ') ORDER BY SAMPLES.DT' cmd = SqlClient.SqlCommand(strSQL, connection) reader = cmd.ExecuteReader() strData = StringBuilder() while (reader.Read()): theTime = reader[0] theValue = reader[1] strData.Append(theTime.ToString(netDTFormat) + ',') if theValue == iDeleteValue: strData.Append('-1E-30\n') else: strData.Append(str(theValue) + '\n') reader.Close() if strData.Length > 0: # Write to file f = open(outputPath + "\\Observed\\" + value + ".txt", 'w') f.write("Time," + value + "\n") f.write(strData.ToString()) f.close() log.write("Data import success for sensor id: " + str(int(key)) + " " + value + "\n") else: log.write("No data for sensor id: " + str(int(key)) + " " + value + "!!!!\n") connection.Close() except: if key == 0: exceptionMessage = "Failed to connect to database. Connecton string: " + strObservedDB + "\n" else: exceptionMessage = "Data import failed for sensor id: " + str( int(key)) + " " + value + "!!!!\n" log.write(exceptionMessage) raise
def WithErrorHandling(action, errorMessage, output=None, showErrorMessageBox=False): result = None try: result = action() except Exception, e: if output is not None: output() output(errorMessage) exception_util.LogOutputErrorDetails(e, output) if showErrorMessageBox: fullErrorMessage = StringBuilder() fullErrorMessage.AppendLine(errorMessage) fullErrorMessage.AppendLine() fullErrorMessage.AppendLine(exception_util.GetExceptionDetails(e)) ShowScriptErrorMessageBox(fullErrorMessage.ToString()) SetDataInCurrentDomain(SCRIPT_HOST_ERROR_DATA_VARIABLE, e)
def getTermList(dictionary, text): stringBuilder = StringBuilder(text) selectedTermList = List[String]() while stringBuilder.Length > 0: s1 = stringBuilder.ToString() selectedTerm1 = None if dictionary.ContainsKey(s1[0]): for term in dictionary[s1[0]]: if s1.StartsWith(term, StringComparison.Ordinal) and term.Length > ( 0 if selectedTerm1 is None else selectedTerm1.Length): selectedTerm1 = term if String.IsNullOrEmpty(selectedTerm1): stringBuilder.Remove(0, 1) else: sb = StringBuilder( stringBuilder.ToString(1, stringBuilder.Length - 1)) selectedTerm2 = None i = 0 max = 0 while sb.Length > 0 and i < selectedTerm1.Length: s2 = sb.ToString() if dictionary.ContainsKey(s2[0]): for term in dictionary[s2[0]]: if s2.StartsWith( term, StringComparison.Ordinal ) and term.Length > (0 if selectedTerm2 is None else selectedTerm2.Length): selectedTerm2 = term max = i + selectedTerm2.Length sb.Remove(0, 1) i += 1 if not String.IsNullOrEmpty( selectedTerm2 ) and selectedTerm1.Length < selectedTerm2.Length: if not selectedTermList.Contains(selectedTerm2): selectedTermList.Add(selectedTerm2) stringBuilder.Remove(0, max) else: if not selectedTermList.Contains(selectedTerm1): selectedTermList.Add(selectedTerm1) stringBuilder.Remove(0, selectedTerm1.Length) return selectedTermList
def DialogShowingEventHandler(sender, eventArgs, output): try: dialogResult = IDOK msg = StringBuilder() msg.AppendLine() msg.AppendLine("Dialog box shown:") msg.AppendLine() if isinstance(eventArgs, TaskDialogShowingEventArgs): msg.AppendLine("\tMessage: " + str(eventArgs.Message)) if eventArgs.DialogId == "TaskDialog_Missing_Third_Party_Updater": dialogResult = 1001 # Continue working with the file. elif eventArgs.DialogId == "TaskDialog_Location_Position_Changed": dialogResult = 1002 # Do not save. elif isinstance(eventArgs, MessageBoxShowingEventArgs): msg.AppendLine("\tMessage: " + str(eventArgs.Message)) msg.AppendLine("\tDialogType: " + str(eventArgs.DialogType)) dialogId = Try( lambda: eventArgs.DialogId ) # Available on DialogBoxShowingEventArgs in Revit 2017+ if dialogId is not None: msg.AppendLine("\tDialogId: " + str(dialogId)) helpId = Try( lambda: eventArgs.HelpId) # No longer available in Revit 2018+ if helpId is not None: msg.AppendLine("\tHelpId: " + str(helpId)) output(msg.ToString()) eventArgs.OverrideResult(dialogResult) except Exception, e: errorMsg = StringBuilder() errorMsg.AppendLine() errorMsg.AppendLine("Caught exception in dialog event handler!") errorMsg.AppendLine("Exception message: " + e.message) output(errorMsg.ToString()) exception_util.LogOutputErrorDetails(e, output)
class NewFocus6700(object): ''' Class for Newfocus 67xx laser control through USB with proper usb driver installed. Args: key: laser DeviceKey id: laser id Methods: Open: open laser instance Close: close laser instance Properties (Fetch/Set): self.connected: laser connection active or no self.output: ON/OFF output state of the laser self.lbd :float: laser wavelength in nm self.current :float: laser current in A self.scan_limit :[float, float]: DC scan limit in nm self.scan_speed :float: DC scan speed in nm self.scan :bool: dc scan status self.beep :bool: set/disabel beep self.error :(read only): fetch error laser and wipe self.identity :(read only): fetch laser identity Utilities: self._open: flag if opening of laser successful self._dev : laser usb socket self._buff : buffer reading the laser status self._is_changing_lbd : track if wavelength is still changing after the user set a wavelength self._is_scaning : track in background if the scan is still ongoing Example: import time import numpy as np import matplotlib.pyplot as plt from NewFocus6700 import NewFocus6700 idLaser = 4106 DeviceKey = '6700 SN10027' laser = NewFocus6700(id =idLaser, key = DeviceKey) laser.connected = True old_lbd = laser.lbd print(f'Laser wavelength: {old_lbd}nm') laser.scan_limit = [1520, 1550] laser.scan_speed = 10 laser.lbd = laser.scan_limit[0] print('waiting until laser parked at correct lbd') while laser._is_changing_lbd: time.sleep(0.25) print(f'Current wavelength: {laser.lbd}nm') print('Now turning on the laser') laser.output = True t = np.array([]) lbd = np.array([]) print('Starting scan') laser.scan = True while laser._is_scaning: pass print('Finished scanning... now turning off the laser') laser.output = False print('All Done!') ''' __author__ = "Gregory Moille" __copyright__ = "Copyright 2021, JQI" __credits__ = ["Gregory Moille", "Kartik Srinivasan"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Gregory Moille" __email__ = "*****@*****.**" __status__ = "Development" def __init__(self, **kwargs): super(NewFocus6700, self).__init__() # Load usb ddl Newport try: # dllpath = 'C:\\ProgramData\\Anaconda3\\DLLs\\' # dllpath = 'C:\\Users\\Greg\\Anaconda3\\DLLs\\' dllpath = 'C:\\ProgramData\\Anaconda3\\DLLs\\' Assembly.LoadFile(dllpath + 'UsbDllWrap.dll') clr.AddReference(r'UsbDllWrap') import Newport self._dev = Newport.USBComm.USB() except Exception as err: print(err) self._dev = None # Laser state self._open = False self._DeviceKey = kwargs.get('key', None) self._idLaser = kwargs.get('id', 4106) # Laser properties self._lbd = '0' self._cc = 0 self._scan_lim = [] self._scan_speed = 0 self._scan = 0 self._beep = 0 self._output = 0 self._is_scaning = False # self._is_changing_lbd = False self._no_error = '0,"NO ERROR"' self._haserr = False # Miscs self._buff = StringBuilder(64) self._err_msg = '' # -- Decorators -- # --------------------------------------------------------- def Checkopen(fun): def wrapper(*args, **kwargs): self = args[0] # if self._open and self._DeviceKey: if self._open and self._DeviceKey: out = fun(*args, **kwargs) return out else: pass return wrapper # -- Methods -- # --------------------------------------------------------- def Query(self, word): self._buff.Clear() self._dev.Query(self._DeviceKey, word , self._buff) return self._buff.ToString() # -- Properties -- # --------------------------------------------------------- @property @InOut.output(bool) def connected(self): return self._open @connected.setter # @Catch.error def connected(self,value): if value: if self._DeviceKey: # try: while True: out = self._dev.OpenDevices(self._idLaser, True) tab = self._dev.GetDeviceTable() #empty buffer out = self._dev.Read(self._DeviceKey, self._buff) # ipdb.set_trace() while not (out == -1 or out == -2 or out == int("-2")): out = self._dev.Read(self._DeviceKey, self._buff) print('Empyting the buffer: {}'.format(out)) time.sleep(0.5) idn = self.identity if not idn == "": print("\nLaser connected: {}".format(idn)) break else: print('Ok reconection try') self._dev.CloseDevices() time.sleep(0.2) # ipdb.set_trace() self.error self._open = True # except Exception as e: # print(e) else: self._dev.CloseDevices() self._open = False @property @InOut.output(bool) def output(self): word = 'OUTPut:STATe?' self._output = self.Query(word) return self._output @output.setter # @Catch.error @InOut.accepts(bool) def output(self,value): word = "OUTPut:STATe {}".format(int(value)) self.Query(word) self._output = value @property @InOut.output(float) def lbd(self): word = 'SENSe:WAVElength?' self._lbd = self.Query(word) return self._lbd @lbd.setter @InOut.accepts(float) # @Catch.error def lbd(self, value): self._targetlbd = value self.Query('OUTP:TRACK 1') word = 'SOURCE:WAVE {}'.format(value) self.Query(word) self._lbd = value @property @InOut.output(float) def current(self): word = 'SOUR:CURR:DIOD?' self._cc = self.Query(word) return self._cc @current.setter # @Catch.error @InOut.accepts(float) def current(self, value): word = 'SOUR:CURR:DIOD {}'.format(value) self.Query(word) self._cc = value @property @InOut.output(float,float) def scan_limit(self): word1 = 'SOUR:WAVE:START?' word2 = 'SOUR:WAVE:STOP?' self._scan_lim = [self.Query(word1), self.Query(word2)] return self._scan_lim @scan_limit.setter # @Catch.error @InOut.accepts(list) def scan_limit(self, value): start = value[0] stop = value[1] word1 = 'SOUR:WAVE:START {}'.format(start) self.Query(word1) word2 = 'SOUR:WAVE:STOP {}'.format(stop) self.Query(word2) self._scan_lim = value @property # @Catch.error @InOut.output(float) def scan_speed(self): word1 = 'SOUR:WAVE:SLEW:FORW?' self._scan_speed = self.Query(word1) return self._scan_speed @scan_speed.setter # @Catch.error @InOut.accepts(float) def scan_speed(self, value): word = 'SOUR:WAVE:SLEW:FORW {}'.format(value) self.Query(word) word = 'SOUR:WAVE:SLEW:RET {}'.format(0.1) self.Query(word) self._scan_speed = value @property @InOut.output(float) def scan(self): word = 'SOUR:WAVE:DESSCANS?' self._scan = self.Query(word) return self._scan @scan.setter # @Catch.error @ChangeState.scan("OUTPut:SCAN:START",'OUTPut:SCAN:STOP') @InOut.accepts(bool) def scan(self, value): self.Query('SOUR:WAVE:DESSCANS 1') self._scan = value if self._scan: self.Query("OUTPut:SCAN:START") else: self.Query("OUTPut:SCAN:STOP") @property @InOut.output(float) def pzt(self): word = 'SOUR:VOLT:PIEZ?' self._pzt = self.Query(word) return self._pzt @pzt.setter # @Catch.error @InOut.accepts(float) def pzt(self, value): word = 'SOUR:VOLT:PIEZ {}'.format(value) self.Query(word) self._pzt = value @property @InOut.output(bool) def beep(self): word = 'BEEP?' self._beep = self.Query(word) return self.beep @beep.setter # @Catch.error @InOut.accepts(bool) def beep(self, value): word = 'BEEP '.format(int(value)) self.Query(word) self._beep = value @property def identity(self): word = "*IDN?" self._id = self.Query(word) return self._id @property def error(self): word = 'ERRSTR?' self._error = '' err = self.Query(word) return err @property def has_error(self): word = '*STB?' dum = self.Query(word) if dum =='128': self._haserr = True if dum == '0': self._haserr = False return self._haserr @property @InOut.output(bool) def _is_changing_lbd(self): return self.Query('OUTP:TRACK?') @property def clear(self): pass @clear.setter @InOut.accepts(bool) def clear(self,val): if val: self.Query('*CLS')
def GetDescriptionSubRecord(self, rec): p = self.page # table has up to 5 columns ss = structure = rec.Structure if not structure or not structure.elements: with p.table(id='record-desc'): if ss: with p.thead(): with p.tr(): p.td(ss.name, class_='headerlabel', width="33%") p.td(ss.desc, colspan='4', class_='header') #with p.tfoot(): # write a blank footer to fix the HtmlRenderer Control # with p.tr(class_='hidden'): # p.td('',class_='header',width="33%").td('').td('').td('').td('') with p.tr(): p.td("String:", width="33%", class_='label') p.td(rec.GetStrData(), class_='value', colspan='4') with p.tr(): p.td("Hex:", width="33%", class_='label') p.td(rec.GetHexData(), class_='value', colspan='4') return try: plugin = rec.GetPlugin() pluginFile = plugin.Name elems = [ elem for elem in rec.EnumerateElements(True) if elem.Structure != None and not elem.Structure.notininfo ] if not elems: return with p.table(id='record-desc'): with p.thead(): with p.tr(): p.td(ss.name, class_='headerlabel') p.td(ss.desc, colspan='4', class_='header') #with p.tfoot(): # write a blank footer to fix the HtmlRenderer Control # with p.tr(class_='hidden'): # p.td('',class_='header',width="33%").td('').td('').td('').td('') with p.tbody(): for elem in elems: sselem = elem.Structure ssname = self.GetElementName(elem) value = self.GetElementValue(elem) strValue = str(value) with p.tr(): p.td(ssname, width="33%", class_='label') if sselem.type == ElementValueType.Blob: p.td(TypeConverter.GetHexData(elem.Data), class_='value', colspan='4') elif sselem.type == ElementValueType.Str4: p.td(TypeConverter.GetString(elem.Data), class_='text', colspan='4') elif sselem.type == ElementValueType.BString: p.td(TypeConverter.GetBString(elem.Data), class_='text', colspan='4') elif sselem.type == ElementValueType.IString: p.td(TypeConverter.GetIString(elem.Data), class_='text', colspan='4') elif sselem.type == ElementValueType.FormID: if not value: p.td(strValue, class_='value', colspan='4') else: formid = value.ToString("X8") record = plugin.GetRecordByID(value) if not record: # lookup plugin name using the id prefName = plugin.GetRecordMaster( value) with p.td(class_='formid', colspan='4'): p.a(formid, href=createLink( pluginFile, sselem.FormIDType, formid, prefName)) else: # lookup actual record to know actual type pref = record.GetPlugin() with p.td(class_='formid', width="15%"): p.a(formid, href=createLink( pluginFile, record.Name, record.FormID.ToString( "X8"), pref.Name)) if record.Name != sselem.FormIDType: p.td(record.DescriptiveName, class_='text', width='20%') else: p.td(getEditorID(record), class_='text', width='20%') id, fullStr = getFullNameWithID(record) if id == None: p.td(fullStr, class_='text', colspan=2) else: p.td(id, class_='textid', width="15%") p.td(fullStr, class_='text') elif sselem.type == ElementValueType.LString: if elem.Type == ElementValueType.String: p.td(value, class_='text', colspan=4) elif TypeConverter.IsLikelyString(elem.Data): p.td(TypeConverter.GetString(elem.Data), class_='text', colspan=4) else: id = TypeConverter.h2i(elem.Data) p.td(id.ToString("X8"), class_='text') p.td(plugin.LookupFormStrings(id), class_='text', colspan=3) elif sselem.type in (ElementValueType.SByte, ElementValueType.Int, ElementValueType.Short, ElementValueType.Byte, ElementValueType.UInt, ElementValueType.UShort): if sselem.type in (ElementValueType.Byte, ElementValueType.UInt, ElementValueType.UShort): intVal = Convert.ToUInt32(value) else: intVal = Convert.ToInt32(value) hasOptions = sselem.options != None and sselem.options.Length > 0 hasFlags = sselem.flags != None and sselem.flags.Length > 1 if sselem.hexview or hasFlags: hexstr = value.ToString( "X" + str(elem.Data.Count * 2)) if sselem.hexviewwithdec: p.td(hexstr, class_='text', width="15%") p.td(strValue, class_='text', width="15%") else: p.td(hexstr, class_='text', colspan=3, width="30%") else: p.td(strValue, class_='text', colspan=3, width="30%") strDesc = '' if hasOptions: for k in xrange(0, sselem.options.Length, 2): ok, intValOption = int.TryParse( sselem.options[k + 1]) if ok and intVal == intValOption: strDesc = sselem.options[k] elif hasFlags: sb = StringBuilder() for k in xrange(0, sselem.flags.Length, 1): if ((intVal & (1 << k)) != 0): if (sb.Length > 0): sb.Append("<br/>") sb.Append(sselem.flags[k]) strDesc = sb.ToString() p.td(strDesc, class_='desc', colspan=3, width='50%') pass else: #p.td(str(sselem.type), class_='text',width='auto' ) p.td(strValue, class_='text', colspan=4) except Exception, e: p.p("Warning: Subrecord doesn't seem to match the expected structure", class_='danger') p.p(str(e), class_='danger')
class StreamOperator(object): def __init__(self, maxsize): self._maxsize = maxsize self._data = Array.CreateInstance(System.Byte, self._maxsize) Random().NextBytes(self._data) self._log = StringBuilder() self._currentoffset = 0 self._currentlength = 0 def setLength(self, streams): newlength = random.randrange(0,self._maxsize) self._currentlength = newlength self._currentoffset = min(self._currentoffset, newlength) self._trace('stream.SetLength(%d)' % newlength) for s in streams: s.SetLength(newlength) def setPosition(self, streams): newposition = random.randrange(0,self._maxsize) self._currentoffset = newposition self._trace('stream.Position = %d' % newposition) for s in streams: s.Position = newposition def seek(self, streams): origin = random.choice([SeekOrigin.Begin, SeekOrigin.Current, SeekOrigin.End]) newoffset = random.randrange(0,self._maxsize) if SeekOrigin.Begin == origin: delta = newoffset - 0 elif SeekOrigin.Current == origin: delta = newoffset - self._currentoffset elif SeekOrigin.End == origin: delta = newoffset - self._currentlength self._currentoffset = newoffset self._trace('stream.Seek(%d, %s)' % (delta, origin)) for s in streams: p = s.Seek(delta, origin) self._check(p == self._currentoffset, 'got offset %d from seek. expected %d' % (p, self._currentoffset)) def write(self, streams): count = random.randrange(0, self._maxsize - self._currentoffset) maxoffset = self._maxsize - count offset = random.randrange(0, maxoffset) self._currentoffset += count self._currentlength = max(self._currentlength, self._currentoffset) self._trace('stream.Write(data, %d, %d)' % (offset, count)) for s in streams: s.Write(self._data, offset, count) def read(self, streams): count = random.randrange(0, self._maxsize) buffer = Array.CreateInstance(System.Byte, self._maxsize) maxoffset = self._maxsize - count offset = random.randrange(0, maxoffset) toread = min(count, self._currentlength - self._currentoffset) toread = max(0, toread) self._currentoffset += toread self._trace('stream.Read(data, %d, %d)' % (offset, count)) for s in streams: r = s.Read(buffer, offset, count) self._check(r == toread, 'got %d bytes from read. expected %d' % (r, toread)) def checkLength(self, streams): for s in streams: l = s.Length self._check(l == self._currentlength, 'stream is %d bytes. expected %d' % (l, self._currentlength)) def checkPosition(self, streams): for s in streams: p = s.Position self._check(p == self._currentoffset, 'position is %d bytes. expected %d' % (p, self._currentoffset)) def rewind(self, streams): self._currentoffset = 0 self._trace('stream.Seek(0, SeekOrigin.Begin)') for s in streams: p = s.Seek(0, SeekOrigin.Begin) self._check(p == self._currentoffset, 'got offset %d from seek. expected %d' % (p, self._currentoffset)) def clear(self, streams): self._currentlength = 0 self._trace('stream.SetLength(0)') self._currentoffset = 0 self._trace('stream.Seek(0, SeekOrigin.Begin)') for s in streams: s.SetLength(0) p = s.Seek(0, SeekOrigin.Begin) self._check(p == self._currentoffset, 'got offset %d from seek. expected %d' % (p, self._currentoffset)) def compare(self, streams): self.checkLength(streams) self.checkPosition(streams) self.rewind(streams) expected = None hash = SHA512Managed() for s in streams: actual = hash.ComputeHash(s) if None <> expected: self._check(self._compareHashValues(expected, actual), 'hash mismatch %s/%s' % (expected, actual)) expected = actual def _compareHashValues(self, a, b): for i in xrange(len(a)): if a[i] <> b[i]: return False return True def _trace(self, s): self._log.AppendLine('%s # position = %d, length = %d' % (s, self._currentoffset, self._currentlength)) def _check(self, condition, message): if not condition: print message print self._log raise AssertionError
#Because the submodule Enyim.Caching is setup to be delay signed when the private key isn't #present, you'll need to modify the project or disable assembly verification #to be able to use a local build. The simplest solution is to disable delay signing #after updating your submodule. This IronPyton script is a QUICK and DIRTY solution to do that. #Again, this script is only useful for local development when working with the source from System.IO import StreamReader, StreamWriter from System.Text import StringBuilder path = r"lib/EnyimMemcached/build/CommonProperties.targets" sr = StreamReader(path) sb = StringBuilder() line = sr.ReadLine() while not line is None: #I'm sure this could all be done in a couple of lines with a nice multi-line Regex #All this does is comment out property groups that attempt to set signing if line.Trim().StartsWith("<PropertyGroup") and line.Contains("PrivateKey"): sb.AppendFormat("<!--{0}\r\n", line) while line is not None and line.Trim() != "</PropertyGroup>": sb.AppendLine(line) line = sr.ReadLine() else: sb.AppendFormat("{0}-->\r\n", line) else: sb.AppendLine(line) line = sr.ReadLine()
def exportSignalsToStream(dc, dayToExport, deviceNameToExport, targetStream, subroutineName, \ exportFileSystemSignals, exportWifiSignals): """ Exports signal data of activity log to a stream. Keyword arguments: dc -- DataContext that should be used to read activity log (TimeCockpit.Data.DataContext) dayToExport -- Day that should be exported (DateTime; time-part has to be 0) deviceNameToExport -- Name of the device that should be exported targetStream -- Target Stream (System.IO.StreamWriter) subroutineName -- Name of the generated routine (should be unique for each export) exportFileSystemSignals -- Indicates whether file system signals should be exported (bool); default is False exportWifiSignals -- Indicates whether WIFI signals should be exported (bool); default is False """ # Internal helper function for extracting type name def extractTypeName(x): helper = str(x) helper = helper.Substring(0, helper.IndexOf(' ')) helper = helper.Substring(helper.LastIndexOf('.') + 1) return helper # Specify all signal types that should be exported signalTypes = [ "APP_CleansedChangeSetSignal", "APP_CleansedComputerActiveSignal", "APP_CleansedEmailSentSignal", "APP_CleansedIpConnectSignal", "APP_CleansedPhoneCallSignal", "APP_CleansedShortMessageSignal", "APP_CleansedUserActiveSignal", "APP_CleansedUserNoteSignal", "APP_CleansedWindowActiveSignal", "APP_CleansedWorkItemChangeSignal" ] if exportFileSystemSignals: # Only export file system signals if explicitly asked for signalTypes.append("APP_CleansedFileSystemSignal") if exportWifiSignals: # Only export WIFI signals if explicitly asked for signalTypes.append("APP_CleansedWifiAvailableSignal") try: chunks = dc.SelectWithParams({ "Query": "From C In SYS_Chunk.Include('SYS_Entity').Include('SYS_Device') " \ "Where ((:Year(C.BeginTime) = @FilterYear And :Month(C.BeginTime) = @FilterMonth And :Day(C.BeginTime) = @FilterDay) " \ " Or (:Year(C.EndTime) = @FilterYear And :Month(C.EndTime) = @FilterMonth And :Day(C.EndTime) = @FilterDay)) " \ " And C.Device.DeviceName = @DeviceName Select C", "@FilterYear": dayToExport.Year, "@FilterMonth": dayToExport.Month, "@FilterDay": dayToExport.Day, "@DeviceName": deviceNameToExport }) if (len(chunks) == 0): raise Exception("No chunks found. Please review export filter criteria.") # Write documentation header targetStream.WriteLine("# -*- coding: utf-8 -*-") targetStream.WriteLine("# This is an auto-generated script") targetStream.WriteLine("#\tGeneration date: {0}", DateTime.Today) targetStream.WriteLine("#\tSource device name: {0}", deviceNameToExport) targetStream.WriteLine("#\tSource day: {0}", dayToExport) targetStream.WriteLine() # Write necessary imports targetStream.WriteLine("from System.Collections.Generic import List") targetStream.WriteLine() # Generate method that regenerates activity log targetStream.WriteLine("def {0}(dc, targetDay):", subroutineName) targetStream.WriteLine("\t\"\"\"", subroutineName) targetStream.WriteLine("\tGenerates activity log in the current user account") targetStream.WriteLine("") targetStream.WriteLine("\tKeyword arguments:") targetStream.WriteLine("\tdc -- DataContext that should be used to write activity log") targetStream.WriteLine("\ttargetDay -- Day into which the activity log should be imported") targetStream.WriteLine("\t\"\"\"", subroutineName) targetStream.WriteLine("\tentities = dc.Select(\"From E In SYS_Entity Select E\")") targetStream.WriteLine("\tdevice = dc.SelectSingle(\"From D In SYS_Device Select D\")") targetStream.WriteLine("\tif device is None:") targetStream.WriteLine("\t\traise Exception(\"No device found\")") targetStream.WriteLine("\ttimeCorrection = targetDay - DateTime({0}, {1}, {2})", dayToExport.Year, dayToExport.Month, dayToExport.Day) targetStream.WriteLine("\tdc.DbClient.BeginTransaction()") targetStream.WriteLine("\ttry:") for chunk in chunks: if (chunk.Entity.EntityName in signalTypes): targetStream.WriteLine("\t\tchunk = dc.CreateChunk({{ \"BeginTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.BeginTime.Year, chunk.BeginTime.Month, chunk.BeginTime.Day, chunk.BeginTime.Hour, chunk.BeginTime.Minute, chunk.BeginTime.Second) targetStream.WriteLine("\t\t\t\"EndTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.EndTime.Year, chunk.EndTime.Month, chunk.EndTime.Day, chunk.EndTime.Hour, chunk.EndTime.Minute, chunk.EndTime.Second) targetStream.WriteLine("\t\t\t\"LogicalBeginTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.LogicalBeginTime.Year, chunk.LogicalBeginTime.Month, chunk.LogicalBeginTime.Day, chunk.LogicalBeginTime.Hour, chunk.LogicalBeginTime.Minute, chunk.LogicalBeginTime.Second) targetStream.WriteLine("\t\t\t\"LogicalEndTime\": DateTime({0}, {1}, {2}, {3}, {4}, {5}) + timeCorrection,", chunk.LogicalEndTime.Year, chunk.LogicalEndTime.Month, chunk.LogicalEndTime.Day, chunk.LogicalEndTime.Hour, chunk.LogicalEndTime.Minute, chunk.LogicalEndTime.Second) targetStream.WriteLine("\t\t\t\"Entity\": [e for e in entities if e.EntityName == \"{0}\"][0],", chunk.Entity.EntityName) targetStream.WriteLine("\t\t\t\"Device\": device })") targetStream.WriteLine("\t\tchunkContentList = List[EntityObject]()") for signal in chunk.Content: signalContent = StringBuilder() for prop in signal.Entity.Properties: typeName = extractTypeName(prop) if (typeName <> "CalculatedProperty"): if (signalContent.Length > 0): signalContent.Append(", ") signalContent.AppendFormat("\"{0}\": ", prop.Name) if (typeName == "TextProperty"): signalContent.Append('"') t = eval("signal.{0}".format(prop.Name)).Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\t").Replace("\r", "\\r") signalContent.Append(t) signalContent.Append('"') elif (typeName == "DateTimeProperty"): signalContent.Append('DateTime(') d = eval("signal.{0}".format(prop.Name)) signalContent.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second) signalContent.Append(')') if (prop.Name == "APP_BeginTime" or prop.Name == "APP_EndTime" or prop.Name == "APP_EventTime"): signalContent.Append(" + timeCorrection") elif (typeName == "BooleanProperty"): b = eval("signal.{0}".format(prop.Name)) signalContent.Append("True" if b else "False") elif (typeName == "GuidProperty"): signalContent.Append('Guid("') signalContent.Append(eval("signal.{0}".format(prop.Name))) signalContent.Append('")') elif (typeName == "NumericProperty"): n = eval("signal.{0}".format(prop.Name)) signalContent.Append(n) else: raise Exception("MISSING TYPE {0}".format(typeName)) targetStream.WriteLine("\t\tchunkContentList.Add(dc.Create{0}({{ {1} }}))", chunk.Entity.EntityName, signalContent.ToString()) targetStream.WriteLine("\t\tchunk.Content = chunkContentList") targetStream.WriteLine("\t\tdc.SaveObject(chunk)") targetStream.WriteLine("\texcept:") targetStream.WriteLine("\t\tif (dc.DbClient.TransactionCount > 0):") targetStream.WriteLine("\t\t\tdc.DbClient.RollbackTransaction()") targetStream.WriteLine("\t\traise") targetStream.WriteLine("\tfinally:") targetStream.WriteLine("\t\tif (dc.DbClient.TransactionCount > 0):") targetStream.WriteLine("\t\t\tdc.DbClient.CommitTransaction()") targetStream.WriteLine() targetStream.WriteLine("# Uncomment and adapt the following two lines to enable the import execution") targetStream.WriteLine("# dc = Context") targetStream.WriteLine("# {0}(dc, DateTime({1}, {2}, {3}))", subroutineName, dayToExport.Year, dayToExport.Month, dayToExport.Day) finally: targetStream.Close()
def parseString(json, index, success): s = StringBuilder() index = JsonDecoder.skipWhitespace(json, index) c = json[index] # " index += 1 complete = False while not complete: if index == json.Length: break c = json[index] index += 1 if c == '"': complete = True break elif c == '\\': if index == json.Length: break c = json[index] index += 1 if c == '"': s.Append('"') elif c == '\\': s.Append('\\') elif c == '/': s.Append('/') elif c == 'b': s.Append('\b') elif c == 'f': s.Append('\f') elif c == 'n': s.Append('\n') elif c == 'r': s.Append('\r') elif c == 't': s.Append('\t') elif c == 'u': remainingLength = json.Length - index if remainingLength >= 4: sb = StringBuilder() for i in range(4): sb.Append(json[index + i]) success, codePoint = UInt32.TryParse(sb.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture) if not success: return String.Empty, index, success s.Append(Encoding.UTF32.GetString(BitConverter.GetBytes(codePoint))) index += 4 else: break else: s.Append(c) if not complete: return None, index, False return s.ToString(), index, success
def GetWindowClassName(hwnd): s = StringBuilder() s.EnsureCapacity(STRING_BUFFER_SIZE) numberOfChars = Win32_GetClassName(hwnd, s, STRING_BUFFER_SIZE) return s.ToString()
print('Restart Check at: ' + dt_string) os.execv(sys.executable, ['python'] + ['opmVOA.py']) else: oEnumerator = oDeviceTable.GetEnumerator() strDeviceKeyList = np.array([]) # Iterate through the Device Table creating a list of Device Keys for nIdx in range(0, nDeviceCount): if (oEnumerator.MoveNext()): strDeviceKeyList = np.append(strDeviceKeyList, oEnumerator.Key) print(strDeviceKeyList) print("\n") strBldr = StringBuilder(64) # Iterate through the list of Device Keys and query each device with *IDN? for oDeviceKey in strDeviceKeyList: strDeviceKey = str(oDeviceKey) print(strDeviceKey) strBldr.Remove(0, strBldr.Length) nReturn = oUSB.Query(strDeviceKey, "*IDN?", strBldr) print("Return Status = %d" % nReturn) print("*IDN Response = %s\n" % strBldr.ToString()) now = datetime.now() dt_string = now.strftime("%m-%d-%Y %H-%M-%S") print("Readings Started " + dt_string) base_dir = os.getcwd()
print(outline.Data.Length, outline.Data) wtr.WriteLine(outline.Data) #Connect to listener server = TcpListener(IP, PORT) server.Start() while True: client = server.AcceptTcpClient() #Create streams for reading/writing stream = client.GetStream() rdr = StreamReader(stream) wtr = StreamWriter(stream) wtr.AutoFlush = True strInput = StringBuilder() #Setup/start process p = Process() p.StartInfo.FileName = "cmd.exe" p.StartInfo.CreateNoWindow = True p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardInput = True p.StartInfo.RedirectStandardError = True p.OutputDataReceived += DataReceivedEventHandler(CmdOutputDataHandler) p.ErrorDataReceived += DataReceivedEventHandler(CmdOutputDataHandler) p.Start() wtr.WriteLine("SPID: %s\nCPID: %s" % (Process.GetCurrentProcess().Id, p.Id))