Ejemplo n.º 1
0
    def getDiskSpace(self):

        free_space = {}
        for folder in self.directories():

            size = None
            if os.path.isdir(folder):
                if os.name == 'nt':
                    _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), \
                                       ctypes.c_ulonglong()
                    if sys.version_info >= (3,) or isinstance(folder, unicode):
                        fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW #@UndefinedVariable
                    else:
                        fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA #@UndefinedVariable
                    ret = fun(folder, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
                    if ret == 0:
                        raise ctypes.WinError()
                    used = total.value - free.value
                    return [total.value, used, free.value]
                else:
                    s = os.statvfs(folder)
                    size = [s.f_blocks * s.f_frsize / (1024 * 1024), (s.f_bavail * s.f_frsize) / (1024 * 1024)]

            free_space[folder] = size

        return free_space
Ejemplo n.º 2
0
def cs_disasm_lite(arch, mode, code, offset, count = 0):
    # verify version compatibility with the core before doing anything
    (major, minor, _combined) = cs_version()
    if major != CS_API_MAJOR or minor != CS_API_MINOR:
        # our binding version is different from the core's API version
        raise CsError(CS_ERR_VERSION)

    if cs_support(CS_SUPPORT_DIET):
        # Diet engine cannot provide @mnemonic & @op_str
        raise CsError(CS_ERR_DIET)

    csh = ctypes.c_size_t()
    status = _cs.cs_open(arch, mode, ctypes.byref(csh))
    if status != CS_ERR_OK:
        raise CsError(status)

    all_insn = ctypes.POINTER(_cs_insn)()
    res = _cs.cs_disasm_ex(csh, code, len(code), offset, count, ctypes.byref(all_insn))
    if res > 0:
        for i in xrange(res):
            insn = all_insn[i]
            yield (insn.address, insn.size, insn.mnemonic, insn.op_str)

        _cs.cs_free(all_insn, res)
    else:
        status = _cs.cs_errno(csh)
        if status != CS_ERR_OK:
            raise CsError(status)
        return
        yield

    status = _cs.cs_close(ctypes.byref(csh))
    if status != CS_ERR_OK:
        raise CsError(status)
Ejemplo n.º 3
0
def get_device_info_detail(dev=0):
    """Get an entry from the internal device info list. """
    dwIndex = c.c_ulong(dev)
    lpdwFlags = c.c_ulong()
    lpdwType = c.c_ulong()
    lpdwID = c.c_ulong()
    lpdwLocId = c.c_ulong()
    pcSerialNumber = c.c_buffer(MAX_DESCRIPTION_SIZE)
    pcDescription = c.c_buffer(MAX_DESCRIPTION_SIZE)
    ftHandle = c.c_ulong()
    _PY_GetDeviceInfoDetail(dwIndex,
                                c.byref(lpdwFlags),
                                c.byref(lpdwType),
                                c.byref(lpdwID),
                                c.byref(lpdwLocId),
                                pcSerialNumber,
                                pcDescription,
                                c.byref(ftHandle))
    return {'Dev': dwIndex.value,
            'Flags': lpdwFlags.value,
            'Type': lpdwType.value,
            'ID': lpdwID.value,
            'LocId': lpdwLocId.value,
            'SerialNumber': pcSerialNumber.value,
            'Description': pcDescription.value,
            'ftHandle': ftHandle}
Ejemplo n.º 4
0
  def read_directory_changes(handle, event_buffer, recursive):
    """Read changes to the directory using the specified directory handle.

    http://timgolden.me.uk/pywin32-docs/win32file__ReadDirectoryChangesW_meth.html
    """
    nbytes = ctypes.wintypes.DWORD()
    try:
      ReadDirectoryChangesW(handle,
                            ctypes.byref(event_buffer),
                            len(event_buffer),
                            recursive,
                            WATCHDOG_FILE_NOTIFY_FLAGS,
                            ctypes.byref(nbytes),
                            None,
                            None)
    except WindowsError:
      return [], 0
    # get_FILE_NOTIFY_INFORMATION expects nBytes to be long.

    # Python 2/3 compat
    try:
      int_class = long
    except NameError:
      int_class = int
    return event_buffer.raw, int_class(nbytes.value)
Ejemplo n.º 5
0
def cs_disasm_quick(arch, mode, code, offset, count = 0):
    # verify version compatibility with the core before doing anything
    (major, minor, _combined) = cs_version()
    if major != CS_API_MAJOR or minor != CS_API_MINOR:
        # our binding version is different from the core's API version
        raise CsError(CS_ERR_VERSION)

    csh = ctypes.c_size_t()
    status = _cs.cs_open(arch, mode, ctypes.byref(csh))
    if status != CS_ERR_OK:
        raise CsError(status)

    all_insn = ctypes.POINTER(_cs_insn)()
    res = _cs.cs_disasm_ex(csh, code, len(code), offset, count, ctypes.byref(all_insn))
    if res > 0:
        for i in xrange(res):
            yield CsInsn(_dummy_cs(csh, arch), all_insn[i])

        _cs.cs_free(all_insn, res)
    else:
        status = _cs.cs_errno(csh)
        if status != CS_ERR_OK:
            raise CsError(status)
        return
        yield

    status = _cs.cs_close(ctypes.byref(csh))
    if status != CS_ERR_OK:
        raise CsError(status)
Ejemplo n.º 6
0
    def get_multi_raw(self, keys):
        keys = [key for key in keys if self.check_key(key)]
        n = len(keys)
        ckeys = (ctypes.c_char_p * n)(*keys)
        lens = (ctypes.c_size_t * n)(*[len(k) for k in keys])
        c.memcached_mget(self.mc, ckeys, lens, n)    

        result = {}
        chunks_record = []
        while True:
            key = ctypes.create_string_buffer(200)
            klen, vlen, flag, rc = ctypes.c_size_t(0), ctypes.c_size_t(0), ctypes.c_uint32(0), ctypes.c_int(0)
            val = c.memcached_fetch(self.mc, key, ctypes.byref(klen), 
                ctypes.byref(vlen), ctypes.byref(flag), ctypes.byref(rc))
            if not val:
                break
            key = key.value
            val = ctypes.string_at(val, vlen.value)
            flag = flag.value
            if flag & _FLAG_CHUNKED:
                chunks_record.append((key, int(val), flag))
            else:
                result[key] = (val, flag)
        
        for key, count, flag in chunks_record:
            val, flag = self._get_raw_split(key, count, flag)
            if val: 
                result[key] = (val, flag)
        
        return result
Ejemplo n.º 7
0
    def get_filepath(self):
        """Get process image file path.
        @return: decoded file path.
        """
        if not self.h_process:
            self.open()

        NT_SUCCESS = lambda val: val >= 0

        pbi = create_string_buffer(200)
        size = c_int()

        # Set return value to signed 32bit integer.
        NTDLL.NtQueryInformationProcess.restype = c_int

        ret = NTDLL.NtQueryInformationProcess(self.h_process,
                                              27,
                                              byref(pbi),
                                              sizeof(pbi),
                                              byref(size))

        if NT_SUCCESS(ret) and size.value > 8:
            try:
                fbuf = pbi.raw[8:]
                fbuf = fbuf[:fbuf.find('\0\0')+1]
                return fbuf.decode('utf16', errors="ignore")
            except:
                return ""

        return ""
Ejemplo n.º 8
0
    def initiator_transceive_bytes(self, inbytes):
        """Sends a series of bytes, returning those bytes sent back by the target"""
        if self.verbosity > 0: print 'R>T[%2X]: %s' % (len(inbytes), hexbytes(inbytes))
        insize = min(len(inbytes), MAX_FRAME_LEN)
        for i in range(insize):
            self._txbytes[i] = ord(inbytes[i])

        rxbytelen = _size_t(0)

        result = _lib.nfc_initiator_transceive_bytes(self._device,
                                                    ctypes.byref(self._txbytes),
                                                    _size_t(insize),
                                                    ctypes.byref(self._rxbytes),
                                                    ctypes.byref(rxbytelen))

        if not result:
            if self.verbosity > 0: print 'T%2X[--]:' % (result)
            return None

        if self.verbosity > 0: print 'T%2X[%2X]: %s' % (result, rxbytelen.value, hexbytes(buffer(self._rxbytes)[:rxbytelen.value]))

        result = ""
        for i in range(min(rxbytelen.value, MAX_FRAME_LEN)):
            result += chr(self._rxbytes[i])

        return result
Ejemplo n.º 9
0
    def win_pick(window, starting_color):
        paste = None
        start_color = None
        if starting_color is not None:
            start_color = hexstr_to_bgr(starting_color[1:])
        s = sublime.load_settings("ColorPicker.sublime-settings")
        custom_colors = s.get("custom_colors", ['0'] * 16)

        if len(custom_colors) < 16:
            custom_colors = ['0'] * 16
            s.set('custom_colors', custom_colors)

        cc = CHOOSECOLOR()
        ctypes.memset(ctypes.byref(cc), 0, ctypes.sizeof(cc))
        cc.lStructSize = ctypes.sizeof(cc)

        if sublime_version == 2:
            cc.hwndOwner = window.hwnd()
        else:
            # Temporary fix for Sublime Text 3 - For some reason the hwnd crashes it
            # Of course, clicking out of the colour picker and into Sublime will make
            # Sublime not respond, but as soon as you exit the colour picker it's ok
            cc.hwndOwner = None

        cc.Flags = CC_SOLIDCOLOR | CC_FULLOPEN | CC_RGBINIT
        cc.rgbResult = c_uint32(start_color) if not paste and start_color else get_pixel()
        cc.lpCustColors = to_custom_color_array(custom_colors)

        if ChooseColorW(ctypes.byref(cc)):
            color = bgr_to_hexstr(cc.rgbResult)
        else:
            color = None

        return color
Ejemplo n.º 10
0
    def mds_command(self, mds_spec, args, input_data):
        """
        :return 3-tuple of output status int, output status string, output data
        """

        cmdarr = (c_char_p * len(args))(*args)

        outbufp = pointer(pointer(c_char()))
        outbuflen = c_long()
        outsp = pointer(pointer(c_char()))
        outslen = c_long()

        ret = self.libcephfs.ceph_mds_command(self.cluster, c_char_p(mds_spec),
                                              cmdarr, len(args),
                                              c_char_p(input_data),
                                              len(input_data), outbufp,
                                              byref(outbuflen), outsp,
                                              byref(outslen))

        my_outbuf = outbufp.contents[:(outbuflen.value)]
        my_outs = outsp.contents[:(outslen.value)]
        if outbuflen.value:
            self.libcephfs.ceph_buffer_free(outbufp.contents)
        if outslen.value:
            self.libcephfs.ceph_buffer_free(outsp.contents)

        return (ret, my_outbuf, my_outs)
Ejemplo n.º 11
0
def imsavetoblob(img, filetype, flags=0):
    """
    s = imsavetoblob(img, filetype, flags=0)

    Save `img` to a `str` object

    Parameters
    ----------
    img : ndarray
        input image
    filetype : str or integer
        A file name like string, used only to determine the file type.
        Alternatively, an integer flag (from FI_FORMAT).
    flags : integer, optional

    Returns
    -------
    s : str
        byte representation of `img` in format `filetype`
    """
    if type(filetype) == str:
        ftype = _FI.FreeImage_GetFIFFromFilename(_bytestr(filetype))
    else:
        ftype = filetype
    try:
        bitmap, fi_type = _array_to_bitmap(img)
        mem = _FI.FreeImage_OpenMemory(0, 0)
        if not _FI.FreeImage_SaveToMemory(ftype, bitmap, mem, flags):
            raise IOError("mahotas.freeimage.imsavetoblob: Cannot save to memory.")
        data = ctypes.c_void_p()
        size = ctypes.c_int()
        _FI.FreeImage_AcquireMemory(mem, ctypes.byref(data), ctypes.byref(size))
        return ctypes.string_at(data, size)
    finally:
        _FI.FreeImage_CloseMemory(mem)
Ejemplo n.º 12
0
def execElevated(path, params=None, wait=False,handleAlreadyElevated=False):
	import subprocess
	import shellapi
	import winKernel
	import winUser
	if params is not None:
		params = subprocess.list2cmdline(params)
	sei = shellapi.SHELLEXECUTEINFO(lpFile=os.path.abspath(path), lpParameters=params, nShow=winUser.SW_HIDE)
	#IsUserAnAdmin is apparently deprecated so may not work above Windows 8
	if not handleAlreadyElevated or not ctypes.windll.shell32.IsUserAnAdmin():
		sei.lpVerb=u"runas"
	if wait:
		sei.fMask = shellapi.SEE_MASK_NOCLOSEPROCESS
	shellapi.ShellExecuteEx(sei)
	if wait:
		try:
			h=ctypes.wintypes.HANDLE(sei.hProcess)
			msg=ctypes.wintypes.MSG()
			while ctypes.windll.user32.MsgWaitForMultipleObjects(1,ctypes.byref(h),False,-1,255)==1:
				while ctypes.windll.user32.PeekMessageW(ctypes.byref(msg),None,0,0,1):
					ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
					ctypes.windll.user32.DispatchMessageW(ctypes.byref(msg))
			return winKernel.GetExitCodeProcess(sei.hProcess)
		finally:
			winKernel.closeHandle(sei.hProcess)
Ejemplo n.º 13
0
def load_texture(renderer, name, colorkey=None):
    fullname = os.path.join('data', name)
    fullname = byteify(fullname, 'utf-8')
    surface = sdl2.SDL_LoadBMP(fullname)

    """
    i'm not sure how to extract the pixel format, so instead:
    - force pixel format to a known format without
    - set the colorkey
    -
    """
    #fmt = sdl2.SDL_PixelFormat(sdl2.SDL_PIXELFORMAT_RGBA8888)
    #surface = sdl2.SDL_ConvertSurface(_surface, fmt, 0)
    #sdl2.SDL_FreeSurface(_surface)
    #colorkey = sdl2.SDL_MapRGB(fmt, 255, 0, 0)
    #sdl2.SDL_SetColorKey(surface, 1, colorkey)

    texture = sdl2.SDL_CreateTextureFromSurface(renderer, surface)
    sdl2.SDL_FreeSurface(surface)
    sdl2.SDL_SetTextureBlendMode(texture, sdl2.SDL_BLENDMODE_BLEND)
    flags = c_uint32()
    access = c_int()
    w = c_int()
    h = c_int()
    sdl2.SDL_QueryTexture(texture, byref(flags), byref(access),
                          byref(w), byref(h))
    rect = sdl2.SDL_Rect(0, 0, w, h)

    return texture, rect
Ejemplo n.º 14
0
    def getNodePos(self , i , j , k):
        """Will return the (x,y,z) for the node given by (i,j,k).

        Observe that this method does not consider cells, but the
        nodes in the grid. This means that the valid input range for
        i,j and k are are upper end inclusive. To get the four
        bounding points of the lower layer of the grid:

           p0 = grid.getNodePos(0 , 0 , 0)
           p1 = grid.getNodePos(grid.getNX() , 0 , 0)
           p2 = grid.getNodePos(0 , grid.getNY() , 0)
           p3 = grid.getNodePos(grid.getNX() , grid.getNY() , 0)

        """
        if not 0 <= i <= self.getNX():
            raise IndexError("Invalid I value:%d - valid range: [0,%d]" % (i , self.getNX()))

        if not 0 <= j <= self.getNY():
            raise IndexError("Invalid J value:%d - valid range: [0,%d]" % (j , self.getNY()))

        if not 0 <= k <= self.getNZ():
            raise IndexError("Invalid K value:%d - valid range: [0,%d]" % (k , self.getNZ()))
            
        x = ctypes.c_double()
        y = ctypes.c_double()
        z = ctypes.c_double()
        cfunc.get_corner_xyz( self , i,j,k , ctypes.byref(x) , ctypes.byref(y) , ctypes.byref(z))
        return (x.value , y.value , z.value)
Ejemplo n.º 15
0
    def find_cell( self , x , y , z , start_ijk = None):
        """
        Lookup cell containg true position (x,y,z).

        Will locate the cell in the grid which contains the true
        position (@x,@y,@z), the return value is as a triplet
        (i,j,k). The underlying C implementation is not veeery
        efficient, and can potentially take quite long time. If you
        provide a good intial guess with the parameter @start_ijk (a
        tuple (i,j,k)) things can speed up quite substantially.

        If the location (@x,@y,@z) can not be found in the grid, the
        method will return None.
        """

        if start_ijk:
            start_index = self.__global_index( ijk = start_ijk )
        else:
            start_index = 0
        global_index = cfunc.get_ijk_xyz( self , x , y , z , start_index)
        if global_index >= 0:
            i = ctypes.c_int()
            j = ctypes.c_int()
            k = ctypes.c_int()
            cfunc.get_ijk1( self , global_index , ctypes.byref(i) , ctypes.byref(j) , ctypes.byref(k))        
            return (i.value , j.value , k.value)
        else:
            return None
Ejemplo n.º 16
0
def cube(x, unpack=True):
    """cube a number

    parameters:

      `x`: number to be cubed.
    """
    tdump = TextDumper()
    tdump.dump(x, "x", ['I', '4'])
    in_str = tdump.close()
    len_in = len(in_str)
    out_str = ctypes.POINTER(c_char)()
    len_out = c_size_t(0)
    LIB.cube_py(c_size_t(len_in),
                c_char_p(in_str),
                ctypes.byref(len_out),
                ctypes.byref(out_str))
    if out_str[:1] == 'E':
        xc_error_msg = out_str[1:len_out.value]
        raise RuntimeError(xc_error_msg)
    val = TextParser(out_str[:len_out.value]).parse()
    LIB.cube_py_clear()
    if unpack:
        if val:
            return val.values()[0] if len(val) == 1 else val.values()
        return None
    else:
        return val
Ejemplo n.º 17
0
def move_point(p, x, unpack=True):
    """Adds a number to each of the coordinates of a point.

    parameters:

      `p`: the point to be moved.
      `x`: the amount the point should be moved.
    """
    tdump = TextDumper()
    tdump.dump(p, "p", ['S', 'Point'])
    tdump.dump(x, "x", ['R', '8'])
    in_str = tdump.close()
    len_in = len(in_str)
    out_str = ctypes.POINTER(c_char)()
    len_out = c_size_t(0)
    LIB.move_point_py(c_size_t(len_in),
                      c_char_p(in_str),
                      ctypes.byref(len_out),
                      ctypes.byref(out_str))
    if out_str[:1] == 'E':
        xc_error_msg = out_str[1:len_out.value]
        raise RuntimeError(xc_error_msg)
    val = TextParser(out_str[:len_out.value]).parse()
    LIB.move_point_py_clear()
    if unpack:
        if val:
            return val.values()[0] if len(val) == 1 else val.values()
        return None
    else:
        return val
Ejemplo n.º 18
0
def print_msg(msg, unpack=True):
    """Print a message to the standard error stream.

    parameters:

      `msg`: the message to be printed.
    """
    tdump = TextDumper()
    tdump.dump(msg, "msg", ['W'])
    in_str = tdump.close()
    len_in = len(in_str)
    out_str = ctypes.POINTER(c_char)()
    len_out = c_size_t(0)
    LIB.print_msg_py(c_size_t(len_in),
                     c_char_p(in_str),
                     ctypes.byref(len_out),
                     ctypes.byref(out_str))
    if out_str[:1] == 'E':
        xc_error_msg = out_str[1:len_out.value]
        raise RuntimeError(xc_error_msg)
    val = TextParser(out_str[:len_out.value]).parse()
    LIB.print_msg_py_clear()
    if unpack:
        if val:
            return val.values()[0] if len(val) == 1 else val.values()
        return None
    else:
        return val
Ejemplo n.º 19
0
def scale_array(v, s, unpack=True):
    """scale a one dimentional array.

    parameters:

      `v`: the array to be scaled.
      `s`: the scalar factor.
    """
    tdump = TextDumper()
    tdump.dump(v, "v", ['T', ['R', '8']])
    tdump.dump(s, "s", ['R', '8'])
    in_str = tdump.close()
    len_in = len(in_str)
    out_str = ctypes.POINTER(c_char)()
    len_out = c_size_t(0)
    LIB.scale_array_py(c_size_t(len_in),
                       c_char_p(in_str),
                       ctypes.byref(len_out),
                       ctypes.byref(out_str))
    if out_str[:1] == 'E':
        xc_error_msg = out_str[1:len_out.value]
        raise RuntimeError(xc_error_msg)
    val = TextParser(out_str[:len_out.value]).parse()
    LIB.scale_array_py_clear()
    if unpack:
        if val:
            return val.values()[0] if len(val) == 1 else val.values()
        return None
    else:
        return val
Ejemplo n.º 20
0
def make_line(p1, p2, unpack=True):
    """Given two points, it constructs a line.

    parameters:

      `p1`: the first point.
      `p2`: the second point.
    """
    tdump = TextDumper()
    tdump.dump(p1, "p1", ['S', 'Point'])
    tdump.dump(p2, "p2", ['S', 'Point'])
    in_str = tdump.close()
    len_in = len(in_str)
    out_str = ctypes.POINTER(c_char)()
    len_out = c_size_t(0)
    LIB.make_line_py(c_size_t(len_in),
                     c_char_p(in_str),
                     ctypes.byref(len_out),
                     ctypes.byref(out_str))
    if out_str[:1] == 'E':
        xc_error_msg = out_str[1:len_out.value]
        raise RuntimeError(xc_error_msg)
    val = TextParser(out_str[:len_out.value]).parse()
    LIB.make_line_py_clear()
    if unpack:
        if val:
            return val.values()[0] if len(val) == 1 else val.values()
        return None
    else:
        return val
Ejemplo n.º 21
0
def scale(v, alpha, unpack=True):
    """Scalar multiplication.

    parameters:

      `v`: the vector to multiply. 
      `alpha`: the scalar.
    """
    tdump = TextDumper()
    tdump.dump(v, "v", ['T', ['R', '8']])
    tdump.dump(alpha, "alpha", ['R', '8'])
    in_str = tdump.close()
    len_in = len(in_str)
    out_str = ctypes.POINTER(c_char)()
    len_out = c_size_t(0)
    LIB.scale_py(c_size_t(len_in),
                 c_char_p(in_str),
                 ctypes.byref(len_out),
                 ctypes.byref(out_str))
    if out_str[:1] == 'E':
        xc_error_msg = out_str[1:len_out.value]
        raise RuntimeError(xc_error_msg)
    val = TextParser(out_str[:len_out.value]).parse()
    LIB.scale_py_clear()
    if unpack:
        if val:
            return val.values()[0] if len(val) == 1 else val.values()
        return None
    else:
        return val
Ejemplo n.º 22
0
 def get(self, k):
     v     = ctypes.c_char_p()
     v_len = ctypes.c_size_t()
     rc = self.fget(self.db, k, len(k), ctypes.byref(v), ctypes.byref(v_len))
     if rc == -1:
         raise self.exc(self.format_error())
     return ctypes.string_at(v, v_len.value)
def fittingSeriesFun(X, Y):
	mydll = ctypes.windll.LoadLibrary("MrdCorpMath_Win32_Release.dll")
	pCalcObj = mydll.mrdCorpMath_CalcDiffOrder_create()

	x, y = X, Y

	x = np.log(x)
	y = np.log(y)

	p0 = [1.6,0] # 第一次猜测的函数拟合参数
	plsq = leastsq(residuals, p0, args=(y, x))

	beta = plsq[0][0]

	St = []
	for i in xrange(len(x)):
		s = x[i] - beta*y[i]
		St.append(s)
	mean = np.mean(St)
	std = np.std(St)

	test = []
	for data in St:
		s = (data - mean)/std
		test.append(s)
	test = np.abs(test)
	test.sort()

	#print std
	#x, y = X, Y
	myResult = MyResult_t()
	#x
	szCntSample = len(x)
	pSample = (ctypes.c_double * szCntSample)()
	for i in xrange(szCntSample):
		pSample[i] = x[i]
	mydll.mrdCorpMath_CalcDiffOrder__do_calc(pCalcObj, ctypes.byref(myResult), pSample, szCntSample)
	xDiffRank = myResult.iOrder
	#y
	szCntSample = len(y)
	pSample = (ctypes.c_double * szCntSample)()
	for i in xrange(szCntSample):
		pSample[i] = y[i]
	mydll.mrdCorpMath_CalcDiffOrder__do_calc(pCalcObj, ctypes.byref(myResult), pSample, szCntSample)
	yDiffRank = myResult.iOrder
	#st
	szCntSample = len(St)
	pSample = (ctypes.c_double * szCntSample)()
	for i in xrange(szCntSample):
		pSample[i] = St[i]
	mydll.mrdCorpMath_CalcDiffOrder__do_calc(pCalcObj, ctypes.byref(myResult), pSample, szCntSample)
	stDiffRank = myResult.iOrder

	isCointegration = False
	if stDiffRank < xDiffRank or stDiffRank < yDiffRank:
		isCointegration = True

	mydll.mrdCorpMath_CalcDiffOrder_destroy(pCalcObj)

	return beta, isCointegration, mean, std, test[len(test)*0.90], test[len(test)*0.04], 2*test[-1]-test[len(test)*0.99]
Ejemplo n.º 24
0
    def play(self, buf, len):

        ss = struct_pa_sample_spec()
        ss.rate = 48000
        ss.channels = 1
        ss.format = PA_SAMPLE_S16LE

        error = ctypes.c_int(0)
    
        s = pa.pa_simple_new(
            None,                # Default server.
            self.name,           # Application's name.
            PA_STREAM_PLAYBACK,  # Stream for playback.
            None,                # Default device.
            'playback',          # Stream's description.
            ctypes.byref(ss),    # Sample format.
            None,                # Default channel map.
            None,                # Default buffering attributes.
            ctypes.byref(error)  # Ignore error code.
        )
        if not s:
            raise Exception('Could not create pulse audio stream: {0}!'.format(pa.strerror(ctypes.byref(error))))

        if pa.pa_simple_write(s, buf, len, error):
            raise Exception('Could not play file!')
        
        # Waiting for all sent data to finish playing.
        if pa.pa_simple_drain(s, error):
            raise Exception('Could not simple drain!')
        
        # Freeing resources and closing connection.
        pa.pa_simple_free(s)
Ejemplo n.º 25
0
    def start(self):
        ss = struct_pa_sample_spec()
        ss.rate = 48000
        ss.channels = 1
        ss.format = PA_SAMPLE_S16LE

        error = ctypes.c_int(0)

        ba = struct_pa_buffer_attr()
        ba.maxlength = -1
        ba.tlength   = -1 
        ba.prebuf    = -1
        ba.minreq    = -1
        ba.fragsize  = 48000/10 * 2 # 1/10th of a second

        self.s = pa.pa_simple_new(
            None,                # Default server.
            self.name,           # Application's name.
            PA_STREAM_RECORD,    # Stream for recording.
            None,                # Default device.
            'record',            # Stream's description.
            ctypes.byref(ss),    # Sample format.
            None,                # Default channel map.
            ctypes.byref(ba),    # buffering attributes.
            ctypes.byref(error)  # Ignore error code.
        )
        if not self.s:
            raise Exception('Could not create pulse audio stream: {0}!'.format(
                pa.strerror(ctypes.byref(error))))
Ejemplo n.º 26
0
	def isfile_cached(self):
		# optimize for nt.stat calls, assuming there are many files for few folders
		try:
			cache = self.__class__.cache_isfile_cache
		except AttributeError:
			cache = self.__class__.cache_isfile_cache = {}

		try:
			c1 = cache[id(self.parent)]
		except KeyError:
			c1 = cache[id(self.parent)] = []

			curpath = self.parent.abspath()
			findData = ctypes.wintypes.WIN32_FIND_DATAW()
			find     = FindFirstFile(TP % curpath, ctypes.byref(findData))

			if find == INVALID_HANDLE_VALUE:
				Logs.error("invalid win32 handle isfile_cached %r", self.abspath())
				return os.path.isfile(self.abspath())

			try:
				while True:
					if findData.cFileName not in UPPER_FOLDERS:
						thatsadir = findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
						if not thatsadir:
							c1.append(str(findData.cFileName))
					if not FindNextFile(find, ctypes.byref(findData)):
						break
			except Exception as e:
				Logs.error('exception while listing a folder %r %r', self.abspath(), e)
				return os.path.isfile(self.abspath())
			finally:
				FindClose(find)
		return self.name in c1
Ejemplo n.º 27
0
	def cached_hash_file(self):
		try:
			cache = self.ctx.cache_listdir_cache_hash_file
		except AttributeError:
			cache = self.ctx.cache_listdir_cache_hash_file = {}

		if id(self.parent) in cache:
			try:
				t = cache[id(self.parent)][self.name]
			except KeyError:
				raise IOError('Not a file')
		else:
			# an opportunity to list the files and the timestamps at once
			findData = ctypes.wintypes.WIN32_FIND_DATAW()
			find     = FindFirstFile(TP % self.parent.abspath(), ctypes.byref(findData))

			if find == INVALID_HANDLE_VALUE:
				cache[id(self.parent)] = {}
				raise IOError('Not a file')

			cache[id(self.parent)] = lst_files = {}
			try:
				while True:
					if findData.cFileName not in UPPER_FOLDERS:
						thatsadir = findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
						if not thatsadir:
							ts = findData.ftLastWriteTime
							d = (ts.dwLowDateTime << 32) | ts.dwHighDateTime
							lst_files[str(findData.cFileName)] = d
					if not FindNextFile(find, ctypes.byref(findData)):
						break
			except Exception:
				cache[id(self.parent)] = {}
				raise IOError('Not a file')
			finally:
				FindClose(find)
			t = lst_files[self.name]

		fname = self.abspath()
		if fname in Build.hashes_md5_tstamp:
			if Build.hashes_md5_tstamp[fname][0] == t:
				return Build.hashes_md5_tstamp[fname][1]

		try:
			fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
		except OSError:
			raise IOError('Cannot read from %r' % fname)
		f = os.fdopen(fd, 'rb')
		m = Utils.md5()
		rb = 1
		try:
			while rb:
				rb = f.read(200000)
				m.update(rb)
		finally:
			f.close()

		# ensure that the cache is overwritten
		Build.hashes_md5_tstamp[fname] = (t, m.digest())
		return m.digest()
Ejemplo n.º 28
0
def rush(value=True):    
    """Raise the priority of the current thread/process 
    Win32 and OS X only so far - on linux use os.nice(niceIncrement)
    
    Set with rush(True) or rush(False)
    
    Beware and don't take priority until after debugging your code
    and ensuring you have a way out (e.g. an escape sequence of
    keys within the display loop). Otherwise you could end up locked
    out and having to reboot!
    """
    if importCtypesFailed: return False
    
    if value:
        bus = getBusFreq()
        extendedPolicy=_timeConstraintThreadPolicy()
        extendedPolicy.period=bus/160 #number of cycles in hz (make higher than frame rate)
        extendedPolicy.computation=bus/320#half of that period
        extendedPolicy.constrain= bus/640#max period that they should be carried out in
        extendedPolicy.preemptible=1
        extendedPolicy=getThreadPolicy(getDefault=True, flavour=THREAD_TIME_CONSTRAINT_POLICY)
        err=cocoa.thread_policy_set(cocoa.mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY, 
            ctypes.byref(extendedPolicy), #send the address of the struct
            THREAD_TIME_CONSTRAINT_POLICY_COUNT)
        if err!=KERN_SUCCESS:
            logging.error('Failed to set darwin thread policy, with thread_policy_set')
        else:
            logging.info('Successfully set darwin thread to realtime')
    else:
        #revert to default policy
        extendedPolicy=getThreadPolicy(getDefault=True, flavour=THREAD_STANDARD_POLICY)
        err=cocoa.thread_policy_set(cocoa.mach_thread_self(), THREAD_STANDARD_POLICY, 
            ctypes.byref(extendedPolicy), #send the address of the struct
            THREAD_STANDARD_POLICY_COUNT)
    return True
Ejemplo n.º 29
0
    def _create_bitmap(self, width, height):
        self._data = (ctypes.c_byte * (4 * width * height))()
        self._bitmap = ctypes.c_void_p()
        self._format = PixelFormat32bppARGB 
        gdiplus.GdipCreateBitmapFromScan0(width, height, width * 4,
            self._format, self._data, ctypes.byref(self._bitmap))

        self._graphics = ctypes.c_void_p()
        gdiplus.GdipGetImageGraphicsContext(self._bitmap,
            ctypes.byref(self._graphics))
        gdiplus.GdipSetPageUnit(self._graphics, UnitPixel)

        self._dc = user32.GetDC(0)
        gdi32.SelectObject(self._dc, self.font.hfont)

        gdiplus.GdipSetTextRenderingHint(self._graphics,
            TextRenderingHintAntiAliasGridFit)


        self._brush = ctypes.c_void_p()
        gdiplus.GdipCreateSolidFill(0xffffffff, ctypes.byref(self._brush))

        
        self._matrix = ctypes.c_void_p()
        gdiplus.GdipCreateMatrix(ctypes.byref(self._matrix))

        self._flags = (DriverStringOptionsCmapLookup |
                       DriverStringOptionsRealizedAdvance)

        self._rect = Rect(0, 0, width, height)

        self._bitmap_height = height
Ejemplo n.º 30
0
    def step(self, timeout=None):
        self.dispatch_posted_events()

        msg = types.MSG()
        if timeout is None:
            timeout = constants.INFINITE
        else:
            timeout = int(timeout * 1000)  # milliseconds

        result = user32.MsgWaitForMultipleObjects(
            self._wait_objects_n,
            self._wait_objects_array,
            False,
            timeout,
            constants.QS_ALLINPUT)
        result -= constants.WAIT_OBJECT_0

        if result == self._wait_objects_n:
            while user32.PeekMessageW(ctypes.byref(msg),
                                      0, 0, 0, constants.PM_REMOVE):
                user32.TranslateMessage(ctypes.byref(msg))
                user32.DispatchMessageW(ctypes.byref(msg))
        elif 0 <= result < self._wait_objects_n:
            object_, func = self._wait_objects[result]
            func()

        # Return True if timeout was interrupted.
        return result <= self._wait_objects_n
Ejemplo n.º 31
0
def _load_client_cert_chain(keychain, *paths):
    """
    Load certificates and maybe keys from a number of files. Has the end goal
    of returning a CFArray containing one SecIdentityRef, and then zero or more
    SecCertificateRef objects, suitable for use as a client certificate trust
    chain.
    """
    # Ok, the strategy.
    #
    # This relies on knowing that macOS will not give you a SecIdentityRef
    # unless you have imported a key into a keychain. This is a somewhat
    # artificial limitation of macOS (for example, it doesn't necessarily
    # affect iOS), but there is nothing inside Security.framework that lets you
    # get a SecIdentityRef without having a key in a keychain.
    #
    # So the policy here is we take all the files and iterate them in order.
    # Each one will use SecItemImport to have one or more objects loaded from
    # it. We will also point at a keychain that macOS can use to work with the
    # private key.
    #
    # Once we have all the objects, we'll check what we actually have. If we
    # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,
    # we'll take the first certificate (which we assume to be our leaf) and
    # ask the keychain to give us a SecIdentityRef with that cert's associated
    # key.
    #
    # We'll then return a CFArray containing the trust chain: one
    # SecIdentityRef and then zero-or-more SecCertificateRef objects. The
    # responsibility for freeing this CFArray will be with the caller. This
    # CFArray must remain alive for the entire connection, so in practice it
    # will be stored with a single SSLSocket, along with the reference to the
    # keychain.
    certificates = []
    identities = []

    # Filter out bad paths.
    paths = (path for path in paths if path)

    try:
        for file_path in paths:
            new_identities, new_certs = _load_items_from_file(
                keychain, file_path)
            identities.extend(new_identities)
            certificates.extend(new_certs)

        # Ok, we have everything. The question is: do we have an identity? If
        # not, we want to grab one from the first cert we have.
        if not identities:
            new_identity = Security.SecIdentityRef()
            status = Security.SecIdentityCreateWithCertificate(
                keychain, certificates[0], ctypes.byref(new_identity))
            _assert_no_error(status)
            identities.append(new_identity)

            # We now want to release the original certificate, as we no longer
            # need it.
            CoreFoundation.CFRelease(certificates.pop(0))

        # We now need to build a new CFArray that holds the trust chain.
        trust_chain = CoreFoundation.CFArrayCreateMutable(
            CoreFoundation.kCFAllocatorDefault,
            0,
            ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
        )
        for item in itertools.chain(identities, certificates):
            # ArrayAppendValue does a CFRetain on the item. That's fine,
            # because the finally block will release our other refs to them.
            CoreFoundation.CFArrayAppendValue(trust_chain, item)

        return trust_chain
    finally:
        for obj in itertools.chain(identities, certificates):
            CoreFoundation.CFRelease(obj)
Ejemplo n.º 32
0
 def envelope(self):
     "Returns the envelope for this Geometry."
     # TODO: Fix Envelope() for Point geometries.
     return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope())))
