def getEncoder(self):
        s = readBytesRaw(1,self.ser);
        # print(s[0])
        # print(0x55)
        # print(s)
        if(s[0] == 0x55):
            s = readBytesRaw(1,self.ser);
            if(s[0] == 0x0A):
                e1 = readBytesRaw(4,self.ser);
                e2 = readBytesRaw(4,self.ser);
                sensor = readBytesRaw(1,self.ser);
                batteryVoltage = readBytesRaw(1,self.ser);
                end = readBytesRaw(1,self.ser);
                if(end[0] == 0x33):
                    enc1 = e1[0]*2**24 + e1[1]*2**16 + e1[2]*2**8 + e1[3];
                    enc2 = e2[0]*2**24 + e2[1]*2**16 + e2[2]*2**8 + e2[3];

                    self.encoder1 = int(ctypes.c_int32(enc1).value)
                    self.encoder2 = int(ctypes.c_int32(enc2).value)
                    
                    self.sensor_signal = sensor[0] & 0x30
                    self.batteryVoltage = batteryVoltage

                    # print(encoder1,encoder2)
                    # if(math.fabs(self.encoder1-encoder1)>1000 or math.fabs(self.encoder2-encoder2)>1000):
                        # print("ENCODER FAIL")
                        # return False
                    return True
        return False
Beispiel #2
0
def _unpackSteim2(data_string, npts, swapflag=0, verbose=0):
    """
    Unpack steim2 compressed data given as string.

    :param data_string: data as string
    :param npts: number of data points
    :param swapflag: Swap bytes, defaults to 0
    :return: Return data as numpy.ndarray of dtype int32
    """
    dbuf = data_string
    datasize = len(dbuf)
    samplecnt = npts
    datasamples = np.empty(npts, dtype="int32")
    diffbuff = np.empty(npts, dtype="int32")
    x0 = C.c_int32()
    xn = C.c_int32()
    nsamples = clibmseed.msr_unpack_steim2(
        C.cast(dbuf, C.POINTER(FRAME)),
        datasize,
        samplecnt,
        samplecnt,
        datasamples,
        diffbuff,
        C.byref(x0),
        C.byref(xn),
        swapflag,
        verbose,
    )
    if nsamples != npts:
        raise Exception("Error in unpack_steim2")
    return datasamples
Beispiel #3
0
def instr_bgt(sim,parts,**kwargs):
    if sim is None:
        return check_direct_instr2(parts,**kwargs)
    t = ctypes.c_int32(sim.read_register(parts[0])).value
    u = ctypes.c_int32(sim.read_register(parts[1])).value
    if t > u:
        sim.progCounter = parts[2]
Beispiel #4
0
    def do_set_histogram_params(self, hist_params): #OK!
        """
        Set Histogram Parameters.

        Sets parameters for the internally generated histograms. If the function 
        is not called, default values are in place. When the function is called, 
        all collected histogram data are cleared.

        Input:

        "hist_params" is a size 2 tuple containing (binWidth, binCount), where:
        binWidth    Width of the histograms bins in units of the TDC Time Base, 
                    see TDC_getTimebase . Range = 1 ... 1000000, default = 1.
        binCount    Number of bins in the histogram buffers. Range = 2 ... 1000000, 
                    default = 10000.
        
        Output:

        Error code
        """
        binWidth = ctypes.c_int32(int(hist_params[0]))
        binCount = ctypes.c_int32(int(hist_params[1]))

        ans = self.qutools_dll.TDC_setHistogramParams(binWidth, binCount)

        return self.err_dict[ans]
Beispiel #5
0
    def __init__(self, tor_ecs, pol_ecs, jgy, nshot=99999):

        if nshot > 33725:
            datum = 0
        elif nshot > 27400:
            datum = 20111122
        else:
            datum = 20000101
        n_gy = [4, 4]
        ngy = n_gy[0] + n_gy[1]
        if jgy < n_gy[0]:
            gy = 101 + jgy
        elif jgy < ngy:
            gy = 201 + jgy - n_gy[0]
        c_err    = ct.c_int32(0)
        c_sysunt = ct.c_int32(gy)
        if jgy > 3:
            c_theta  = ct.c_double(1e3*pol_ecs) # [m] -> [mm] for ECRH2
        else:
            c_theta  = ct.c_double(pol_ecs) # deg for ECRH1
        c_phi    = ct.c_double(tor_ecs)
        _err     = ct.byref(c_err)
        _sysunt  = ct.byref(c_sysunt)
        _theta   = ct.byref(c_theta)
        _phi     = ct.byref(c_phi)
        c_datum  = ct.c_double(datum)
        _datum   = ct.byref(c_datum)

        s = libecrh.setval2tp_(_err, _sysunt, _theta, _phi, _datum)

        self.tor = c_phi.value   # deg
        self.pol = c_theta.value # deg
