• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numpy.int8函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.int8函数的典型用法代码示例。如果您正苦于以下问题:Python int8函数的具体用法?Python int8怎么用?Python int8使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了int8函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_sites_summary

def get_sites_summary(noaa_dir, stemxy=False):
    """create a pandas data frame with site code, lon and lat for all
    sites with data files in the specified directory

    ARGS:
    noaa_dir (string): full path to a directory containing NOAA OCS observation
        files

    RETURNS:
    pandas DataFrame object with columns site_code, lon, lat
    """
    all_sites_df = get_all_NOAA_airborne_data(noaa_dir)
    if stemxy:
        dom = domain.STEM_Domain()
        all_sites_df.get_stem_xy(dom.get_lon(), dom.get_lat())
    summary_df = all_sites_df.obs.groupby('sample_site_code').mean()
    if stemxy:
        summary_df = summary_df[['sample_longitude', 'sample_latitude',
                                 'x_stem', 'y_stem']]
        # make sure x, y indices are integers
        summary_df['x_stem'] = np.int8(np.round(summary_df['x_stem']))
        summary_df['y_stem'] = np.int8(np.round(summary_df['y_stem']))
    else:
        summary_df = summary_df[['sample_longitude', 'sample_latitude']]
    summary_df = summary_df.reset_index()
    summary_df.rename(columns={k: k.replace('sample_', '')
                               for k in summary_df.columns.values},
                      inplace=True)
    return(summary_df)
开发者ID:Timothy-W-Hilton,项目名称:STEMPyTools,代码行数:29,代码来源:noaa_ocs.py


示例2: multi_where

def multi_where(vec1, vec2):
    '''Given two vectors, multi_where returns a tuple of indices where those
    two vectors overlap.
    ****THIS FUNCTION HAS NOT BEEN TESTED ON N-DIMENSIONAL ARRAYS*******
    Inputs:
           2 numpy vectors
    Output:
           (xy, yx) where xy is a numpy vector containing the indices of the
           elements in vector 1 that are also in vector 2. yx is a vector
           containing the indices of the elements in vector 2 that are also
           in vector 1.
    Example:
           >> x = np.array([1,2,3,4,5])
           >> y = np.array([3,4,5,6,7])
           >> (xy,yx) = multi_where(x,y)
           >> xy
           array([2,3,4])
           >> yx
           array([0,1,2])
    '''

    OneInTwo = np.array([])
    TwoInOne = np.array([])
    for i in range(vec1.shape[0]):
        if np.where(vec2 == vec1[i])[0].shape[0]:
            OneInTwo = np.append(OneInTwo,i)
            TwoInOne = np.append(TwoInOne, np.where(vec2 == vec1[i])[0][0])

    return (np.int8(OneInTwo), np.int8(TwoInOne))
开发者ID:eigenbrot,项目名称:snakes,代码行数:29,代码来源:ADEUtils.py


示例3: test_apply_scaling

def test_apply_scaling():
    # Null scaling, same array returned
    arr = np.zeros((3,), dtype=np.int16)
    assert_true(apply_read_scaling(arr) is arr)
    assert_true(apply_read_scaling(arr, np.float64(1.0)) is arr)
    assert_true(apply_read_scaling(arr, inter=np.float64(0)) is arr)
    f32, f64 = np.float32, np.float64
    f32_arr = np.zeros((1,), dtype=f32)
    i16_arr = np.zeros((1,), dtype=np.int16)
    # Check float upcast (not the normal numpy scalar rule)
    # This is the normal rule - no upcast from scalar
    assert_equal((f32_arr * f64(1)).dtype, np.float32)
    assert_equal((f32_arr + f64(1)).dtype, np.float32)
    # The function does upcast though
    ret = apply_read_scaling(np.float32(0), np.float64(2))
    assert_equal(ret.dtype, np.float64)
    ret = apply_read_scaling(np.float32(0), inter=np.float64(2))
    assert_equal(ret.dtype, np.float64)
    # Check integer inf upcast
    big = f32(type_info(f32)['max'])
    # Normally this would not upcast
    assert_equal((i16_arr * big).dtype, np.float32)
    # An equivalent case is a little hard to find for the intercept
    nmant_32 = type_info(np.float32)['nmant']
    big_delta = np.float32(2**(floor_log2(big)-nmant_32))
    assert_equal((i16_arr * big_delta + big).dtype, np.float32)
    # Upcasting does occur with this routine
    assert_equal(apply_read_scaling(i16_arr, big).dtype, np.float64)
    assert_equal(apply_read_scaling(i16_arr, big_delta, big).dtype, np.float64)
    assert_equal(apply_read_scaling(np.int8(0), -1.0, 0.0).dtype, np.float32)
    assert_equal(apply_read_scaling(np.int8(0), 1e38, 0.0).dtype, np.float64)
    assert_equal(apply_read_scaling(np.int8(0), -1e38, 0.0).dtype, np.float64)