Ejemplo n.º 33
0
 def get_pubkey(self):
     size = _ssl.i2o_ECPublicKey(self.k, 0)
     mb = ctypes.create_string_buffer(size)
     _ssl.i2o_ECPublicKey(self.k, ctypes.byref(ctypes.pointer(mb)))
     return mb.raw
Ejemplo n.º 34
0
 def get_privkey(self):
     size = _ssl.i2d_ECPrivateKey(self.k, 0)
     mb_pri = ctypes.create_string_buffer(size)
     _ssl.i2d_ECPrivateKey(self.k, ctypes.byref(ctypes.pointer(mb_pri)))
     return mb_pri.raw
Ejemplo n.º 35
0
 def set_pubkey(self, key):
     self.mb = ctypes.create_string_buffer(key)
     return _ssl.o2i_ECPublicKey(ctypes.byref(self.k), ctypes.byref(ctypes.pointer(self.mb)), len(key))
Ejemplo n.º 36
0
 def set_privkey(self, key):
     self.mb = ctypes.create_string_buffer(key)
     return _ssl.d2i_ECPrivateKey(ctypes.byref(self.k), ctypes.byref(ctypes.pointer(self.mb)), len(key))
Ejemplo n.º 37
0
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')
Ejemplo n.º 38
0
def checkSignature(file, bundle=None):
    SECURITY_FRAMEWORK = '/System/Library/Frameworks/Security.framework/Versions/Current/Security'
    kSecCSDefaultFlags = 0x0
    kSecCSDoNotValidateResources = 0x4
    kSecCSCheckAllArchitectures = 0x1
    kSecCSCheckNestedCode = 0x8
    kSecCSStrictValidate = 0x16
    kSecCSStrictValidate_kSecCSCheckAllArchitectures = 0x17
    kSecCSStrictValidate_kSecCSCheckAllArchitectures_kSecCSCheckNestedCode = 0x1f
    errSecSuccess = 0x0
    SecCSSignatureOK = errSecSuccess
    errSecCSUnsigned = -67062
    kPOSIXErrorEACCES = 100013
    kSecCSSigningInformation = 0x2
    kSecCodeInfoCertificates = 'certificates'

    #return dictionary
    signingInfo = {}
    sigCheckFlags = kSecCSStrictValidate_kSecCSCheckAllArchitectures_kSecCSCheckNestedCode
    securityFramework = ctypes.cdll.LoadLibrary(SECURITY_FRAMEWORK)
    objcRuntime = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
    objcRuntime.objc_getClass.restype = ctypes.c_void_p
    objcRuntime.sel_registerName.restype = ctypes.c_void_p
    status = not errSecSuccess
    signedStatus = None
    isApple = False
    authorities = []

    file = Foundation.NSString.stringWithString_(file)
    file = file.stringByAddingPercentEscapesUsingEncoding_(
        Foundation.NSUTF8StringEncoding).encode('utf-8')
    path = Foundation.NSURL.URLWithString_(
        Foundation.NSString.stringWithUTF8String_(file))
    staticCode = ctypes.c_void_p(0)
    result = securityFramework.SecStaticCodeCreateWithPath(
        ctypes.c_void_p(objc.pyobjc_id(path)), kSecCSDefaultFlags,
        ctypes.byref(staticCode))
    signedStatus = securityFramework.SecStaticCodeCheckValidityWithErrors(
        staticCode, sigCheckFlags, None, None)
    if errSecSuccess == signedStatus:
        requirementReference = "anchor apple"
        NSString = objcRuntime.objc_getClass('NSString')
        objcRuntime.objc_msgSend.restype = ctypes.c_void_p
        objcRuntime.objc_msgSend.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p
        ]
        requirementsString = objcRuntime.objc_msgSend(
            NSString, objcRuntime.sel_registerName('stringWithUTF8String:'),
            requirementReference)
        requirement = ctypes.c_void_p(0)
        if errSecSuccess == securityFramework.SecRequirementCreateWithString(
                ctypes.c_void_p(requirementsString), kSecCSDefaultFlags,
                ctypes.byref(requirement)):
            if errSecSuccess == securityFramework.SecStaticCodeCheckValidity(
                    staticCode, sigCheckFlags, requirement):
                isApple = True

        information = ctypes.c_void_p(0)
        result = securityFramework.SecCodeCopySigningInformation(
            staticCode, kSecCSSigningInformation, ctypes.byref(information))
        objcRuntime.objc_msgSend.restype = ctypes.c_void_p
        objcRuntime.objc_msgSend.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p
        ]
        key = objcRuntime.objc_msgSend(
            NSString, objcRuntime.sel_registerName('stringWithUTF8String:'),
            kSecCodeInfoCertificates)
        objcRuntime.objc_msgSend.restype = ctypes.c_void_p
        objcRuntime.objc_msgSend.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p
        ]
        certChain = objcRuntime.objc_msgSend(
            information, objcRuntime.sel_registerName('objectForKey:'), key)
        objcRuntime.objc_msgSend.restype = ctypes.c_uint
        objcRuntime.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
        count = objcRuntime.objc_msgSend(certChain,
                                         objcRuntime.sel_registerName('count'))
        certName = ctypes.c_char_p(0)
        for index in range(count):
            objcRuntime.objc_msgSend.restype = ctypes.c_void_p
            objcRuntime.objc_msgSend.argtypes = [
                ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint
            ]
            cert = objcRuntime.objc_msgSend(
                certChain, objcRuntime.sel_registerName('objectAtIndex:'),
                index)
            result = securityFramework.SecCertificateCopyCommonName(
                ctypes.c_void_p(cert), ctypes.byref(certName))
            if errSecSuccess != result:
                continue
            objcRuntime.objc_msgSend.restype = ctypes.c_char_p
            objcRuntime.objc_msgSend.argtypes = [
                ctypes.c_void_p, ctypes.c_void_p
            ]
            authorities.append(
                objcRuntime.objc_msgSend(
                    certName, objcRuntime.sel_registerName('UTF8String')))

    status = errSecSuccess
    if signedStatus == 0:
        signingInfo['status'] = "signed"
    else:
        signingInfo['status'] = "unsigned"
    signingInfo['apple_binary'] = isApple
    signingInfo['Authority'] = authorities
    return (signingInfo)