Beispiel #6
0
def instr_div(sim,parts,**kwargs):
    if sim is None:
        return check_register_instr2(parts)
    t = sim.read_register(parts[0])
    u = sim.read_register(parts[1])
    sim.write_register('HI',ctypes.c_int32(t % u).value)
    sim.write_register('LO',ctypes.c_int32(t // u).value)
Beispiel #7
0
def load_metadata(conn, configs):
	mdfile = configs['metadatafile']
	print 'Using metadata from \"%s\"...' % mdfile

	print 'Begin loading metadata for %s...' % configs['hostname']
	print '='*80
	tic = time.time()

	create_index_for_principal(conn)
	create_index_for_resource(conn)
	create_index_for_operation(conn)


	with open(mdfile, 'r+b') as f:
		map = mmap.mmap(f.fileno(), 0)
		line = map.readline()
		while line:
			m = line.split('|')
			fullpath = m[0]
			fileext = m[1]
			nfileext = int(m[2]) # unused
			filetype = m[3]
			nfiletype = int(m[4]) # unused
			mode = ctypes.c_int32(int(m[5])).value
			uid = ctypes.c_int32(int(m[6])).value
			gid = ctypes.c_int32(int(m[7])).value

			# Skip entries for which we don't have info.
			if mode == -1 or uid == -1 or mode == -1:
				line = map.readline()
				continue

			cur = conn.cursor()
			cur.execute('BEGIN TRANSACTION')
			#cur.close()

			req_perm = AuditdReqPerm(None, cur)
			rsrc = AuditdResource( None, cur, path=fullpath, rid=None )
			if rsrc.rid != None:
				tyid = AuditdType( None, cur,
											 fullpath if 'directory' in filetype.lower() \
											 else os.path.dirname(fullpath),
											 filetype ).get_tyid()
				rsrc.update( tyid, fileext, uid, gid, mode )
				req_perm.compute(rsrc)
				#rsrc.compute_actors( shadow=False )

			#cur = conn.cursor()
			#cur.execute('END TRANSACTION')
			cur.close()
			conn.commit()

			line = map.readline()
		map.close()

	toc = time.time()
	print '='*80
	elapsed = toc - tic
	print 'Done loading metadata for %s. Took %f seconds.' \
			% (configs['hostname'], elapsed)
Beispiel #8
0
    def do_get_histogram_params(self): #OK!
        """
        Read back Histogram Parameters.

        Reads back the histogram parameters that have been set with 
        TDC_setHistogramParams or their default values, respectively.

        Output:

        (binWidth,binCount) where
        binWidth 	Width of the histograms bins in TDC Time Base 
                        units, see TDC_getTimebase .
        binCount 	Number of bins in the histogram buffers.
        """
        
        binWidth = ctypes.c_int32()
        binCount = ctypes.c_int32()

        ans = self.qutools_dll.TDC_getHistogramParams(ctypes.byref(binWidth),
                ctypes.byref(binCount))

        if ans != 0:
            return self.err_dict[ans]
        else:
            return binWidth.value, binCount.value
Beispiel #9
0
    def do_get_device_params(self): #OK!
        """
        Read Back Device Parameters.

        Reads the device parameters back from the device. All Parameters are 
        output parameters but may be NULL-Pointers if the result is not required.

        Output:
        
        tuple of the form (channelMask, coincWin, expTime) where:
        channelMask     Enabled channels, see TDC_enableChannels
        coincWin 	Coincidence window, see TDC_setCoincidenceWindow
        expTime 	Exposure time, see TDC_setExposureTime
        """
        
        channelMask = ctypes.c_int32()
        coincWindow = ctypes.c_int32()
        expTime = ctypes.c_int32() 

        ans = self.qutools_dll.TDC_getDeviceParams(ctypes.byref(channelMask),
                ctypes.byref(coincWindow), ctypes.byref(expTime))
        
        if ans != 0:
            return self.err_dict[ans]
        else:
            return self.revert_channelmask(channelMask.value), \
                    coincWindow.value, expTime.value
Beispiel #10
0
    def configure_selftest(self, channels, period, burst_periods, burst_dist): #OK!
        """
        Input:

        channels        List of channels, e.g. [0, 1, 2] for channels 1 to 3.
        period 	        Period in seconds, Range = 40 ns ... 1200 ns
        burst_periods 	Number of periods in a burst, Range = 1 ... 65535
        burst_dist 	Distance between bursts in seconds, Range = 0 ns ... 0.8 ms
        
        Output:

        Error code
        """
        
        period = int(period/20E-9)
        burst_periods = int(burst_periods)
        burst_dist = int(burst_dist/80E-9)

        channelMask = ctypes.c_int32(self.convert_channelmask(channels))
        Period = ctypes.c_int32(period)
        BurstSize = ctypes.c_int32(burst_periods)
        BurstDist = ctypes.c_int32(burst_dist)

        ans = self.qutools_dll.TDC_configureSelftest(channelMask, Period, 
                BurstSize, BurstDist)

        return self.err_dict[ans]
    def getFrames(self):
        frames = []
        for n in self.newFrames():

            # Lock the frame in the camera buffer & get address.
            data_address = ctypes.c_void_p(0)
            row_bytes = ctypes.c_int32(0)
            self.checkStatus(dcam.dcam_lockdata(self.camera_handle,
                                                ctypes.byref(data_address),
                                                ctypes.byref(row_bytes),
                                                ctypes.c_int32(n)),
                             "dcam_lockdata")

            # Create storage for the frame & copy into this storage.
            hc_data = HCamData(self.frame_bytes)
            hc_data.copyData(data_address)

            # Unlock the frame.
            #
            # According to the documentation, this would be done automatically
            # on the next call to lockdata, but we do this anyway.
            self.checkStatus(dcam.dcam_unlockdata(self.camera_handle),
                             "dcam_unlockdata")

            frames.append(hc_data)

        return [frames, [self.frame_x, self.frame_y]]
Beispiel #12
0
    def _dtype_shape(self):
        """
        Data type and shape.
        """
        import numpy
        w = c_int32()
        h = c_int32()
        dll.dc1394_get_image_size_from_video_mode(self._cam, self._mode_id,
                                                  byref(w), byref(h))
        self._shape = (h.value, w.value)

        cc = color_coding_t()
        dll.dc1394_get_color_coding_from_video_mode(
                self._cam, self._mode_id, byref(cc))

        self._color_coding = color_codings[cc.value]

        self._dtype = '<u1'
        if '8' in self._color_coding:
            self._dtype = '>u1'
        elif '16' in self._color_coding:
            self._dtype = '>u2'
        elif 'YUV' in self._color_coding:
            print("Warning: YUV image format!")
            # the data depth is 8 bit in the buffer,
            # but 12 or 16 bit in a _color pixel.
            self._dtype = ">u1"
        else:
            print("Nonstandard image format: %s" % mode[-1])
            self._dtype = ">u1"

        if "RGB" in self._color_coding:
            self._shape.append(3)
Beispiel #13
0
def pixBlockconv(pix, half_width, half_height):
    """Return pix object convoluted by a kernel specified by input dimensions."""

    wc, hc = C.c_int32(half_width), C.c_int32(half_height)

    with LeptonicaErrorTrap():
        return lept.pixBlockconv(pix, wc, hc)
Beispiel #14
0
 def _internalwrite(self,o):
     cp=self.fp.tell()
     l=len(o)
     self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(l)),4))
     ds=[pickle.dumps(so) for so in o]
     ls=map(len,ds)
     iscompress=[0]*l
     for i in range(l):
         if (ls[i]>64):
             ds[i]=zlib.compress(ds[i])
             ls[i]=len(ds[i])
             clen=ctypes.string_at(ctypes.pointer(ctypes.c_int32(ls[i])),4)
             ds[i]=clen+ds[i]
             ls[i]+=4
             iscompress[i]=1
     ofa=numpy.array([0]+ls,dtype=numpy.uint32).cumsum()# compute offsets
     ofa+=(cp+((2+l+l)*4)) # relocate correctly
     for i in range(l):
         self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(ofa[i])),4))
         self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(iscompress[i])),4))
     self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(ofa[l])),4)) # write next block
     for i in range(len(ds)):
         if (self.fp.tell()!=ofa[i]):
             raise Exception, ("error file @ %d but declared offset at %d"%(self.fp.tell(),ofa[i]))
         self.fp.write(ds[i])
Beispiel #15
0
Datei: kk.py Projekt: pyIPP/pykk
 def getMagneticField(self, time, R, z):
     if not self.status:
         raise Exception('No shotnumber specified.')
     error = ctypes.c_int32(0)
     t = ctypes.c_float(time)
     N = numpy.size(R)
     rin = numpy.zeros(N, dtype=numpy.float32)
     rin[:] = R
     zin = numpy.zeros(N, dtype=numpy.float32)
     zin[:] = z
     lin = ctypes.c_int32(rin.size)
     br = numpy.zeros(rin.size, dtype=numpy.float32)
     bz = numpy.zeros(rin.size, dtype=numpy.float32)
     bt = numpy.zeros(rin.size, dtype=numpy.float32)
     fpf = numpy.zeros(rin.size, dtype=numpy.float32)
     jpol = numpy.zeros(rin.size, dtype=numpy.float32)
     lexper = ctypes.c_uint64(len(self.experiment))
     ldiag = ctypes.c_uint64(len(self.diagnostic))
     __blockstdout__()
     __libkk__.kkrzbrzt_(ctypes.byref(error), ctypes.c_char_p(self.experiment), ctypes.c_char_p(self.diagnostic), 
                         ctypes.byref(self.shotnumber), ctypes.byref(self.edition), ctypes.byref(t), rin.ctypes.data_as(ctypes.c_void_p),
                         zin.ctypes.data_as(ctypes.c_void_p), ctypes.byref(lin) , br.ctypes.data_as(ctypes.c_void_p), 
                         bz.ctypes.data_as(ctypes.c_void_p) , bt.ctypes.data_as(ctypes.c_void_p), fpf.ctypes.data_as(ctypes.c_void_p), 
                         jpol.ctypes.data_as(ctypes.c_void_p), lexper , ldiag)
     __releasestdout__()
     return magneticField(t.value, rin, zin, bt, br, bz, fpf, jpol)