开发者ID:FNNDSC,项目名称:nibabel,代码行数:32,代码来源:test_utils.py


示例4: test_NumPy_arrayview_deletion_sitkImage_1

    def test_NumPy_arrayview_deletion_sitkImage_1(self):
      # 2D image
      image = sitk.Image(sizeX, sizeY, sitk.sitkInt32)
      for j in range(sizeY):
          for i in range(sizeX):
              image[i, j] = j*sizeX + i

      npview = sitk.GetArrayFromImage(image, arrayview = True, writeable = True)
      image.SetPixel(0,0, newSimpleITKPixelValueInt32)

      del image

      carr = np.array(npview, copy = False)
      rarr = np.reshape(npview, (1, npview.size))
      varr = npview.view(dtype=np.int8)

      self.assertEqual( carr[0,0],newSimpleITKPixelValueInt32)
      self.assertEqual( rarr[0,0],newSimpleITKPixelValueInt32)
      self.assertEqual( varr[0,0],np.int8(newSimpleITKPixelValueInt32))

      npview[0,0] = newNumPyElementValueInt32

      del npview

      self.assertEqual( carr[0,0],newNumPyElementValueInt32)
      self.assertEqual( rarr[0,0],newNumPyElementValueInt32)
      self.assertEqual( varr[0,0],np.int8(newNumPyElementValueInt32))
开发者ID:hyunjaeKang,项目名称:SimpleITKDataBridge,代码行数:27,代码来源:sitkGetArrayViewFromImageTest.py


示例5: moveObject

def moveObject(initial_depthMAT):
    ###########################################################################
    ## Checking each pixel and invoking functions to process pixels on the vessels.
    ###########################################################################
    global done,startx,starty,clock,screen,endx,endy
    global im
    global endpoint
    global current_depth
    global depthMAT
    global rough_range
    global modified_depthMAT,mask_depthMAT
    
    if np.amax(im)!=1:
        ret,im = cv2.threshold(im, 250, 1, cv2.THRESH_BINARY)
    else:
        print np.amax(im)
        np.int8(im)
    mask_depthMAT=initial_depthMAT
    modified_depthMAT=initial_depthMAT
    depthMAT=getDepth(im,modified_depthMAT)
    rough_range=np.median(depthMAT[depthMAT>0])/LEVEL
    im0=np.copy(im)

    convalue_n=Neigh_Cov(im0)

    cols=im.shape[1]
    rows=im.shape[0]

    for y in range(0,rows,1): 
        for x in range(0,cols,1):
            if im[y][x]==1:
                fillPixel(x,y,convalue_n)

    return convalue_n
开发者ID:JasmineLei,项目名称:Blood-Vessel-Flow-Visualisation,代码行数:34,代码来源:layer.py


示例6: classify

 def classify(self, inputs):
     # switch to test mode
     self.mode.set_value(np.int8(1))
     rval = self._classify(inputs)
     # switch to train mode
     self.mode.set_value(np.int8(0))
     return rval
开发者ID:OuYag,项目名称:Emotion-Recognition-RNN,代码行数:7,代码来源:fusion.py


示例7: process

    def process(self, target, **kwargs):
        """ Filter the image leaving only the required annulus. """
        # Check target type
        if target.name() != 'Image':
            self.logger.warning("[%s] Input variable is not an image. Skipping.", self.name())
            return {'output': None}
        # Check that inner and outer diameter are defined
        if self._inner is None or self._outer is None:
            self.logger.warning("[%s] One of the required diameter is not set. Skipping.", self.name())
            return {'output': None}

        # If size has changed or mask is not defined, we prepare it
        if self._mask is None or target.value.shape[1:] != self._size:
            self._size = target.value.shape[1:]
            if self._center is None:
                self._center = [int(target.value.shape[2] / 2), int(target.value.shape[1] / 2)]

            # Build the mask
            y, x = np.ogrid[0:self._size[0], 0:self._size[1]]
            x -= self._center[0]
            y -= self._center[1]
            r_in = x ** 2 / self._inner[0] + y ** 2 / self._inner[1]
            r_out = x ** 2 / self._outer[0] + y ** 2 / self._outer[1]
            self._mask = np.int8(r_in > 1) * np.int8(r_out < 1)

        # Filter the image using the defined mask
        self.logger.debug("[%s] Image shape %s, Mask shape %s.", self.name(), target.value.shape, self._mask.shape)
        out = Image()
        out.value = np.copy(target.value) * np.tile(self._mask, (target.value.shape[0], 1, 1))
        return {'output': out}