Ejemplo n.º 39
0
def _get_total_physmem():
    retval = None

    try:
        if IS_WIN:
            import ctypes

            kernel32 = ctypes.windll.kernel32
            c_ulong = ctypes.c_ulong
            class MEMORYSTATUS(ctypes.Structure):
                _fields_ = [
                    ('dwLength', c_ulong),
                    ('dwMemoryLoad', c_ulong),
                    ('dwTotalPhys', c_ulong),
                    ('dwAvailPhys', c_ulong),
                    ('dwTotalPageFile', c_ulong),
                    ('dwAvailPageFile', c_ulong),
                    ('dwTotalVirtual', c_ulong),
                    ('dwAvailVirtual', c_ulong)
                ]

            memory_status = MEMORYSTATUS()
            memory_status.dwLength = ctypes.sizeof(MEMORYSTATUS)
            kernel32.GlobalMemoryStatus(ctypes.byref(memory_status))

            retval = memory_status.dwTotalPhys
        else:
            retval = 1024 * int(re.search(r"(?i)MemTotal:\s+(\d+)\skB", open("/proc/meminfo").read()).group(1))
    except:
        pass

    if not retval:
        try:
            import psutil
            retval = psutil.virtual_memory().total
        except:
            pass

    if not retval:
        try:
            retval = int(re.search(r"real mem(ory)?\s*=\s*(\d+) ", open("/var/run/dmesg.boot").read()).group(2))
        except:
            pass

    if not retval:
        try:
            retval = int(re.search(r"hw\.(physmem|memsize):\s*(\d+)", subprocess.check_output("sysctl hw", shell=True, stderr=subprocess.STDOUT)).group(2))
        except:
            pass

    if not retval:
        try:
            retval = 1024 * int(re.search(r"\s+(\d+) K total memory", subprocess.check_output("vmstat -s", shell=True, stderr=subprocess.STDOUT)).group(1))
        except:
            pass

    if not retval:
        try:
            retval = int(re.search(r"Mem:\s+(\d+)", subprocess.check_output("free -b", shell=True, stderr=subprocess.STDOUT)).group(1))
        except:
            pass

    if not retval:
        try:
            retval = 1024 * int(re.search(r"KiB Mem:\s*\x1b[^\s]+\s*(\d+)", subprocess.check_output("top -n 1", shell=True, stderr=subprocess.STDOUT)).group(1))
        except:
            pass

    return retval