Beispiel #16
0
def c_svd_euclidean_train_epoch(train_points, users, user_offsets, movies,
                                movie_averages, num_features, learn_rate,
                                k_factor):
    import ctypes
    from ctypes import c_void_p, c_int32, c_float
    import os
    from utils.data_paths import LIBRARY_DIR_PATH
    num_train_points = train_points.shape[0]
    num_users = users.shape[0]
    num_movies = movies.shape[0]
    library_file_name = 'svd_euclidean.so'
    library_file_path = os.path.join(LIBRARY_DIR_PATH, library_file_name)
    svd_euclidean_lib = ctypes.cdll.LoadLibrary(library_file_path)
    c_train_epoch = svd_euclidean_lib.c_train_epoch
    returned_value = c_train_epoch(
        c_void_p(train_points.ctypes.data),    # (void*) train_points
        c_int32(num_train_points),             # (int)   num_train_points
        c_void_p(users.ctypes.data),           # (void*) users
        c_void_p(user_offsets.ctypes.data),    # (void*) user_offsets
        c_int32(num_users),                    # (int)   num_users
        c_void_p(movies.ctypes.data),          # (void*) movies
        c_void_p(movie_averages.ctypes.data),  # (void*) movie_averages
        c_int32(num_movies),                   # (int)   num_movies
        c_float(learn_rate),                   # (float) learn_rate
        c_int32(num_features),                 # (int)   num_features
        c_float(k_factor)                      # (float) k_factor
    )
    if returned_value != 0:
        raise CException(returned_value)
Beispiel #17
0
    def config_i2c(self, size=None, address=0, clock_rate=100, timeout=2000):
        """
        Set the ni845x I2C configuration.
        
        Parameters
        ----------
            size : Configuration address size (default 7Bit).
            address : Configuration address (default 0).
            clock_rate : Configuration clock rate in kilohertz (default 100).

        Returns
        -------
            None
        """
        if size is None:
            size = self.kNi845xI2cAddress7Bit
        size = ctypes.c_int32(size)
        address = ctypes.c_uint16(address)
        clock_rate = ctypes.c_uint16(clock_rate)
        timeout = ctypes.c_uint32(timeout)
        #
        # create configuration reference
        #
        self.i2c_handle = ctypes.c_int32()
        errChk(ni845x_dll.ni845xI2cConfigurationOpen(ctypes.byref(self.i2c_handle)))
        
        #
        # configure configuration properties
        #
        errChk(ni845x_dll.ni845xI2cConfigurationSetAddressSize(self.i2c_handle, size))
        errChk(ni845x_dll.ni845xI2cConfigurationSetAddress(self.i2c_handle, address))
        errChk(ni845x_dll.ni845xI2cConfigurationSetClockRate(self.i2c_handle, clock_rate))
        errChk(ni845x_dll.ni845xSetTimeout(self.dev_handle, timeout))
Beispiel #18
0
def TreeGetDbi(tree,itemname):
    itemlist={'NAME':(1,str,12),'SHOTID':(2,int),'MODIFIED':(3,bool),
              'OPEN_FOR_EDIT':(4,bool),'INDEX':(5,int),'NUMBER_OPENED':(6,int),
              'MAX_OPEN':(7,int),'DEFAULT':(10,int),'OPEN_READONLY':(9,bool),
              'VERSIONS_IN_MODEL':(10,bool),'VERSIONS_IN_PULSE':(11,bool)}
    try:
        item=itemlist[itemname.upper()]
    except KeyError:
        raise KeyError('Item name must be one of %s' % (str(itemlist.keys()),))
    if item[1]==str:
        ans=_C.c_char_p(str.encode('x'.rjust(item[2])))
        retlen=_C.c_int32(0)
        itmlst=DBI_ITM_CHAR(item[0],item[2],ans,retlen)
    else:
        ans=_C.c_int32(0)
        itmlst=DBI_ITM_INT(item[0],ans)
    try:
        tree.lock()
        status=__TreeGetDbi(tree.ctx,_C.cast(
            _C.pointer(itmlst),_C.c_void_p))
    finally:
        tree.unlock()
    if not (status & 1):
        raise TreeException(MdsGetMsg(status))
    if item[1]==str:
        if isinstance(ans.value,str):
          return ans.value
        else:
          return ans.value.decode()
    else:
        return item[1](ans.value)
    def encodeMessage(self):
        #since Python only uses ints and longs and does weird memory stuff, we need to wrap them here using the C types
        newVersion=ctypes.c_uint8(self.version)
        newFlag=ctypes.c_uint8(self.flag)
        newType=ctypes.c_uint16(self.optype)
        newCorrelation=ctypes.c_uint32(self.correlation)
        newPartition=ctypes.c_int32(self.partition)

        byteArray=bytearray(newVersion)+bytearray(newFlag)+bytearray(newType)+bytearray(newCorrelation)+bytearray(newPartition)
        netSize=4+len(byteArray)+2
        self.HEADER_SIZE=netSize
        if self.extension is not None:
            netSize+=len(self.extension)
        self.DATA_OFFSET=netSize
        if self.payload is not None:
            netSize+=len(self.payload)

        self.FRAME_SIZE=netSize


        newSize=ctypes.c_int32(self.FRAME_SIZE)
        newOffset=ctypes.c_uint16(self.DATA_OFFSET)

        byteArray=bytearray(newSize)+byteArray+bytearray(newOffset)
        if self.extension is not None:
            byteArray+=self.extension
        if self.payload is not None:
            byteArray+=self.payload

        return byteArray
Beispiel #20
0
    def testEncodingWithExtension(self):
        msg=ClientMessage()
        vr=0
        optype=200
        corrID=0
        parID=-1

        msg.version=vr
        msg.optype=optype
        msg.correlation=corrID
        msg.partition=parID
        msg.addExtension(bytearray(ctypes.c_uint32(4203239)))
        frame = bytearray()
        #Create a byte array of size 18


        frame+=bytearray(ctypes.c_int32(18+4))
        frame+=bytearray(ctypes.c_uint8(vr))
        frame+=bytearray(ctypes.c_uint8(192))
        frame+=bytearray(ctypes.c_uint16(optype))
        frame+=bytearray(ctypes.c_int32(corrID))
        frame+=bytearray(ctypes.c_int32(parID))
        frame+=bytearray(ctypes.c_uint16(22))
        frame+=bytearray(ctypes.c_uint32(4203239))

        encodedMsg=msg.encodeMessage()


        self.assertEqual(frame,encodedMsg)
