Beispiel #1
0
    def testPyType_Ready(self, mapper, addToCleanUp):
        typePtr = Marshal.AllocHGlobal(Marshal.SizeOf(PyTypeObject()))
        CPyMarshal.Zero(typePtr, Marshal.SizeOf(PyTypeObject()))
        addToCleanUp(lambda: Marshal.FreeHGlobal(typePtr))

        self.assertEquals(mapper.PyType_Ready(typePtr), 0, "wrong")
        self.assertEquals(
            CPyMarshal.ReadPtrField(typePtr, PyTypeObject, "ob_type"),
            mapper.PyType_Type, "failed to fill in missing ob_type")
        self.assertEquals(
            CPyMarshal.ReadPtrField(typePtr, PyTypeObject, "tp_base"),
            mapper.PyBaseObject_Type, "failed to fill in missing tp_base")
        tp_dict = mapper.Retrieve(
            CPyMarshal.ReadPtrField(typePtr, PyTypeObject, "tp_dict"))
        self.assertEquals(mapper.Retrieve(typePtr).__dict__, tp_dict)

        typeFlags = CPyMarshal.ReadIntField(typePtr, PyTypeObject, "tp_flags")
        self.assertEquals(typeFlags & UInt32(Py_TPFLAGS.READY),
                          UInt32(Py_TPFLAGS.READY), "did not ready type")
        self.assertEquals(
            typeFlags & UInt32(Py_TPFLAGS.HAVE_CLASS),
            UInt32(Py_TPFLAGS.HAVE_CLASS),
            "we always set this flag, for no better reason than 'it makes ctypes kinda work'"
        )

        CPyMarshal.WritePtrField(typePtr, PyTypeObject, "ob_type", IntPtr.Zero)
        self.assertEquals(mapper.PyType_Ready(typePtr), 0, "wrong")
        self.assertEquals(
            CPyMarshal.ReadPtrField(typePtr, PyTypeObject, "ob_type"),
            IntPtr.Zero, "unexpectedly and unnecessarily rereadied type")
Beispiel #2
0
def marking(pairs):
    marking_lst = List[KeyValuePair[Place, UInt32]]()
    for m in pairs:
        t = KeyValuePair[Place, UInt32](m[0], UInt32.Parse(str(m[1])))
        marking_lst.Add(t)

    return Marking(marking_lst)
Beispiel #3
0
    def testOffset(self):
        self.assertEquals(CPyMarshal.Offset(IntPtr(354), 123), IntPtr(477))
        self.assertEquals(CPyMarshal.Offset(IntPtr(354), 0), IntPtr(354))
        self.assertEquals(CPyMarshal.Offset(IntPtr(354), -123), IntPtr(231))
        self.assertEquals(CPyMarshal.Offset(IntPtr(354), UInt32(123)),
                          IntPtr(477))

        self.assertEquals(CPyMarshal.Offset(IntPtr(354), IntPtr(123)),
                          IntPtr(477))
        self.assertEquals(CPyMarshal.Offset(IntPtr(354), IntPtr(0)),
                          IntPtr(354))
Beispiel #4
0
    def testStoreUnknownType(self, mapper, _):
        class C(object):
            __name__ = "cantankerous.cochineal"
        cPtr = mapper.Store(C)
        self.assertEquals(CPyMarshal.ReadIntField(cPtr, PyTypeObject, "ob_refcnt"), 2, "seems easiest to 'leak' types, and ensure they live forever")
        self.assertEquals(CPyMarshal.ReadPtrField(cPtr, PyTypeObject, "ob_type"), mapper.PyType_Type)
        self.assertEquals(CPyMarshal.ReadPtrField(cPtr, PyTypeObject, "tp_base"), mapper.PyBaseObject_Type)
        self.assertEquals(CPyMarshal.ReadPtrField(cPtr, PyTypeObject, "tp_bases"), IntPtr.Zero)
        self.assertEquals(CPyMarshal.ReadPtrField(cPtr, PyTypeObject, "tp_as_number"), IntPtr.Zero)

        namePtr = CPyMarshal.ReadPtrField(cPtr, PyTypeObject, "tp_name")
        self.assertEquals(mapper.Retrieve(namePtr), "cantankerous.cochineal")

        baseFlags = CPyMarshal.ReadIntField(cPtr, PyTypeObject, "tp_flags")
        self.assertEquals(baseFlags & UInt32(Py_TPFLAGS.READY), UInt32(Py_TPFLAGS.READY), "did not ready newly-stored type")
        
        instancePtr = Marshal.AllocHGlobal(Marshal.SizeOf(PyObject))
        CPyMarshal.WritePtrField(instancePtr, PyObject, "ob_type", cPtr)
        CPyMarshal.WriteIntField(instancePtr, PyObject, "ob_refcnt", 2)
        
        instance = mapper.Retrieve(instancePtr)
        self.assertEquals(isinstance(instance, C), True)
        self.assertEquals(mapper.Store(instance), instancePtr)