Ejemplo n.º 40
0
def _get_conout_mode():
    with open("CONOUT$", "w") as conout:
        mode = DWORD()
        conout_handle = get_osfhandle(conout.fileno())
        kernel32.GetConsoleMode(conout_handle, byref(mode))
        return mode.value
Ejemplo n.º 41
0
 def enum_cb(hwnd, results):
     if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) != '':
         dwmapi.DwmGetWindowAttribute(HWND(hwnd), DWORD(DWMWA_CLOAKED), ctypes.byref(isCloacked),
                                      ctypes.sizeof(isCloacked))
         if (isCloacked.value == 0):
             results.append((hwnd, win32gui.GetWindowText(hwnd)))
 def __enter__(self):
     self.old_value = ctypes.c_long()
     self.success = self._disable(ctypes.byref(self.old_value))
Ejemplo n.º 43
0
def main():
    os.system('nvidia-smi')

    libnames = ('libcuda.so', 'libcuda.dylib', 'cuda.dll')
    for libname in libnames:
        try:
            cuda = ctypes.CDLL(libname)
        except OSError:
            continue
        else:
            break
    else:
        raise OSError("could not load any of: " + ' '.join(libnames))

    nGpus = ctypes.c_int()
    name = b' ' * 100
    cc_major = ctypes.c_int()
    cc_minor = ctypes.c_int()
    cores = ctypes.c_int()
    threads_per_core = ctypes.c_int()
    clockrate = ctypes.c_int()
    bandwidth = ctypes.c_int()
    freeMem = ctypes.c_size_t()
    totalMem = ctypes.c_size_t()

    result = ctypes.c_int()
    device = ctypes.c_int()
    context = ctypes.c_void_p()
    error_str = ctypes.c_char_p()

    result = cuda.cuInit(0)

    if result != CUDA_SUCCESS:
        cuda.cuGetErrorString(result, ctypes.byref(error_str))
        print("cuInit failed with error code %d: %s" %
              (result, error_str.value.decode()))
        return 1
    result = cuda.cuDeviceGetCount(ctypes.byref(nGpus))

    if result != CUDA_SUCCESS:
        cuda.cuGetErrorString(result, ctypes.byref(error_str))
        print("cuDeviceGetCount failed with error code %d: %s" %
              (result, error_str.value.decode()))
        return 1
    print(" %d carte(s) détectée(s)." % nGpus.value)

    for i in range(nGpus.value):
        result = cuda.cuDeviceGet(ctypes.byref(device), i)

        if result != CUDA_SUCCESS:
            cuda.cuGetErrorString(result, ctypes.byref(error_str))
            print("cuDeviceGet failed with error code %d: %s" %
                  (result, error_str.value.decode()))
            return 1
        print("\n Carte n° : %d" % i)

        if cuda.cuDeviceGetName(ctypes.c_char_p(name), len(name),
                                device) == CUDA_SUCCESS:
            print("  Nom : %s" % (name.split(b'\0', 1)[0].decode()))

        if cuda.cuDeviceComputeCapability(ctypes.byref(cc_major),
                                          ctypes.byref(cc_minor),
                                          device) == CUDA_SUCCESS:
            print("  Capacité de calcul : %d.%d" %
                  (cc_major.value, cc_minor.value))

        if cuda.cuDeviceGetAttribute(ctypes.byref(cores),
                                     CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT,
                                     device) == CUDA_SUCCESS:
            print("  Multiprocesseurs : %d" % cores.value)
            print("  Cores CUDA : %d" %
                  (cores.value *
                   ConvertSMVer2Cores(cc_major.value, cc_minor.value)))

            if cuda.cuDeviceGetAttribute(
                    ctypes.byref(threads_per_core),
                    CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
                    device) == CUDA_SUCCESS:
                print("  Unités de calcul : %d" % (threads_per_core.value))

        if cuda.cuDeviceGetAttribute(ctypes.byref(clockrate),
                                     CU_DEVICE_ATTRIBUTE_CLOCK_RATE,
                                     device) == CUDA_SUCCESS:
            print("  Fréquence du GPU : %g MHz" % (clockrate.value / 1000.))

        if cuda.cuDeviceGetAttribute(
                ctypes.byref(bandwidth),
                CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH,
                device) == CUDA_SUCCESS:
            print("  Bande passante : %g GB/s " % ((bandwidth.value)))
        result = cuda.cuCtxCreate(ctypes.byref(context), 0, device)

        if result != CUDA_SUCCESS:
            cuda.cuGetErrorString(result, ctypes.byref(error_str))
            print("cuCtxCreate failed with error code %d: %s" %
                  (result, error_str.value.decode()))
        else:
            result = cuda.cuMemGetInfo(ctypes.byref(freeMem),
                                       ctypes.byref(totalMem))
            if result == CUDA_SUCCESS:
                print("  Mémoire Totale : %ld MiB" %
                      (totalMem.value / 1024**2))
                print("  Mémoire libre : %ld MiB" % (freeMem.value / 1024**2))
            else:
                cuda.cuGetErrorString(result, ctypes.byref(error_str))
                print("cuMemGetInfo failed with error code %d: %s" %
                      (result, error_str.value.decode()))
            cuda.cuCtxDetach(context)
    return 0