开发者ID:wyrdmeister,项目名称:OnlineAnalysis,代码行数:30,代码来源:Image.py


示例8: add_vars_to_grp

def add_vars_to_grp(grp,types, **kwargs):
    v = grp.createVariable(kwargs.get('var1','var1'),numpy.int8)
    v[:] = numpy.int8(8)
    v.foo = 'bar'
    
    v = grp.createVariable(kwargs.get('var2','var2'),numpy.int8, (dim3._name,), fill_value=5)
    v[:] = numpy.int8(8)
    v.foo = 'bar'
    
    v = grp.createVariable(kwargs.get('var3','var3'),numpy.int8, (dim1._name,dim4._name,))
    v[:] = numpy.arange(8,dtype=numpy.int8).reshape(2,4)
    v.foo = 'bar'
    
    v = grp.createVariable(kwargs.get('var4','var4'),'S1', (dim1._name,dim4._name,))
    #v[:] = numpy.ndarray(8,dtype='S1').reshape(2,4)
    v[:] = 'a'
    v.foo = 'bar'
    
    for num,type in enumerate(types):    
        default_name = 'var{}'.format(num+5)
        print default_name
        v = grp.createVariable(kwargs.get(default_name,default_name),type, (dim4._name,))
        try:
            v[:] = numpy.iinfo(type).max
            continue
        except ValueError:
            pass
        try:
            for i,c in enumerate('char'):
                v[i] = c 
            continue
        except ValueError:
            pass
       
        v[:] = numpy.pi
开发者ID:benjwadams,项目名称:petulant-bear,代码行数:35,代码来源:create_test_nc_file.py


示例9: parse_objects

 def parse_objects(self, data):
     x = y = dx = dy = count = 0
     addr = None
     objects = []
     data = np.array(data, dtype=np.uint8)
     last = len(data)
     index = 0
     while index < last:
         c = data[index]
         log.debug("index=%d, command=%x" % (index, c))
         self.pick_index += 1
         index += 1
         command = None
         if c < 0xfb:
             if addr is not None:
                 obj = self.get_object(self.pick_index, x, y, c, dx, dy, addr)
                 objects.append(obj)
         elif c >= 0xfc and c <= 0xfe:
             arg1 = data[index]
             arg2 = data[index + 1]
             index += 2
             if c == 0xfc:
                 addr = arg2 * 256 + arg1
             elif c == 0xfd:
                 x = int(arg1)
                 y = int(arg2)
             else:
                 dx = int(np.int8(arg1))  # signed!
                 dy = int(np.int8(arg2))
         elif c == 0xff:
             last = 0  # force the end
     return objects
开发者ID:robmcmullen,项目名称:omnivore,代码行数:32,代码来源:parser.py


示例10: test_valid

    def test_valid(self):
        prop = bcpp.Int()

        assert prop.is_valid(None)

        assert prop.is_valid(0)
        assert prop.is_valid(1)

        assert prop.is_valid(np.int8(0))
        assert prop.is_valid(np.int8(1))
        assert prop.is_valid(np.int16(0))
        assert prop.is_valid(np.int16(1))
        assert prop.is_valid(np.int32(0))
        assert prop.is_valid(np.int32(1))
        assert prop.is_valid(np.int64(0))
        assert prop.is_valid(np.int64(1))
        assert prop.is_valid(np.uint8(0))
        assert prop.is_valid(np.uint8(1))
        assert prop.is_valid(np.uint16(0))
        assert prop.is_valid(np.uint16(1))
        assert prop.is_valid(np.uint32(0))
        assert prop.is_valid(np.uint32(1))
        assert prop.is_valid(np.uint64(0))
        assert prop.is_valid(np.uint64(1))

        # TODO (bev) should fail
        assert prop.is_valid(False)
        assert prop.is_valid(True)