Beispiel #5
0
    def get_text(self):
        if self.TextAlign == HorizontalAlignment.Center and self.Text == self.placeholder:
            text = None
        else:
            text = self.Text

        if self.formtype is str:
            return text
        elif self.formtype is UInt32:
            self.LOGGER.info("Converting integer string {} in formbox '{}' to type UInt32.".format(text,
                                                                                                 self.placeholder))
            return UInt32(text)
        elif self.formtype is Array[str]:
            split_text = text.split(';')
            return Array[str](split_text)
Beispiel #6
0
 def assertTypeSubclassFlag(self, mapper, t, f):
     typeFlags = CPyMarshal.ReadIntField(mapper.Store(t), PyTypeObject, "tp_flags")
     self.assertEquals(typeFlags & UInt32(f), UInt32(f), "did not have appropriate flag")
Beispiel #7
0
    "PyMethod_Type": types.MethodType,
    "PyClass_Type": types.ClassType,
    "PyInstance_Type": types.InstanceType,
}

TYPE_SUBCLASS_FLAGS = {
    int: Py_TPFLAGS.INT_SUBCLASS,
    long: Py_TPFLAGS.LONG_SUBCLASS,
    list: Py_TPFLAGS.LIST_SUBCLASS,
    tuple: Py_TPFLAGS.TUPLE_SUBCLASS,
    str: Py_TPFLAGS.STRING_SUBCLASS,
    dict: Py_TPFLAGS.DICT_SUBCLASS,
# TODO    BaseException: Py_TPFLAGS.BASE_EXC_SUBCLASS, # this is a little tricky
    type: Py_TPFLAGS.TYPE_SUBCLASS,
}
SUBCLASS_FLAGS_MASK = UInt32(reduce(operator.or_, TYPE_SUBCLASS_FLAGS.values()))

class Types_Test(TestCase):
    
    @WithMapper
    def testTypeMappings(self, mapper, _):
        for (k, v) in BUILTIN_TYPES.items():
            typePtr = getattr(mapper, k)
            self.assertEquals(CPyMarshal.ReadCStringField(typePtr, PyTypeObject, 'tp_name'), v.__name__)
            
            if typePtr == mapper.PyFile_Type:
                self.assertNotEquals(mapper.Retrieve(typePtr), v, "failed to map PyFile_Type to something-that-isn't file")
            else:
                self.assertEquals(mapper.Retrieve(typePtr), v, "failed to map " + k)
            
            if typePtr in (mapper.PyType_Type, mapper.PyBaseObject_Type):
Beispiel #8
0
 def testFlags(self, mapper, _):
     flags = CPyMarshal.ReadUIntField(mapper.PyString_Type, PyTypeObject,
                                      "tp_flags")
     self.assertEquals(flags & UInt32(Py_TPFLAGS.HAVE_GETCHARBUFFER),
                       UInt32(Py_TPFLAGS.HAVE_GETCHARBUFFER))
Beispiel #9
0
	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
Beispiel #10
0
 def __len__(self):
     return UInt32(123)
Beispiel #11
0
                except Exception, e:
                    Trace.WriteLine(e.clsException.Message)
                    Trace.WriteLine(e.clsException.StackTrace)

                finally:
                    task.Result.Response.Close()

            return None

        try:
            httpListener = HttpListener()
            httpListener.Prefixes.Add(
                String.Format(
                    "http://localhost:{0}/",
                    UInt32.Parse("B0B", NumberStyles.HexNumber).ToString(
                        CultureInfo.InvariantCulture)))  # localhost:2827
            httpListener.Start()
            httpListener.GetContextAsync().ContinueWith[List[Entry]](
                Func[Task[HttpListenerContext], List[Entry]](onDispatch),
                TaskContinuationOptions.LongRunning).ContinueWith(
                    Action[Task[List[Entry]]](onCompleted), context)

        except Exception, e:
            Trace.WriteLine(e.clsException.Message)
            Trace.WriteLine(e.clsException.StackTrace)


def onExit(sender, args):
    global sessionEnding, httpListener

    if not sessionEnding and httpListener is not None:
Beispiel #12
0
def create_step_range(start, end):
    range = Array.CreateInstance(COR_DEBUG_STEP_RANGE, 1)
    range[0] = COR_DEBUG_STEP_RANGE(startOffset=UInt32(start),
                                    endOffset=UInt32(end))
    return range