Ejemplo n.º 44
0
    def get_associated_descriptors(self, dtype):
        """
        get_associated_descriptors(int or str) -> tuple of DMDescriptor

        raises AttributeError if dtype not in self.associated_dtypes
        """
        # First be sure we have this dtype.
        if isinstance(dtype, str):
            try:
                dtype = const.DESC_TYPE_MAP[dtype]
            except KeyError:
                raise ValueError("dtype: '%s' not in %s" %
                                 (dtype,
                                  set([
                                      const.DESC_TYPE_MAP[key]
                                      for key in const.DESC_TYPE_MAP
                                  ])))
        else:
            if not isinstance(dtype, numbers.Integral):
                raise TypeError("dtype: '%s' object is not int or str" % \
                                (dtype.__class__.__name__))
            try:
                if dtype not in set(const.DESC_TYPE):
                    raise ValueError("dtype: %d not in %s" %
                                     (dtype, set(const.DESC_TYPE)))
            except TypeError:
                raise

        if dtype not in self.associated_dtypes:
            raise AttributeError("dtype: %d ('%s') not valid for %d ('%s')" % \
                                 (dtype, const.DESC_TYPE_MAP[dtype],
                                  self.dtype, const.DESC_TYPE_MAP[self.dtype]))

        # Finally... all is well so lets look it up.
        err = C.c_int()

        # By setting restype we get the right class
        cfunc.dm_get_associated_descriptors.restype = \
            C.POINTER(_RESTYPE[dtype])
        descp = cfunc.dm_get_associated_descriptors(self, dtype, C.byref(err))
        cfunc.dm_get_associated_descriptors.restype = \
            _dm_get_associated_descriptors_restype

        if err.value != 0:
            if err.value == errno.ENOMEM:
                raise MemoryError("insufficient memory")
            else:
                raise OSError(err.value, "dm_get_associated_descriptors: " \
                              "%s" % (os.strerror(err.value)))

        rlist = list()
        idx = 0
        while True:
            val = descp[idx]
            # NULL
            if val.value == 0:
                break
            # GC Alert
            val.ref = descp
            rlist.append(val)
            idx += 1
        if idx > 0:
            # Got descriptors so we have to track them.
            CTypesStructureRef(descp, cfunc.dm_free_descriptors)
        else:
            cfunc.dm_free_descriptors(descp)

        return tuple(rlist)
 def SetConsoleColor(color):
     '''Change the text color on console window'''
     if not Win32API.DefaultColor:
         if not Win32API.ConsoleOutputHandle:
             Win32API.ConsoleOutputHandle = ctypes.windll.kernel32.GetStdHandle(Win32API.StdOutputHandle)
         bufferInfo = ConsoleScreenBufferInfo()
         ctypes.windll.kernel32.GetConsoleScreenBufferInfo(Win32API.ConsoleOutputHandle, ctypes.byref(bufferInfo))
         Win32API.DefaultColor = int(bufferInfo.wAttributes & 0xFF)
     if IsPy3:
         sys.stdout.flush() # need flush stdout in python 3
     ctypes.windll.kernel32.SetConsoleTextAttribute(Win32API.ConsoleOutputHandle, color)