开发者ID:jakirkham,项目名称:bokeh,代码行数:28,代码来源:test_primitive.py


示例11: test_numpy

    def test_numpy(self):
        assert chash(np.bool_(True)) == chash(np.bool_(True))

        assert chash(np.int8(1)) == chash(np.int8(1))
        assert chash(np.int16(1))
        assert chash(np.int32(1))
        assert chash(np.int64(1))

        assert chash(np.uint8(1))
        assert chash(np.uint16(1))
        assert chash(np.uint32(1))
        assert chash(np.uint64(1))

        assert chash(np.float32(1)) == chash(np.float32(1))
        assert chash(np.float64(1)) == chash(np.float64(1))
        assert chash(np.float128(1)) == chash(np.float128(1))

        assert chash(np.complex64(1+1j)) == chash(np.complex64(1+1j))
        assert chash(np.complex128(1+1j)) == chash(np.complex128(1+1j))
        assert chash(np.complex256(1+1j)) == chash(np.complex256(1+1j))

        assert chash(np.datetime64('2000-01-01')) == chash(np.datetime64('2000-01-01'))
        assert chash(np.timedelta64(1,'W')) == chash(np.timedelta64(1,'W'))

        self.assertRaises(ValueError, chash, np.object())

        assert chash(np.array([[1, 2], [3, 4]])) == \
            chash(np.array([[1, 2], [3, 4]]))
        assert chash(np.array([[1, 2], [3, 4]])) != \
            chash(np.array([[1, 2], [3, 4]]).T)
        assert chash(np.array([1, 2, 3])) == chash(np.array([1, 2, 3]))
        assert chash(np.array([1, 2, 3], dtype=np.int32)) != \
            chash(np.array([1, 2, 3], dtype=np.int64))
开发者ID:lebedov,项目名称:chash,代码行数:33,代码来源:test_chash.py


示例12: chain2image

def chain2image(chaincode,start_pix):

    """
    Method to compute the pixel contour providing the chain code string
    and the starting pixel location [X,Y].
    Author: Xavier Bonnin (LESIA)
    """

    if (type(chaincode) != str):
        print "First input argument must be a string!"
        return None

    if (len(start_pix) != 2):
        print "Second input argument must be a 2-elements vector!"
        return None

    ardir = np.array([[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]])
    ccdir = np.array([0,7,6,5,4,3,2,1])

    X=[start_pix[0]]
    Y=[start_pix[1]]
    for c in chaincode:
        if (abs(np.int8(c)) > 7):
            print "Wrong chain code format!"
            return None
        wc = np.where(np.int8(c) == np.int8(ccdir))[0]
        X.append(X[-1] + np.int(ardir[wc,0]))
        Y.append(Y[-1] + np.int(ardir[wc,1]))
    return X,Y
开发者ID:HELIO-HFC,项目名称:SPoCA,代码行数:29,代码来源:improlib.py


示例13: result_dict_to_hdf5

def result_dict_to_hdf5(f, rd):
    for name, data in rd.items():
        flag = None
        # beware: isinstance(True/False, int) == True
        if isinstance(data, bool):
            data = np.int8(data)
            flag = "py_bool"
        elif isinstance(data, int):
            data = np.int64(data)
            flag = "py_int"

        if isinstance(data, np.ndarray):
            dataset = f.create_dataset(name, data=data)
        else:
            ty = type(data)
            if ty is str:
                ty_h5 = "S{}".format(len(data))
                data = data.encode()
            else:
                try:
                    ty_h5 = _type_to_hdf5[ty]
                except KeyError:
                    raise TypeError("Type {} is not supported for HDF5 output"
                                    .format(ty)) from None
            dataset = f.create_dataset(name, (), ty_h5)
            dataset[()] = data

        if flag is not None:
            dataset.attrs[flag] = np.int8(1)
开发者ID:carriercomm,项目名称:artiq,代码行数:29,代码来源:worker_db.py


示例14: conv_int8

def conv_int8( value ):
    if( len(value) == 0 ):
        rval = imiss
    else:
        rval = int( value )
    assert numpy.int8( rval ) == numpy.int32( rval ) , " conv_int8: value out of range"
    return numpy.int8( rval )
开发者ID:glamod,项目名称:icoads2cdm,代码行数:7,代码来源:functions.py_save.py