Beispiel #21
0
    def testEncoding(self):
        msg=ClientMessage()
        vr=0
        optype=200
        corrID=0
        parID=-1

        msg.setVersion(vr)
        msg.setFlagBoth()
        msg.setOperationType(200)
        msg.correlation=corrID
        msg.setPartition(parID)

        frame = bytearray()

        #Create a byte array of size 18
        frame+=bytearray(ctypes.c_int32(18))
        frame+=bytearray(ctypes.c_uint8(vr))
        frame+=bytearray(ctypes.c_uint8(192))
        frame+=bytearray(ctypes.c_uint16(optype))
        frame+=bytearray(ctypes.c_int32(corrID))
        frame+=bytearray(ctypes.c_int32(parID))
        frame+=bytearray(ctypes.c_uint16(18))

        self.assertEqual(frame,msg.encodeMessage())
Beispiel #22
0
 def getQueue(eventid,timeout=0):
     """Retrieve event occurrence.
     @param eventid: eventid returned from MDSQueueEvent function
     @type eventid: int
     @param timeout: Optional timeout. If greater than 0 an MdsTimeout exception will be raised if no event occurs
     within timeout seconds after function invokation. If timeout equals zero then this function will
     block until an event occurs. If timeout is less than zero this function will not wait for events
     and will either returned a queued event or raise MdsNoMoreEvents.
     @type timeout: int
     @return: event data
     @rtype: Uint8Array
     """
     dlen=_C.c_int32(0)
     bptr=_C.c_void_p(0)
     status=_MdsShr.MDSGetEventQueue(_C.c_int32(eventid),_C.c_int32(timeout),_C.pointer(dlen),_C.pointer(bptr))
     if status==1:
         if dlen.value>0:
             ans = _data.Uint8Array(_NP.ndarray(shape=[dlen.value],buffer=buffer(_C.cast(bptr,_C.POINTER((_C.c_uint8 * dlen.value))).contents),dtype=_NP.uint8))
             _MdsShr.MdsFree(bptr)
             return ans
         else:
             return _data.Uint8Array([])
     elif status==0:
         if timeout > 0:
             raise MdsTimeout("Timeout")
         else:
             raise MdsNoMoreEvents("No more events")
     elif status==2:
         raise MdsInvalidEvent("Invalid eventid")
     else:
         raise MdsException("Unknown error - status=%d" % (status,))
Beispiel #23
0
 def getObjectValue(self, name, field):
     """ Returns the value for the specified field for the given object name. """
     if not self.status:
         raise Exception('Shotfile not open')
     error = ctypes.c_int32(0)
     data = __fields__[field]()
     try:
         value = ctypes.c_char_p(data)
     except TypeError:
         try:
             value = data.ctypes.data_as(ctypes.c_void_p)
         except AttributeError:
             del data
             val = ctypes.c_int32(0)
             value = ctypes.byref(val)
     try:
         _name = ctypes.c_char_p(name)
     except TypeError:
         _name = ctypes.c_char_p(name.encode())
     try:
         _field = ctypes.c_char_p(field)
     except TypeError:
         _field = ctypes.c_char_p(field.encode())
     lname = ctypes.c_uint64(len(name))
     lfield = ctypes.c_uint64(len(field))
     result = __libddww__.ddobjval_(ctypes.byref(error),ctypes.byref(self.diaref),_name,_field, value,
                                    lname,lfield)
     getError(error)
     try:
         return data
     except Exception, Error:
         return numpy.int32(val.value)
Beispiel #24
0
def _set_decode_area(codec, image, start_x=0, start_y=0, end_x=0, end_y=0):
    """Wraps openjp2 library function opj_set_decode area.

    Sets the given area to be decoded.  This function should be called right
    after read_header and before any tile header reading.

    Parameters
    ----------
    codec : _codec_t_p
        Codec initialized by create_decompress function.
    image : _image_t pointer
        The decoded image previously set by read_header.
    start_x, start_y : optional, int
        The left and upper position of the rectangle to decode.
    end_x, end_y : optional, int
        The right and lower position of the rectangle to decode.

    Raises
    ------
    RuntimeError
        If the OpenJPEG library routine opj_set_decode_area fails.
    """
    _OPENJP2.opj_set_decode_area(codec, image,
                                 ctypes.c_int32(start_x),
                                 ctypes.c_int32(start_y),
                                 ctypes.c_int32(end_x),
                                 ctypes.c_int32(end_y))
    def get_server_info(self, gameid, session_id, client_id):
        server_info = None
        servers = self.server_manager.get_natneg_server(session_id)._getvalue()

        if servers == None:
            return None

        console = 0
        ipstr = self.session_list[session_id][client_id]['addr'][0]

        if console != 0:
            ip = str(ctypes.c_int32(utils.get_int_be(bytearray([int(x) for x in ipstr.split('.')]), 0)).value) # Wii
            console = 0
        else:
            ip = str(ctypes.c_int32(utils.get_int(bytearray([int(x) for x in ipstr.split('.')]), 0)).value) # DS
            console = 1

        for server in servers:
            if server['publicip'] == ip:
                server_info = server
                break

        if server_info == None:
            if console != 0:
                ip = str(ctypes.c_int32(utils.get_int_be(bytearray([int(x) for x in ipstr.split('.')]), 0)).value) # Wii
            else:
                ip = str(ctypes.c_int32(utils.get_int(bytearray([int(x) for x in ipstr.split('.')]), 0)).value) # DS

            for server in servers:
                if server['publicip'] == ip:
                    server_info = server
                    break

        return server_info
    def setPropertyValue(self, property_name, property_value):

        # Check if the property exists.
        if not (property_name in self.properties):
            print " unknown property name:", property_name
            return False

        # If the value is text, figure out what the 
        # corresponding numerical property value is.
        if (type(property_value) == type("")):
            text_values = self.getPropertyText(property_name)
            if (property_value in text_values):
                property_value = float(text_values[property_value])
            else:
                print " unknown property text value:", property_value, "for", property_name
                return False

        # Check that the property is within range.
        [pv_min, pv_max] = self.getPropertyRange(property_name)
        if (property_value < pv_min):
            print " set property value", property_value, "is less than minimum of", pv_min, property_name, "setting to minimum"
            property_value = pv_min
        if (property_value > pv_max):
            print " set property value", property_value, "is greater than maximum of", pv_max, property_name, "setting to maximum"
            property_value = pv_max
        
        # Set the property value, return what it was set too.
        prop_id = self.properties[property_name]
        p_value = ctypes.c_double(property_value)
        self.checkStatus(dcam.dcam_setgetpropertyvalue(self.camera_handle,
                                                       ctypes.c_int32(prop_id),
                                                       ctypes.byref(p_value),
                                                       ctypes.c_int32(DCAM_DEFAULT_ARG)),
                         "dcam_setgetpropertyvalue")
        return p_value.value