Ejemplo n.º 46
0
def main(argv=sys.argv):

    global program_name
    program_name = os.path.basename(argv[0])

    try:
        opts, args = getopt.getopt(argv[1:], "i:Ips:aB:")
    except getopt.GetoptError:
        usage()

    device = None
    dorfmon = False
    dopromisc = False
    snaplen = MAXIMUM_SNAPLEN
    bufsize = 0
    useactivate = False
    for opt, optarg in opts:
        if opt == '-i':
            device = optarg.encode("utf-8")
        elif opt == '-I':
            dorfmon = True
            useactivate = True  # required for rfmon
        elif opt == '-p':
            dopromisc = True
        elif opt == '-s':
            try:
                long_snaplen = int(optarg)
            except:
                error("invalid snaplen {}", optarg)
            if not (0 <= long_snaplen <= MAXIMUM_SNAPLEN):
                error("invalid snaplen {}", optarg)
            elif long_snaplen == 0:  # <AK> fix, was: snaplen == 0:
                snaplen = MAXIMUM_SNAPLEN
            else:
                snaplen = long_snaplen
        elif opt == '-B':
            try:
                bufsize = int(optarg) * 1024
            except:
                error("invalid packet buffer size {}", optarg)
            if bufsize <= 0:
                error("invalid packet buffer size {}", optarg)
            useactivate = True  # required for bufsize
        elif opt == '-a':
            useactivate = True
        else:
            usage()

    status = 0

    ebuf = ct.create_string_buffer(pcap.PCAP_ERRBUF_SIZE)

    if device is None:
        devlist = ct.POINTER(pcap.pcap_if_t)()
        if pcap.findalldevs(ct.byref(devlist), ebuf) == -1:
            error("{!s}", ebuf.value.decode("utf-8", "ignore"))
        if not devlist:
            error("no interfaces available for capture")
        device = devlist[0].name
        pcap.freealldevs(devlist)

    if useactivate:

        pd = pcap.create(device, ebuf)
        if not pd:
            error("{!s}: pcap.create failed: {!s}",
                  device.decode("utf-8"),
                  ebuf.value.decode("utf-8", "ignore"))

        status = pcap.set_snaplen(pd, snaplen)
        if status != 0:
            error("{!s}: pcap.set_snaplen failed: {!s}",
                  device.decode("utf-8"),
                  statustostr(status).decode("utf-8", "ignore"))

        if dopromisc:
            status = pcap.set_promisc(pd, 1)
            if status != 0:
                error("{!s}: pcap.set_promisc failed: {!s}",
                      device.decode("utf-8"),
                      statustostr(status).decode("utf-8", "ignore"))

        if dorfmon:
            try:
                status = pcap.set_rfmon(pd, 1)
            except AttributeError:
                error("pcap.set_rfmon is not available on this platform")
            if status != 0:
                error("{!s}: pcap.set_rfmon failed: {!s}",
                      device.decode("utf-8"),
                      statustostr(status).decode("utf-8", "ignore"))

        status = pcap.set_timeout(pd, 1000)
        if status != 0:
            error("{!s}: pcap.set_timeout failed: {!s}",
                  device.decode("utf-8"),
                  statustostr(status).decode("utf-8", "ignore"))

        if bufsize != 0:
            status = pcap.set_buffer_size(pd, bufsize)
            if status != 0:
                error("{!s}: pcap.set_buffer_size failed: {!s}",
                      device.decode("utf-8"),
                      statustostr(status).decode("utf-8", "ignore"))

        status = pcap.activate(pd)
        if status < 0:
            # pcap.activate() failed.
            error("{!s}: {!s}\n({!s})",
                  device.decode("utf-8"),
                  statustostr(status).decode("utf-8", "ignore"),
                  pcap.geterr(pd).decode("utf-8", "ignore"))
        elif status > 0:
            # pcap.activate() succeeded, but it's warning us
            # of a problem it had.
            warning("{!s}: {!s}\n({!s})",
                    device.decode("utf-8"),
                    statustostr(status).decode("utf-8", "ignore"),
                    pcap.geterr(pd).decode("utf-8", "ignore"))
        else:
            print("{!s} opened successfully".format(device.decode("utf-8")))

        pcap.close(pd)

    else:

        ebuf.value = b""
        pd = pcap.open_live(device, 65535, 0, 1000, ebuf)
        if not pd:
            error("{!s}", ebuf.value.decode("utf-8", "ignore"))
        elif ebuf.value:
            warning("{!s}", ebuf.value.decode("utf-8", "ignore"))
        else:
            print("{!s} opened successfully".format(device.decode("utf-8")))

        pcap.close(pd)

    return 1 if status < 0 else 0