示例15: process

    def process(self, image,
                dark=None,
                variance=None,
                dark_variance=None,
                normalization_factor=1.0
                ):
        """Perform the pixel-wise operation of the array

        :param raw: numpy array with the input image
        :param dark: numpy array with the dark-current image
        :param variance: numpy array with the variance of input image
        :param dark_variance: numpy array with the variance of dark-current image
        :param normalization_factor: divide the result by this
        :return: array with processed data,
                may be an array of (data,variance,normalization) depending on class initialization
        """
        with self.sem:
            if id(image) != id(self.on_device.get("image")):
                self.send_buffer(image, "image")

            if dark is not None:
                do_dark = numpy.int8(1)
                if id(dark) != id(self.on_device.get("dark")):
                    self.send_buffer(dark, "dark")
            else:
                do_dark = numpy.int8(0)
            if (variance is not None) and self.on_host.get("calc_variance"):
                if id(variance) != id(self.on_device.get("variance")):
                    self.send_buffer(variance, "variance")
            if (dark_variance is not None) and self.on_host.get("calc_variance"):
                if id(dark_variance) != id(self.on_device.get("dark_variance")):
                    self.send_buffer(dark_variance, "dark_variance")

            if self.on_host.get("poissonian"):
                kernel_name = "corrections3Poisson"
            elif self.on_host.get("calc_variance"):
                kernel_name = "corrections3"
            elif self.on_host.get("split_result"):
                kernel_name = "corrections2"
            else:
                kernel_name = "corrections"
            kwargs = self.cl_kernel_args[kernel_name]
            kwargs["do_dark"] = do_dark
            kwargs["normalization_factor"] = numpy.float32(normalization_factor)
            if (kernel_name == "corrections3") and (self.on_device.get("dark_variance") is not None):
                kwargs["do_dark_variance"] = do_dark
            kernel = self.kernels.get_kernel(kernel_name)
            evt = kernel(self.queue, (self.size,), None, *list(kwargs.values()))
            if kernel_name.startswith("corrections3"):
                dest = numpy.empty(self.on_device.get("image").shape + (3,), dtype=numpy.float32)
            elif kernel_name == "corrections2":
                dest = numpy.empty(self.on_device.get("image").shape + (2,), dtype=numpy.float32)
            else:
                dest = numpy.empty(self.on_device.get("image").shape, dtype=numpy.float32)

            copy_result = pyopencl.enqueue_copy(self.queue, dest, self.cl_mem["output"])
            copy_result.wait()
            if self.profile:
                self.events += [EventDescription("preproc", evt), EventDescription("copy result", copy_result)]
        return dest
开发者ID:kif,项目名称:pyFAI,代码行数:60,代码来源:preproc.py


示例16: test_numpy_scalar_conversion_values

 def test_numpy_scalar_conversion_values(self):
     self.assertEqual(nd.as_py(nd.array(np.bool_(True))), True)
     self.assertEqual(nd.as_py(nd.array(np.bool_(False))), False)
     self.assertEqual(nd.as_py(nd.array(np.int8(100))), 100)
     self.assertEqual(nd.as_py(nd.array(np.int8(-100))), -100)
     self.assertEqual(nd.as_py(nd.array(np.int16(20000))), 20000)
     self.assertEqual(nd.as_py(nd.array(np.int16(-20000))), -20000)
     self.assertEqual(nd.as_py(nd.array(np.int32(1000000000))), 1000000000)
     self.assertEqual(nd.as_py(nd.array(np.int64(-1000000000000))),
                      -1000000000000)
     self.assertEqual(nd.as_py(nd.array(np.int64(1000000000000))),
                      1000000000000)
     self.assertEqual(nd.as_py(nd.array(np.int32(-1000000000))),
                      -1000000000)
     self.assertEqual(nd.as_py(nd.array(np.uint8(200))), 200)
     self.assertEqual(nd.as_py(nd.array(np.uint16(50000))), 50000)
     self.assertEqual(nd.as_py(nd.array(np.uint32(3000000000))), 3000000000)
     self.assertEqual(nd.as_py(nd.array(np.uint64(10000000000000000000))),
                      10000000000000000000)
     self.assertEqual(nd.as_py(nd.array(np.float32(2.5))), 2.5)
     self.assertEqual(nd.as_py(nd.array(np.float64(2.5))), 2.5)
     self.assertEqual(nd.as_py(nd.array(np.complex64(2.5-1j))), 2.5-1j)
     self.assertEqual(nd.as_py(nd.array(np.complex128(2.5-1j))), 2.5-1j)
     if np.__version__ >= '1.7':
         self.assertEqual(nd.as_py(nd.array(np.datetime64('2000-12-13'))),
                          date(2000, 12, 13))