Beispiel #13
0
def Load(devicelist, freq_signal, n_points, Vmatrix):
        
    ncount = 0 #counter of number of employed channels
    result= []   #init array of control booleans
    listchannel = GetListOfChannels(devicelist) #it converts the list of devices into a list of channels
    nchannels = len(listchannel)
    
    if nchannels != n_subs+1: #number of AWG channels must be equal to the number of subsections plus one
        return("ERR_NCH")
    
    for i in range(n_points):
        Vmatrix[i].insert(0,0.) #it insert a (0,0) at the first line, because the first channel is the low one (V-) and it is always 0 V and low impedance for having a short circuit (see later) 
    
    pars_freq = RecalcSignalFreq(freq_signal/1000., n_points)#because freq_signal is in Hz but RecalcSignalFreq requires kHz
    sampl_rate_prescaler = pars_freq[1]
    f_smpl = Decimal(fsample) #cast from float to Decimal needed for the following methods 
    for dev in devicelist: # I have to set the following parameters otherwise the devices are not sync
        res=dev.SetSamplingFrequency(f_smpl, f_smpl, ClockSource.Internal,f_smpl)
        if res[0].ErrorSource != ErrorCodes.RES_SUCCESS:
            return("ERR_FREQ")        
        res= dev.PairLeft.SetFrequencyInterpolation(FrequencyInterpolation.Frequency1X)
        if res.ErrorSource != ErrorCodes.RES_SUCCESS:
            return("ERR_FREQ") 
        res=dev.PairRight.SetFrequencyInterpolation(FrequencyInterpolation.Frequency1X)
        if res.ErrorSource != ErrorCodes.RES_SUCCESS:
            return("ERR_FREQ")         
        res=dev.SetATXSSDeSkewDelay(UInt32(0.))
        if res.ErrorSource != ErrorCodes.RES_SUCCESS:
            return("ERR_FREQ")        


    for ch in range(nchannels): #loop over channels
        channelARB = listchannel[ch]
        if(channelARB == None):
                return(0)
        
        elif channelARB.ChannelFunctionality == Functionality.ARB:
            
            channelARB.SampligRatePrescaler = sampl_rate_prescaler
            
            if ch==0:
                setimp = channelARB.SetOutputImpedance(OutputImpedance.LowImpedance) #first channel, first device, short circuited
            else:                              
                setimp = channelARB.SetOutputImpedance(OutputImpedance.Ohm50) # all other channels set to 50 Ohm
        
            if setimp.ErrorSource != ErrorCodes.RES_SUCCESS:
                return("ERR_IMP")
                
            chan = (n_points)*[0]
                
            #It saves into chan the sequence of the voltages of a channel, it corresponds to a column of Vmatrix
            for j in range(n_points):                                                                               
                chan[j] = (Vmatrix[j][ch])/2. # divided by 2 because Rout=50 Ohm
            
            #if ch==nchannels-1:
            #    print(chan)
            
            wavefrm = WaveformStruct()
            wavefrm.Sample = Array[Double](chan)
            
            
            if ch== 4*(masterdev-1)+masterch-1: #master channel
                markers = [1]
                wavefrm.Marker = Array[Double](markers) #add a marker on a channel, needed for the trigger
                
            wavefrmlist = Array[WaveformStruct]([wavefrm])
            res_load = channelARB.LoadWaveforms(wavefrmlist)
            
            genseq = GenerationSequenceStruct()
            seq = Array[GenerationSequenceStruct]([genseq])
            seq[0].WaveformIndex = 0
            seq[0].Repetitions = 1
            
            channelARB.LoadGenerationSequence(seq, TransferMode.NonReEntrant, True)
                
            if (res_load.ErrorSource == ErrorCodes.RES_SUCCESS):
                result.append(1)
            else:
                result.append(0)
                                
            ncount+=1
            
            channelARB.SetTriggerMode(TriggerMode.Continuous)
            
            if ch == 4*(masterdev-1)+masterch-1: #index of master channel in the list of channels                                
                
                x = channelARB.ATXSSSlaveDisableStartCondition()
                if x.ErrorSource != ErrorCodes.RES_SUCCESS:
                    print("CHANNEL ERROR " + str(ch+1))
                x = channelARB.ATXSSSlaveDisableStopCondition()
                if x.ErrorSource != ErrorCodes.RES_SUCCESS:
                    print("CHANNEL ERROR " + str(ch+1))
                                     
            else:

                x = channelARB.ATXSSSlaveEnableStartCondition(ATXSSEvent.Start) # it starts when master channel starts
                if x.ErrorSource != ErrorCodes.RES_SUCCESS:
                    print("CHANNEL ERROR " + str(ch+1))
                x = channelARB.ATXSSSlaveEnableStopCondition(ATXSSEvent.Stop) # it stops when master channel stops
                if x.ErrorSource != ErrorCodes.RES_SUCCESS:
                    print("CHANNEL ERROR " + str(ch+1))
                    
                #channelARB.SetTriggerMode(TriggerMode.Stepped)
    
    return(result) #it returns an array of 0 and 1 where 0 means that the channel was not loaded correctly, 1 is OK