Ejemplo n.º 47
0
 def channel_group(self):
     ptr = c_void_p()
     self._call("GetChannelGroup", byref(ptr))
     return ChannelGroup(ptr)
Ejemplo n.º 48
0
 def ref(value, offset=0):
     if offset == 0:
         return ctypes.byref(value)
     return ctypes.cast(ctypes.addressof(value) + offset, ctypes.POINTER(ctypes.c_byte))
Ejemplo n.º 49
0
 def get_parameter_value_by_index(self, index):
     val = c_float()
     actual = c_float()
     self._call("GetParameterValueByIndex", index, byref(val), byref(actual))
     return (val.value, actual.value)
Ejemplo n.º 50
0
    print("No device available.")
    exit(0)
print("Using device #%1d" % dev[0])
print("\nInitializing the device...")

# Histo mode with internal clock
tryfunc(mhlib.MH_Initialize(ct.c_int(dev[0]), ct.c_int(MODE_HIST), ct.c_int(0)),
        "Initialize")

# Only for information
tryfunc(mhlib.MH_GetHardwareInfo(dev[0], hwModel, hwPartno, hwVersion),
        "GetHardwareInfo")
print("Found Model %s Part no %s Version %s" % (hwModel.value.decode("utf-8"),
      hwPartno.value.decode("utf-8"), hwVersion.value.decode("utf-8")))

tryfunc(mhlib.MH_GetNumOfInputChannels(ct.c_int(dev[0]), byref(numChannels)),
        "GetNumOfInputChannels")
print("Device has %i input channels." % numChannels.value)

tryfunc(mhlib.MH_SetSyncDiv(ct.c_int(dev[0]), ct.c_int(syncDivider)), "SetSyncDiv")

tryfunc(
    mhlib.MH_SetSyncEdgeTrg(ct.c_int(dev[0]), ct.c_int(syncEdgeTrg),
                            ct.c_int(1)),
    "SetSyncEdgeTrg"
)

tryfunc(mhlib.MH_SetSyncChannelOffset(ct.c_int(dev[0]), ct.c_int(syncChannelOffset)),
        "SetSyncChannelOffset")

# we use the same input settings for all channels, you can change this
Ejemplo n.º 51
0
 def get_parameter_by_index(self, index):
     ptr = c_void_p()
     self._call("GetParameterByIndex", index, byref(ptr))
     return ParameterInstance(ptr)
Ejemplo n.º 52
0
 def get_volume(self, volume):
     volume = c_float()
     finalVolume = c_float()
     self._call("GetVolume", byref(volume), byref(finalVolume))
     return volume
Ejemplo n.º 53
0
 def playback_state(self):
     state = c_int()
     self._call("GetPlaybackState", byref(state))
     return PLAYBACK_STATE(state.value)