Beispiel #27
0
def _read_tile_header(codec, stream):
    """Reads a tile header.

    Wraps the openjp2 library function opj_read_tile_header.

    Parameters
    ----------
    codec : codec_t
        The JPEG2000 codec to read.
    stream : _stream_t_p
        The JPEG2000 stream.

    Returns
    -------
    tile_index : int
        index of the tile being decoded
    data_size : int
        number of bytes for the decoded area
    x0, y0 : int
        upper left-most coordinate of tile
    x1, y1 : int
        lower right-most coordinate of tile
    ncomps : int
        number of components in the tile
    go_on : bool
        indicates that decoding should continue

    Raises
    ------
    RuntimeError
        If the OpenJPEG library routine opj_read_tile_header fails.
    """
    tile_index = ctypes.c_uint32()
    data_size = ctypes.c_uint32()
    x0 = ctypes.c_int32()
    y0 = ctypes.c_int32()
    x1 = ctypes.c_int32()
    y1 = ctypes.c_int32()
    ncomps = ctypes.c_uint32()
    go_on = _bool_t()
    _OPENJP2.opj_read_tile_header(codec,
                                  stream,
                                  ctypes.byref(tile_index),
                                  ctypes.byref(data_size),
                                  ctypes.byref(x0),
                                  ctypes.byref(y0),
                                  ctypes.byref(x1),
                                  ctypes.byref(y1),
                                  ctypes.byref(ncomps),
                                  ctypes.byref(go_on))
    go_on = bool(go_on.value)
    return (tile_index.value,
            data_size.value,
            x0.value,
            y0.value,
            x1.value,
            y1.value,
            ncomps.value,
            go_on)
Beispiel #28
0
    def hash(self, timestamp, latitude, longitude, accuracy, authticket, sessiondata, requestslist):
        self.location_hash = None
        self.location_auth_hash = None
        self.request_hashes = []

        payload = {
            'Timestamp': timestamp,
            'Latitude64': unpack('<q', pack('<d', latitude))[0],
            'Longitude64': unpack('<q', pack('<d', longitude))[0],
            'Accuracy64': unpack('<q', pack('<d', accuracy))[0],
            'AuthTicket': base64.b64encode(authticket).decode('ascii'),
            'SessionData': base64.b64encode(sessiondata).decode('ascii'),
            'Requests': [base64.b64encode(x.SerializeToString()).decode('ascii') for x in requestslist]
        }

        # request hashes from hashing server
        try:
            response = self._session.post(self.endpoint, json=payload, headers=self.headers, timeout=30)
        except requests.exceptions.Timeout:
            raise HashingTimeoutException('Hashing request timed out.')
        except requests.exceptions.ConnectionError as error:
            raise HashingOfflineException(error)

        if response.status_code == 400:
            raise BadHashRequestException("400: Bad request, error: {}".format(response.text))
        elif response.status_code == 403:
            raise TempHashingBanException('Your IP was temporarily banned for sending too many requests with invalid keys')
        elif response.status_code == 429:
            raise HashingQuotaExceededException("429: Request limited, error: {}".format(response.text))
        elif response.status_code in (502, 503, 504):
            raise HashingOfflineException('{} Server Error'.format(response.status_code))
        elif response.status_code != 200:
            error = 'Unexpected HTTP server response - needs 200 got {c}. {t}'.format(
                c=response.status_code, t=response.text)
            raise UnexpectedHashResponseException(error)

        if not response.content:
            raise MalformedHashResponseException('Response was empty')

        headers = response.headers
        try:
            self.status['period'] = int(headers['X-RatePeriodEnd'])
            self.status['remaining'] = int(headers['X-RateRequestsRemaining'])
            self.status['maximum'] = int(headers['X-MaxRequestCount'])
            self.status['expiration'] = int(headers['X-AuthTokenExpiration'])
            self.status['token'] = self.headers['X-AuthToken']
        except (KeyError, TypeError, ValueError):
            pass

        try:
            response_parsed = response.json()
        except ValueError:
            raise MalformedHashResponseException('Unable to parse JSON from hash server.')

        self.location_auth_hash = ctypes.c_int32(response_parsed['locationAuthHash']).value
        self.location_hash = ctypes.c_int32(response_parsed['locationHash']).value

        for request_hash in response_parsed['requestHashes']:
            self.request_hashes.append(ctypes.c_int64(request_hash).value)
Beispiel #29
0
 def deviceGetServiceStatus(self, device_info):
     kl = kvrlib()
     kl.fn = 'deviceGetServiceStatus'
     state = ct.c_int32(-1)
     start_info = ct.c_int32(-1)
     kl.dll.kvrDeviceGetServiceStatus(ct.byref(device_info),
                                      ct.byref(state), ct.byref(start_info))
     return (state.value, start_info.value)
Beispiel #30
0
def accumulated_cost_matrix(x,y,distances):
    len_x = ctypes.c_int32(x.shape[0])
    len_y = ctypes.c_int32(y.shape[0])
    accumulated_cost = numpy.empty((x.shape[0],y.shape[0]),dtype=numpy.float32)

    generates_accumulated_cost(len_x, len_y, accumulated_cost, distances)

    return accumulated_cost
Beispiel #31
0
def pid_is_running(i):
    global _lib
    if _lib == None:
        return True
    else:
        return _lib.pid_is_running(_ctypes.c_int32(i)) == 1
 def __conv_float_to_fixed_point(cls, d):
     shift_amount = 31
     one_shifted = ctypes.c_int32(1 << 31).value
     beforecomma = int(d)
     aftercomma = int(((d - beforecomma) * one_shifted))
     return ctypes.c_int32(beforecomma << shift_amount).value + aftercomma
Beispiel #33
0
def kill_process(i):
    global _lib
    if _lib == None:
        return True
    else:
        return _lib.kill_process(_ctypes.c_int32(i)) == 1
Beispiel #34
0
def from_outputs(outputs):
    for prediction in java.next_bits.from_outputs(outputs, 32):
        yield c_int32(prediction).value
Beispiel #35
0
 def fetch_operands(self, reader):
     self.index = ctypes.c_uint(reader.read_uint8()).value
     self.const = ctypes.c_int32(reader.read_int8()).value
Beispiel #36
0
def add_function(a, b):
    return ctypes_add_function(ctypes.c_int32(a), ctypes.c_int32(b))
Beispiel #37
0
        def learn_line(self, body, num_context):
            """
            Learn from a sentence.
            """

            words = body.split()
            # Ignore sentences of < 1 words XXX was < 3
            if len(words) < 1:
                return

            voyelles = "aàâeéèêiîïoöôuüûyaAeEiIoOuUyY"
            for x in xrange(0, len(words)):

                nb_voy = 0
                digit = 0
                char = 0
                for c in words[x]:
                    if c in voyelles:
                        nb_voy += 1
                    if c.isalpha():
                        char += 1
                    if c.isdigit():
                        digit += 1

                for censored in self.settings.censored:
                    pattern = "^%s$" % censored
                    if re.search(pattern, words[x]):
                        print "Censored word %s" % words[x]
                        return

                if len(words[x]) > 13 \
                or (((nb_voy * 100) / len(words[x]) < 21) and len(words[x]) > 5) \
                or (char and digit) \
                or (self.words.has_key(words[x]) == 0 and self.settings.learning == 0):
                    #if one word as more than 13 characters, don't learn
                    #        (in french, this represent 12% of the words)
                    #and don't learn words where there are less than 20% of voyels
                    #don't learn the sentence if one word is censored
                    #don't learn too if there are digits and char in the word
                    #same if learning is off
                    return
                elif ("-" in words[x] or "_" in words[x]):
                    words[x] = "#nick"

            num_w = self.settings.num_words
            if num_w != 0:
                num_cpw = self.settings.num_contexts / float(
                    num_w)  # contexts per word
            else:
                num_cpw = 0

            cleanbody = " ".join(words)

            # Hash collisions we don't care about. 2^32 is big :-)
            hashval = ctypes.c_int32(hash(cleanbody)).value

            # Check context isn't already known
            if not self.lines.has_key(hashval):
                if not (num_cpw > 100 and self.settings.learning == 0):

                    self.lines[hashval] = [cleanbody, num_context]
                    # Add link for each word
                    for x in xrange(0, len(words)):
                        if self.words.has_key(words[x]):
                            # Add entry. (line number, word number)
                            self.words[words[x]].append(
                                struct.pack("lH", hashval, x))
                        else:
                            self.words[words[x]] = [
                                struct.pack("lH", hashval, x)
                            ]
                            self.settings.num_words += 1
                        self.settings.num_contexts += 1
            else:
                self.lines[hashval][1] += num_context

            #is max_words reached, don't learn more
            if self.settings.num_words >= self.settings.max_words:
                self.settings.learning = 0
Beispiel #38
0
def get_message_body(ql, msg, parts):
    parts = c_int32(parts).value
    if parts >= 0:
        return ql.mem.read(ql.unpack32(ql.mem.read(msg, 4)), ql.unpack32(ql.mem.read(msg + 4, 4)))
    elif parts < 0:
        return ql.mem.read(msg, -parts)
Beispiel #39
0
print '0x%03x: updater1 length = 0x%x. starts at 0x%x' % (updater1header, updater1len, updater1)
print '0x%03x: 0x%x' % ( updater1header + 4, getLongLE( m, updater1header+4 ))
print '0x%03x: 0x%x' % ( updater1header + 8, getLongLE( m, updater1header+8 ))
xorSeed = getLongLE( m, updater1header + 0xc )
print '0x%03x: xor seed value = 0x%x' % ( updater1header + 0xc, xorSeed)
if getLongLE( m, 0xc0 )!=0 or options.zeros:
  print '0x0c0: %s' % hexlify( m[ 0x0c0:0x0d0 ] ) 
  print '0x0d0: %s' % hexlify( m[ 0x0d0:0x0f0 ] ) 
  print '0x0f0: %s' % hexlify( m[ 0x0f0:0x100 ] ) 
  print '0x100: %s' % hexlify( m[ 0x100:0x120 ] ) 
print '0x%03x: --- updater1 (ciphered) ---' % updater1
prefix = '{0:04x}'.format(model & 0xffff) + "_" + m[0x10]+m[0x12]+m[0x14] 
if options.extract:
  decipher_updater( xorSeed, updater1, updater1len, prefix+'_updater1_.bin')

if ctypes.c_int32(updater2header).value!=-1:
  print '---updater2 header---'
  model2 = getLongLE( m, updater2header )
  print '0x%03x: (+0x000), modelId = 0x%08x,' % (updater2header, model2),
  os2, modelName2 = getModel( model2 )
  if (os2 != None):
    print '(%s, %s)' % (modelName2, osName[os2] )
  print '0x%03x: (+0x010), version = %s' % ( updater2header+0x10, m[updater2header+0x10:updater2header+0x10+5] )
  fsum2 = getLongLE( m, updater2header+0x20 )
  print '0x%03x: (+0x020), checksum? = 0x%08x' %  ( updater2header+0x20, fsum2 )
  print '0x%03x: (+0x024), 0x%x' %  ( updater2header+0x24, getLongLE( m, updater2header+0x24 ) )
  print '0x%03x: (+0x028), 0x%x' %  ( updater2header+0x28, getLongLE( m, updater2header+0x28 ) )
  print '0x%03x: (+0x02c),' % (updater2header+0x2c),
  for i in range (3):
    print '%x' %  ( getLongLE( m, updater2header+0x2c+i*4 ) ),
  print
Beispiel #40
0
def check_index(arr_len, index):
    import ctypes

    # 如果数组索引小于0,或者大于等于数组长度,则抛出ArrayIndexOutOfBoundsException异常
    if index < 0 or index >= ctypes.c_int32(arr_len).value:
        raise RuntimeError("ArrayIndexOutOfBoundsException")
Beispiel #41
0
 def meters_fault_rate_x_repair_hrs(self) -> float:
     """Returns the sum of Fault Rate Time Repair Hours in this section of the meter zone."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(5), ctypes.c_double(0)))
Beispiel #42
0
def from_seed(seed):
    for prediction in java.next_bits.from_seed(seed, 32):
        yield c_int32(prediction).value
Beispiel #43
0
def minimum_linear_ip(proto_byte_string: bytes) -> Ip_p:
    return ctypes_minimum_linear_ip(ctypes.c_char_p(proto_byte_string),
                                    ctypes.c_int32(len(proto_byte_string)))
Beispiel #44
0
 def add(self, a, b):
     return self.lib.add(ctypes.c_int32(a), ctypes.c_int32(b))
Beispiel #45
0
    def insert(self, key, value, typeid=None):
        """Insert a new element in the form `key = value` or `key = {value1, ... valueN}` pair.

        The element is inserted only if its `key` is not equivalent to the `key` of any other
        element already in the map (i.e keys must be unique). If the optional parameter `typeid` is
        omitted, the function will try it's best effort to deduce the typeid, otherwise the value
        will be converted to match the type of `typeid` (see :class:`TypeID <serialbox.TypeID>`).

            >>> m = MetainfoMap()
            >>> m.insert('key', 5)
            >>> m
            <MetainfoMap {"key": 5}>
            >>> m.insert('Array', [1, 2, 3, 4])
            >>> m
            <MetainfoMap {"Array": [1, 2, 3, 4], "key": 5}>
            >>> m.insert('Float', 5.0, TypeID.Float32)
            >>> m
            <MetainfoMap {"Array": [1, 2, 3, 4], "Float": 5.000000, "key": 5}>
            >>> type(m['Float'])
            <class 'float'>

        :param key: Key of the new element
        :type key: str
        :param value: Object to be copied to the value of the new element
        :param typeid: Type-id to use
        :type typeid: serialbox.TypeID
        :raises SerialboxError: if element with key already exists or typeid could not be deduced
        :raises TypeError: if `typeid` is not a serialbox.TypeID or int
        """
        isArray = False
        keystr = extract_string(key)[0]

        if typeid and isinstance(typeid, TypeID):
            typeid = typeid.value
        elif typeid and not isinstance(typeid, int):
            raise TypeError(
                "param 'typeid' must be of type serialbox.TypeID or int (type: %s)"
                % type(typeid))

        #
        # Deduce typeid
        #
        if not typeid:

            # Check if type is iterable
            if isinstance(value, list):
                isArray = True
                valueToDeduce = value[0]
            else:
                valueToDeduce = value

            # Deduce primitve type
            if isinstance(valueToDeduce, BooleanTypes):
                typeid = TypeID.Boolean.value
            elif isinstance(valueToDeduce, Int32Types):
                typeid = TypeID.Int32.value
            elif isinstance(valueToDeduce, Int64Types):
                typeid = TypeID.Int64.value
            elif isinstance(valueToDeduce, Float32Types):
                typeid = TypeID.Float32.value
            elif isinstance(valueToDeduce, Float64Types):
                typeid = TypeID.Float64.value
            elif isinstance(valueToDeduce, StringTypes):
                typeid = TypeID.String.value
            else:
                raise SerialboxError(
                    "could not deduce type-id of key '%s' (python type: %s)" %
                    (key, type(value)))

            if isArray:
                typeid |= TypeID.Array.value

        #
        # Insert into map
        #
        ret = 0
        if typeid is TypeID.Boolean.value:
            ret = invoke(lib.serialboxMetainfoAddBoolean, self.__metainfomap,
                         keystr, c_bool(value))

        elif typeid is TypeID.Int32.value:
            ret = invoke(lib.serialboxMetainfoAddInt32, self.__metainfomap,
                         keystr, c_int32(value))

        elif typeid is TypeID.Int64.value:
            ret = invoke(lib.serialboxMetainfoAddInt64, self.__metainfomap,
                         keystr, c_int64(value))

        elif typeid is TypeID.Float32.value:
            ret = invoke(lib.serialboxMetainfoAddFloat32, self.__metainfomap,
                         keystr, c_float(value))

        elif typeid is TypeID.Float64.value:
            ret = invoke(lib.serialboxMetainfoAddFloat64, self.__metainfomap,
                         keystr, c_double(value))

        elif typeid is TypeID.String.value:
            ret = invoke(lib.serialboxMetainfoAddString, self.__metainfomap,
                         keystr,
                         extract_string(value)[0])

        elif typeid is TypeID.ArrayOfBoolean.value:
            array = invoke(lib.serialboxArrayOfBooleanCreate,
                           c_int(len(value)))
            for i in range(array.contents.len):
                array.contents.data[i] = c_int(value[i])
            ret = invoke(lib.serialboxMetainfoAddArrayOfBoolean,
                         self.__metainfomap, keystr, array)
            invoke(lib.serialboxArrayOfBooleanDestroy, array)

        elif typeid is TypeID.ArrayOfInt32.value:
            array = invoke(lib.serialboxArrayOfInt32Create, c_int(len(value)))
            for i in range(array.contents.len):
                array.contents.data[i] = c_int32(value[i])
            ret = invoke(lib.serialboxMetainfoAddArrayOfInt32,
                         self.__metainfomap, keystr, array)
            invoke(lib.serialboxArrayOfInt32Destroy, array)

        elif typeid is TypeID.ArrayOfInt64.value:
            array = invoke(lib.serialboxArrayOfInt64Create, c_int(len(value)))
            for i in range(array.contents.len):
                array.contents.data[i] = c_int64(value[i])
            ret = invoke(lib.serialboxMetainfoAddArrayOfInt64,
                         self.__metainfomap, keystr, array)
            invoke(lib.serialboxArrayOfInt64Destroy, array)

        elif typeid is TypeID.ArrayOfFloat32.value:
            array = invoke(lib.serialboxArrayOfFloat32Create,
                           c_int(len(value)))
            for i in range(array.contents.len):
                array.contents.data[i] = c_float(value[i])
            ret = invoke(lib.serialboxMetainfoAddArrayOfFloat32,
                         self.__metainfomap, keystr, array)
            invoke(lib.serialboxArrayOfFloat32Destroy, array)

        elif typeid is TypeID.ArrayOfFloat64.value:
            array = invoke(lib.serialboxArrayOfFloat64Create,
                           c_int(len(value)))
            for i in range(array.contents.len):
                array.contents.data[i] = c_double(value[i])
            ret = invoke(lib.serialboxMetainfoAddArrayOfFloat64,
                         self.__metainfomap, keystr, array)
            invoke(lib.serialboxArrayOfFloat64Destroy, array)

        elif typeid is TypeID.ArrayOfString.value:
            array = invoke(lib.serialboxArrayOfStringCreate, c_int(len(value)))
            for i in range(array.contents.len):
                array.contents.data[i] = extract_string(value[i])[0]
            ret = invoke(lib.serialboxMetainfoAddArrayOfString,
                         self.__metainfomap, keystr, array)
            invoke(lib.serialboxArrayOfStringDestroy, array)

        else:
            raise SerialboxError('internal error: unreachable (typeid = %s)' %
                                 (typeid))

        if not ret:
            raise SerialboxError("cannot insert key '%s': key already exists" %
                                 key)
    def test_read_multi_vars(self):
        db = 1

        # build and write test values
        test_value_1 = 129.5
        test_bytes_1 = bytearray(struct.pack('>f', test_value_1))
        self.client.db_write(db, 0, test_bytes_1)

        test_value_2 = -129.5
        test_bytes_2 = bytearray(struct.pack('>f', test_value_2))
        self.client.db_write(db, 4, test_bytes_2)

        test_value_3 = 123
        test_bytes_3 = bytearray([0, 0])
        util.set_int(test_bytes_3, 0, test_value_3)
        self.client.db_write(db, 8, test_bytes_3)

        test_values = [test_value_1, test_value_2, test_value_3]

        # build up our requests
        data_items = (S7DataItem * 3)()

        data_items[0].Area = ctypes.c_int32(S7AreaDB)
        data_items[0].WordLen = ctypes.c_int32(S7WLByte)
        data_items[0].Result = ctypes.c_int32(0)
        data_items[0].DBNumber = ctypes.c_int32(db)
        data_items[0].Start = ctypes.c_int32(0)
        data_items[0].Amount = ctypes.c_int32(4)  # reading a REAL, 4 bytes

        data_items[1].Area = ctypes.c_int32(S7AreaDB)
        data_items[1].WordLen = ctypes.c_int32(S7WLByte)
        data_items[1].Result = ctypes.c_int32(0)
        data_items[1].DBNumber = ctypes.c_int32(db)
        data_items[1].Start = ctypes.c_int32(4)
        data_items[1].Amount = ctypes.c_int32(4)  # reading a REAL, 4 bytes

        data_items[2].Area = ctypes.c_int32(S7AreaDB)
        data_items[2].WordLen = ctypes.c_int32(S7WLByte)
        data_items[2].Result = ctypes.c_int32(0)
        data_items[2].DBNumber = ctypes.c_int32(db)
        data_items[2].Start = ctypes.c_int32(8)
        data_items[2].Amount = ctypes.c_int32(2)  # reading an INT, 2 bytes

        # create buffers to receive the data
        # use the Amount attribute on each item to size the buffer
        for di in data_items:
            # create the buffer
            dataBuffer = ctypes.create_string_buffer(di.Amount)
            # get a pointer to the buffer
            pBuffer = ctypes.cast(ctypes.pointer(dataBuffer),
                                  ctypes.POINTER(ctypes.c_uint8))
            di.pData = pBuffer

        result, data_items = self.client.read_multi_vars(data_items)

        result_values = []
        # function to cast bytes to match data_types[] above
        byte_to_value = [util.get_real, util.get_real, util.get_int]

        # unpack and test the result of each read
        for i in range(len(data_items)):
            btv = byte_to_value[i]
            di = data_items[i]
            value = btv(di.pData, 0)
            result_values.append(value)

        self.assertEqual(result_values[0], test_values[0])
        self.assertEqual(result_values[1], test_values[1])
        self.assertEqual(result_values[2], test_values[2])
Beispiel #47
0
def sum_function(data):
    return ctypes_sum_function(
        data.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
        ctypes.c_int32(data.size))
Beispiel #48
0
    def vq(self):
        b = self.TKK
        d = b.split('.')
        b = int(d[0]) | 0
        a = self.wd
        f = 0
        e = []
        g = 0
        c = '&tk='
        while g < len(a):
            l = ord(a[g])
            if 128 > l:
                e.append(l)
                f += 1
            else:
                if 2048 > l:
                    e[f] = c_int32(l >> 6).value | 192
                    f += 1
                else:
                    if (55296 == c_int32(l & 64512).value and g + 1 < a.length
                            and 56320 == c_int32(ord(a[g + 1]) & 64512).value):
                        g += 1
                        l = 65536 + c_int32(
                            (l & 1023) << 10).value + (ord(a[g]) & 1023)
                        e[f] = c_int32(l >> 18).value | 240
                        f += 1
                        e[f] = c_int32(l >> 12).value & 63 | 128
                        f += 1
                    else:
                        e[f] = c_int32(l >> 12).value | 224
                        f += 1
                        e[f] = c_int32(l >> 6).value & 63 | 128
                        f += 1

                    e[f] = c_int32(l >> 6).value & 63 | 128
                    f += 1
            g += 1
        a = b
        f = 0
        while f < len(e):
            a += e[f]
            a = self.tq(a, "+-a^+6")
            f += 1
        a = self.tq(a, "+-3^+b+-f")
        a = c_int32(a ^ int(d[1])).value
        #0 > a & (a = (a & 2147483647) + 2147483648)
        if a < 0:
            a = c_int32(a & 2147483647).value + 2147483648
        a = int(a % 1E6)
        return c + (str(a) + "." + str(a ^ b))
Beispiel #49
0
# offsetVoltage = 0
# pkToPk = 2000000
# waveType = ctypes.c_int16(0) = PS6000_SINE
# startFrequency = 10 kHz
# stopFrequency = 10 kHz
# increment = 0
# dwellTime = 1
# sweepType = ctypes.c_int16(1) = PS6000_UP
# operation = 0
# shots = 0
# sweeps = 0
# triggerType = ctypes.c_int16(0) = PS6000_SIGGEN_RISING
# triggerSource = ctypes.c_int16(0) = PS6000_SIGGEN_NONE
# extInThreshold = 1
wavetype = ctypes.c_int16(0)
sweepType = ctypes.c_int32(0)
triggertype = ctypes.c_int32(0)
triggerSource = ctypes.c_int32(0)

status["SetSigGenBuiltIn"] = ps.ps6000SetSigGenBuiltIn(chandle, 0, 2000000, wavetype, 10000, 10000, 0, 1, sweepType, 0, 0, 0, triggertype, triggerSource, 1)
assert_pico_ok(status["SetSigGenBuiltIn"])

# Pauses the script to show signal
time.sleep(10)

# Output a square wave with peak-to-peak voltage of 2 V and frequency of 10 kHz
# handle = chandle
# offsetVoltage = -1000000
# pkToPk = 1500000
# waveType = ctypes.c_int16(1) = PS6000_SQUARE
# startFrequency = 10 kHz
Beispiel #50
0
 def execute(self, frame):
     stack = frame.operand_stack
     l = stack.pop_numeric()
     i = ctypes.c_int32(l).value
     stack.push_numeric(i)
Beispiel #51
0
 def meters_sum_branch_flt_rates(self) -> float:
     """Returns the sum of the branch fault rates in this section of the meter's zone."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(6), ctypes.c_double(0)))