开发者ID:garaud,项目名称:dynd-python,代码行数:26,代码来源:test_numpy_interop.py


示例17: testInt

    def testInt(self):
        num = np.int(2562010)
        self.assertEqual(np.int(ujson.decode(ujson.encode(num))), num)

        num = np.int8(127)
        self.assertEqual(np.int8(ujson.decode(ujson.encode(num))), num)

        num = np.int16(2562010)
        self.assertEqual(np.int16(ujson.decode(ujson.encode(num))), num)

        num = np.int32(2562010)
        self.assertEqual(np.int32(ujson.decode(ujson.encode(num))), num)

        num = np.int64(2562010)
        self.assertEqual(np.int64(ujson.decode(ujson.encode(num))), num)

        num = np.uint8(255)
        self.assertEqual(np.uint8(ujson.decode(ujson.encode(num))), num)

        num = np.uint16(2562010)
        self.assertEqual(np.uint16(ujson.decode(ujson.encode(num))), num)

        num = np.uint32(2562010)
        self.assertEqual(np.uint32(ujson.decode(ujson.encode(num))), num)

        num = np.uint64(2562010)
        self.assertEqual(np.uint64(ujson.decode(ujson.encode(num))), num)
开发者ID:paddymul,项目名称:pandas,代码行数:27,代码来源:test_ujson.py


示例18: testIntMax

    def testIntMax(self):
        num = np.int(np.iinfo(np.int).max)
        self.assertEqual(np.int(ujson.decode(ujson.encode(num))), num)

        num = np.int8(np.iinfo(np.int8).max)
        self.assertEqual(np.int8(ujson.decode(ujson.encode(num))), num)

        num = np.int16(np.iinfo(np.int16).max)
        self.assertEqual(np.int16(ujson.decode(ujson.encode(num))), num)

        num = np.int32(np.iinfo(np.int32).max)
        self.assertEqual(np.int32(ujson.decode(ujson.encode(num))), num)

        num = np.uint8(np.iinfo(np.uint8).max)
        self.assertEqual(np.uint8(ujson.decode(ujson.encode(num))), num)

        num = np.uint16(np.iinfo(np.uint16).max)
        self.assertEqual(np.uint16(ujson.decode(ujson.encode(num))), num)

        num = np.uint32(np.iinfo(np.uint32).max)
        self.assertEqual(np.uint32(ujson.decode(ujson.encode(num))), num)

        if platform.architecture()[0] != '32bit':
            num = np.int64(np.iinfo(np.int64).max)
            self.assertEqual(np.int64(ujson.decode(ujson.encode(num))), num)

            # uint64 max will always overflow as it's encoded to signed
            num = np.uint64(np.iinfo(np.int64).max)
            self.assertEqual(np.uint64(ujson.decode(ujson.encode(num))), num)
开发者ID:paddymul,项目名称:pandas,代码行数:29,代码来源:test_ujson.py


示例19: test_is_int

def test_is_int():
    # is int
    assert isinstance(1, int) is True
    assert isinstance(np.int(1), int) is True
    assert isinstance(np.int8(1), int) is False
    assert isinstance(np.int16(1), int) is False

    if PY3:
        assert isinstance(np.int32(1), int) is False
    elif PY2:
        assert isinstance(np.int32(1), int) is True

    assert isinstance(np.int64(1), int) is False

    # is np.int
    assert isinstance(np.int(1), np.int) is True
    assert isinstance(np.int8(1), np.int) is False
    assert isinstance(np.int16(1), np.int) is False

    if PY3:
        assert isinstance(np.int32(1), np.int) is False
    elif PY2:
        assert isinstance(np.int32(1), np.int) is True

    assert isinstance(np.int64(1), np.int) is False
开发者ID:MacHu-GWU,项目名称:convert2-project,代码行数:25,代码来源:dev_only_isinstance.py


示例20: read_serial_thread