Ejemplo n.º 54
0
 def get_parameter_value(self, name):
     val = c_float()
     actual = c_float()
     self._call("GetParameterValue", prepare_str(name), byref(val), byref(actual))
     return (val.value, actual.value)
Ejemplo n.º 55
0
def _run_argvemulator(timeout = 60):

    # Configure ctypes
    carbon = _ctypes_setup()

    # Is the emulator running?
    running = [True]

    # Configure AppleEvent handlers
    ae_callback = carbon.AEInstallEventHandler.argtypes[2]

    kAEInternetSuite,   = struct.unpack('>i', B('GURL'))
    kAEISGetURL,        = struct.unpack('>i', B('GURL'))
    kCoreEventClass,    = struct.unpack('>i', B('aevt'))
    kAEOpenApplication, = struct.unpack('>i', B('oapp'))
    kAEOpenDocuments,   = struct.unpack('>i', B('odoc'))
    keyDirectObject,    = struct.unpack('>i', B('----'))
    typeAEList,         = struct.unpack('>i', B('list'))
    typeChar,           = struct.unpack('>i', B('TEXT'))
    typeFSRef,          = struct.unpack('>i', B('fsrf'))
    FALSE               = B('\0')
    TRUE               = B('\1')

    kEventClassAppleEvent, = struct.unpack('>i', B('eppc'))
    kEventAppleEvent = 1


    @ae_callback
    def open_app_handler(message, reply, refcon):
        running[0] = False
	return 0

    carbon.AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
            open_app_handler, 0, FALSE)

    @ae_callback
    def open_file_handler(message, reply, refcon):
        listdesc = AEDesc()
        sts = carbon.AEGetParamDesc(message, keyDirectObject, typeAEList,
                ctypes.byref(listdesc))
        if sts != 0:
            print >>sys.stderr, "argvemulator warning: cannot unpack open document event"
            running[0] = False
            return

        item_count = ctypes.c_long()
        sts = carbon.AECountItems(ctypes.byref(listdesc), ctypes.byref(item_count))
        if sts != 0:
            print >>sys.stderr, "argvemulator warning: cannot unpack open document event"
            running[0] = False
            return

        desc = AEDesc()
        for i in range(item_count.value):
            sts = carbon.AEGetNthDesc(ctypes.byref(listdesc), i+1, typeFSRef, 0, ctypes.byref(desc))
            if sts != 0:
                print >>sys.stderr, "argvemulator warning: cannot unpack open document event"
                running[0] = False
                return

            sz = carbon.AEGetDescDataSize(ctypes.byref(desc))
            buf = ctypes.create_string_buffer(sz)
            sts = carbon.AEGetDescData(ctypes.byref(desc), buf, sz)
            if sts != 0:
                print >>sys.stderr, "argvemulator warning: cannot extract open document event"
                continue

            fsref = buf

            buf = ctypes.create_string_buffer(1024)
            sts = carbon.FSRefMakePath(ctypes.byref(fsref), buf, 1023)
            if sts != 0:
                print >>sys.stderr, "argvemulator warning: cannot extract open document event"
                continue

            print >>sys.stderr, "Adding: %s"%(repr(buf.value.decode('utf-8')),)

            if sys.version_info[0] > 2:
                sys.argv.append(buf.value.decode('utf-8'))
            else:
                sys.argv.append(buf.value)

        running[0] = False
	return 0

    carbon.AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
            open_file_handler, 0, FALSE)

    @ae_callback
    def open_url_handler(message, reply, refcon):
        listdesc = AEDesc()
        ok = carbon.AEGetParamDesc(message, keyDirectObject, typeAEList,
                ctypes.byref(listdesc))
        if ok != 0:
            print >>sys.stderr, "argvemulator warning: cannot unpack open document event"
            running[0] = False
            return

        item_count = ctypes.c_long()
        sts = carbon.AECountItems(ctypes.byref(listdesc), ctypes.byref(item_count))
        if sts != 0:
            print >>sys.stderr, "argvemulator warning: cannot unpack open url event"
            running[0] = False
            return

        desc = AEDesc()
        for i in range(item_count.value):
            sts = carbon.AEGetNthDesc(ctypes.byref(listdesc), i+1, typeChar, 0, ctypes.byref(desc))
            if sts != 0:
                print >>sys.stderr, "argvemulator warning: cannot unpack open URL event"
                running[0] = False
                return

            sz = carbon.AEGetDescDataSize(ctypes.byref(desc))
            buf = ctypes.create_string_buffer(sz)
            sts = carbon.AEGetDescData(ctypes.byref(desc), buf, sz)
            if sts != 0:
                print >>sys.stderr, "argvemulator warning: cannot extract open URL event"

            else:
                if sys.version_info[0] > 2:
                    sys.argv.append(buf.value.decode('utf-8'))
                else:
                    sys.argv.append(buf.value)

        running[0] = False
	return 0
    
    carbon.AEInstallEventHandler(kAEInternetSuite, kAEISGetURL,
            open_url_handler, 0, FALSE)

    # Remove the funny -psn_xxx_xxx argument
    if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn':
	del sys.argv[1]

    start = time.time()
    now = time.time()
    eventType = EventTypeSpec()
    eventType.eventClass = kEventClassAppleEvent
    eventType.eventKind = kEventAppleEvent

    while running[0] and now - start < timeout:
        event = ctypes.c_void_p()

        sts = carbon.ReceiveNextEvent(1, ctypes.byref(eventType), 
                start + timeout - now, TRUE, ctypes.byref(event))
        if sts != 0:
            print >>sys.stderr, "argvemulator warning: fetching events failed"
            break

        sts = carbon.AEProcessEvent(event)
        if sts != 0:
            print >>sys.stderr, "argvemulator warning: processing events failed"
            break
        

    carbon.AERemoveEventHandler(kCoreEventClass, kAEOpenApplication, 
            open_app_handler, FALSE)
    carbon.AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments,
            open_file_handler, FALSE)
    carbon.AERemoveEventHandler(kAEInternetSuite, kAEISGetURL,
            open_url_handler, FALSE)
Ejemplo n.º 56
0
 def get_parameter(self, name):
     ptr = c_void_p()
     self._call("GetParameter", prepare_str(name), byref(ptr))
     return ParameterInstance(ptr)
Ejemplo n.º 57
0
 def test_SDL_GetDesktopDisplayMode(self):
     numdisplays = video.SDL_GetNumVideoDisplays()
     for index in range(numdisplays):
         dmode = video.SDL_DisplayMode()
         ret = video.SDL_GetDesktopDisplayMode(index, byref(dmode))
         self.assertEqual(ret, 0)
Ejemplo n.º 58
0
 def paused(self):
     paused = c_bool()
     self._call("GetPaused", byref(paused))
     return paused.value
Ejemplo n.º 59
0
 def new_mpz():
     return byref(_MPZ())
Ejemplo n.º 60
0
    def step1(self, py_num_ghost, py_mx, qbc, auxbc, py_dx, py_dt, method,
              mthlim, fwave, rp):
        r"""
        Take one time step on the homogeneous hyperbolic system.

        This function directly wraps the Clawpack step1 call, and is responsible
        for translating Pythonic data structures into their C/Fortran
        equivalents.
        """

        from ctypes import c_int, c_double, c_bool, byref

        # a real solver object would be caching/verifying these values, this is
        # just scaffolding

        py_num_eqn, mxbc = qbc.shape
        num_eqn = c_int(py_num_eqn)

        mthlim = np.asarray(mthlim, dtype=np.int)
        py_num_waves = mthlim.shape[0]
        num_waves = c_int(py_num_waves)

        py_num_aux, mxauxbc = auxbc.shape
        num_aux = c_int(py_num_aux)

        cfl = c_double()
        use_fwave = c_bool(False)

        num_ghost = c_int(py_num_ghost)
        mx = c_int(py_mx)

        dx = c_double(py_dx)
        dt = c_double(py_dt)

        if not self.allocated:
            self.allocate(py_mx, py_num_eqn, py_num_ghost, py_num_waves)

        def to_double_ref(nparray):
            return nparray.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

        def to_int_ref(nparray):
            return nparray.ctypes.data_as(ctypes.POINTER(ctypes.c_int))

        self._dll.step1_c(byref(num_eqn), byref(num_waves), byref(num_ghost),
                          byref(num_aux), byref(mx), to_double_ref(qbc),
                          to_double_ref(auxbc), byref(dx), byref(dt),
                          to_int_ref(method), to_int_ref(mthlim), byref(cfl),
                          to_double_ref(self._f), to_double_ref(self._wave),
                          to_double_ref(self._s), to_double_ref(self._amdq),
                          to_double_ref(self._apdq), to_double_ref(self._dtdx),
                          byref(use_fwave), byref(rp._rp), byref(rp.context))

        return qbc, cfl.value