Beispiel #52
0
def _IOC(dir_, type_, nr, size):
    return (ctypes.c_int32(dir_ << _IOC_DIRSHIFT).value
            | ctypes.c_int32(ord(type_) << _IOC_TYPESHIFT).value
            | ctypes.c_int32(nr << _IOC_NRSHIFT).value
            | ctypes.c_int32(size << _IOC_SIZESHIFT).value)
Beispiel #53
0
 def meters_cust_interrupts(self) -> float:
     """Returns the total customer interruptions for this meter zone based on reliability calcs."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(3), ctypes.c_double(0)))
Beispiel #54
0
 def meters_saifi_kw(self) -> float:
     """Returns the SAIFI based on kW rather than number of customers. Get after reliability calcs."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(1), ctypes.c_double(0)))
Beispiel #55
0
 def meters_saidi(self) -> float:
     """Returns the SAIDI for this meter zone. Execute DoreliabilityCalc first."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(2), ctypes.c_double(0)))
Beispiel #56
0
 def meters_avg_repair_time(self) -> float:
     """Returns the average Repair Time in this Section of the meter zone."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(4), ctypes.c_double(0)))
Beispiel #57
0
 def cmathlib_cabs(self) -> float:
     """Returns the absolute value of complex number given in real (Argument1) and imaginary (Argument2) doubles."""
     return float(
         self.dss_obj.CmathLibF(ctypes.c_int32(0), ctypes.c_double(0)))
Beispiel #58
0
 def cmathlib_cdang(self) -> float:
     """Returns the angle, in degrees, of a complex number specified as two doubles: Real part (Argument1) and
     imaginary part (Argument2)."""
     return float(
         self.dss_obj.CmathLibF(ctypes.c_int32(1), ctypes.c_double(0)))
Beispiel #59
0
    CIRCLE = "○ "
except UnicodeDecodeError:
    TICK = "P "
    CROSS = "x "
    CIRCLE = "o "

if os.name != 'nt' or sys.getwindowsversion() >= (10, 0, 14393):
    if os.name == 'nt':
        import ctypes
        kernel32 = ctypes.windll.kernel32
        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
        STD_OUTPUT_HANDLE = -11
        STD_ERROR_HANDLE = -12
        # Enable ascii color control to stdout
        stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
        stdout_mode = ctypes.c_int32()
        kernel32.GetConsoleMode(stdout, ctypes.byref(stdout_mode))
        kernel32.SetConsoleMode(
            stdout, stdout_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
        # Enable ascii color control to stderr
        stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
        stderr_mode = ctypes.c_int32()
        kernel32.GetConsoleMode(stderr, ctypes.byref(stderr_mode))
        kernel32.SetConsoleMode(
            stderr, stderr_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
    # primitive formatting on supported
    # terminal via ANSI escape sequences:
    BOLD = ('\033[0m', '\033[1m')
    GREEN = ('\033[0m', '\033[0;32m')
    RED = ('\033[0m', '\033[0;31m')
    GREY = ('\033[0m', '\033[1;30m')
Beispiel #60
0
 def meters_saifi(self) -> float:
     """Returns SAIFI for this meter's zone. Execute reliability calc method first."""
     return float(
         self.dss_obj.MetersF(ctypes.c_int32(0), ctypes.c_double(0)))