def read_serial_thread():
    # all global variables this function can modify:
    global IR_0, IR_1, IR_2, IR_3, IR_4, IR_Yaw_right, IR_Yaw_left, Yaw, p_part, alpha, Kp, Kd, AUTO_STATE, manual_state, mode, blue_percentage

    while 1:
        no_of_bytes_waiting = serial_port.inWaiting()
        if no_of_bytes_waiting > 19: # the ardu sends 20 bytes at the time (18 data, 2 control)
            # read the first byte (read 1 byte): (ord: gives the actual value of the byte)
            first_byte = np.uint8(ord(serial_port.read(size = 1))) 
            
            # read all data bytes if first byte was the start byte:
            if first_byte == 100:
                serial_data = []
                # read all data bytes:
                for counter in range(18): # 18 data bytes is sent from the ardu
                    serial_data.append(ord(serial_port.read(size = 1)))
                
                # read the received checksum:
                checksum = np.uint8(ord(serial_port.read(size = 1)))
                
                # calculate checksum for the received data bytes: (pleae note that the use of uint8 and int8 exactly match what is sent from the arduino)
                calc_checksum = np.uint8(np.uint8(serial_data[0]) + np.uint8(serial_data[1]) + 
                    np.uint8(serial_data[2]) + np.uint8(serial_data[3]) + np.uint8(serial_data[4]) + 
                    np.int8(serial_data[5]) + np.int8(serial_data[6]) + np.int8(serial_data[7]) + 
                    np.int8(serial_data[8]) + np.int8(serial_data[9]) + np.int8(serial_data[10]) + 
                    np.uint8(serial_data[11]) + np.uint8(serial_data[12]) + np.uint8(serial_data[13]) + 
                    np.uint8(serial_data[14]) + np.uint8(serial_data[15]) + np.uint8(serial_data[16]) + np.uint8(serial_data[17]))

                # update the variables with the read serial data only if the checksums match:
                if calc_checksum == checksum:
                    IR_0 = int(np.uint8(serial_data[0])) # (int() is needed to convert it to something that can be sent to the webpage) 
                    IR_1 = int(np.uint8(serial_data[1]))
                    IR_2 = int(np.uint8(serial_data[2]))
                    IR_3 = int(np.uint8(serial_data[3]))
                    IR_4 = int(np.uint8(serial_data[4]))
                    IR_Yaw_right = int(np.int8(serial_data[5])) # IR_Yaw_right was sent as an int8_t, but in order to make python treat it as one we first need to tell it so explicitly with the help of numpy, before converting the result (a number between -128 and +127) to the corresponding python int 
                    IR_Yaw_left = int(np.int8(serial_data[6]))
                    Yaw = int(np.int8(serial_data[7]))
                    p_part = int(np.int8(serial_data[8]))
                    alpha_low_byte = np.uint8(serial_data[9])
                    alpha_high_byte = np.uint8(serial_data[10]) # yes, we need to first treat both the low and high bytes as uint8:s, try it by hand and a simple example (try sending -1)
                    alpha = int(np.int16(alpha_low_byte + alpha_high_byte*256)) # (mult with 256 corresponds to a 8 bit left shift)
                    Kp = int(np.uint8(serial_data[11]))
                    Kd_low_byte = np.uint8(serial_data[12])
                    Kd_high_byte = np.uint8(serial_data[13])
                    Kd = int(Kd_low_byte + Kd_high_byte*256)
                    AUTO_STATE = auto_states[int(np.uint8(serial_data[14]))] # look up the received integer in the auto_states dict
                    manual_state = manual_states[int(np.uint8(serial_data[15]))]
                    mode = mode_states[int(np.uint8(serial_data[16]))]
                    blue_percentage = int(np.uint8(serial_data[17]))
                else: # if the checksums doesn't match: something weird has happened during transmission: flush input buffer and start over
                    serial_port.flushInput()
                    print("Something went wrong in the transaction: checksums didn't match!")                      
            else: # if first byte isn't the start byte: we're not in sync: just read the next byte until we get in sync (until we reach the start byte)
                pass
        else: # if not enough bytes for entire transmission, just wait for more data:
            pass

        time.sleep(0.025) # Delay for ~40 Hz loop frequency (faster than the sending frequency)
开发者ID:dirac-hatt,项目名称:Sommarprojekt16,代码行数:59,代码来源:__init__.py



注:本文中的numpy.int8函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numpy.int_函数代码示例发布时间:2022-05-27
下一篇:
Python numpy.int64函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap