def read_mp(self): ''' Read NTARGS points from an rxp file ''' if not self.file: raise RXPException("RXPFile is not open") want = ctypes.c_uint(NTARGS) pxyz32 = (_C_scanifc_xyz32_t * NTARGS)() pattributes = (_C_scanifc_attributes_t * NTARGS)() ptime = (ctypes.c_ulonglong * NTARGS)() got = ctypes.c_uint() eof = ctypes.c_bool() print "\n#{}: Reading {} points".format(time.strftime('%X %x'), NTARGS) self._wrap_call(self.lib.scanifc_point3dstream_read( self.file, want, ctypes.byref(pxyz32), ctypes.byref(pattributes), ctypes.byref(ptime), ctypes.byref(got), ctypes.byref(eof) )) print "\n#{}: Got {} points".format(time.strftime('%X %x'), got.value) if got.value <= 0: print "\n#{}: All points read".format(time.strftime('%X %x')) return 0 return [np.array(ptime), np.array(pxyz32), np.array(pattributes)]
def get_named_security_info(self, obj_name, obj_type, security_info_flags): """Retrieve object security information. :param security_info_flags: specifies which informations will be retrieved. :param ret_val: dict, containing pointers to the requested structures. Note that the returned security descriptor will have to be freed using LocalFree. Some requested information may not be present, in which case the according pointers will be NULL. """ sec_info = {} if security_info_flags & OWNER_SECURITY_INFORMATION: sec_info['pp_sid_owner'] = self._get_void_pp() if security_info_flags & GROUP_SECURITY_INFORMATION: sec_info['pp_sid_group'] = self._get_void_pp() if security_info_flags & DACL_SECURITY_INFORMATION: sec_info['pp_dacl'] = self._get_void_pp() if security_info_flags & SACL_SECURITY_INFORMATION: sec_info['pp_sacl'] = self._get_void_pp() sec_info['pp_sec_desc'] = self._get_void_pp() self._win32_utils.run_and_check_output( advapi.GetNamedSecurityInfoW, ctypes.c_wchar_p(obj_name), ctypes.c_uint(obj_type), ctypes.c_uint(security_info_flags), sec_info.get('pp_sid_owner'), sec_info.get('pp_sid_group'), sec_info.get('pp_dacl'), sec_info.get('pp_sacl'), sec_info['pp_sec_desc']) return sec_info
def __init__(self, _context=None): """ Initializes a new instance of the Context class, using the local or the network backend of the IIO library. returns: type=iio.Context An new instance of this class This function will create a network context if the IIOD_REMOTE environment variable is set to the hostname where the IIOD server runs. If set to an empty string, the server will be discovered using ZeroConf. If the environment variable is not set, a local context will be created instead. """ if(_context is None): self._context = _new_default() elif type(_context) is str: self._context = _new_uri(_context) else: self._context = _context # TODO(pcercuei): Use a dictionary for the devices. self._devices = [ Trigger(dev) if _d_is_trigger(dev) else Device(self, dev) for dev in \ [ _get_device(self._context, x) for x in xrange(0, _devices_count(self._context)) ]] self._name = _get_name(self._context) self._description = _get_description(self._context) self._xml = _get_xml(self._context) major = c_uint() minor = c_uint() buf = create_string_buffer(8) _get_version(self._context, _byref(major), _byref(minor), buf) self._version = (major.value, minor.value, buf.value )
def read(self, jobnr): ''' Read points from an rxp file ''' if not self.file: raise RXPException("RXPFile is not open") want = ctypes.c_uint(NTARGS) pxyz32 = (_C_scanifc_xyz32_t * NTARGS)() pattributes = (_C_scanifc_attributes_t * NTARGS)() ptime = (ctypes.c_ulonglong * NTARGS)() got = ctypes.c_uint() eof = ctypes.c_bool() while True: self._wrap_call(self.lib.scanifc_rmsstream_read( self.file, want, ctypes.byref(pxyz32), ctypes.byref(pattributes), ctypes.byref(ptime), ctypes.byref(got), ctypes.byref(eof), ctypes.byref(ctypes.c_ushort(jobnr)) )) self.data = [ptime, pxyz32, pattributes] break
def runApp(self): self.getter.start() getpid=self.getter.pid procget=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(getpid)) kernel.SetPriorityClass(procget, 0x0100) self.processer.start() procpid=self.processer.pid procproc=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(procpid)) kernel.SetPriorityClass(procproc, 0x0100) try: while self.getter.is_alive(): #print("Entered Loop") data=self.q.recv() #if type(data)==str:print(data) #print("Got data"+str(len(data))) #print("Data"+str(data)) print(len(data)) #print(self.processer.is_alive()) print(time.time()) #print(data) self.system_up_time+=16/128 #ms=self.checkMarkerStatus() #print(self.system_up_time) ## for i in data: ## i.append(ms) ## self.writelines(data) except: self.getter.terminate() self.processer.terminate() self.closedump() raise
def getCpuAffinity(): """ Get affinity of current process as a list of all CPU numbers to which the process is assigned. May return None if something went wrong. """ maxNum = getCpuCount() result = [] procMask = c_uint() sysMask = c_uint() retval = GetProcessAffinityMask(GetCurrentProcess(), byref(procMask), byref(sysMask)) if retval == 0: # Something went wrong return None procMask = procMask.value for i in range(maxNum): if (procMask & (1 << i)) != 0: result.append(i) return result
def som_create(rows, cols, conn_type, parameters): """! @brief Create of self-organized map using CCORE pyclustering library. @param[in] rows (uint): Number of neurons in the column (number of rows). @param[in] cols (uint): Number of neurons in the row (number of columns). @param[in] conn_type (type_conn): Type of connection between oscillators in the network (grid four, grid eight, honeycomb, function neighbour). @param[in] parameters (som_parameters): Other specific parameters. @return (POINTER) C-pointer to object of self-organized feature in memory. """ ccore = cdll.LoadLibrary(PATH_DLL_CCORE_64); c_params = c_som_parameters(); c_params.init_type = parameters.init_type; c_params.init_radius = parameters.init_radius; c_params.init_learn_rate = parameters.init_learn_rate; c_params.adaptation_threshold = parameters.adaptation_threshold; som_pointer = ccore.som_create(c_uint(rows), c_uint(cols), c_uint(conn_type), pointer(c_params)); return som_pointer;
def texture_from_data(internalformat, size, data_format, data_type, data): '''Create texture from a data buffer (whatever can be passed as pointer to ctypes) internalformat - GL_RGBA8 or GL_RGB8 recommended size - a 1-, 2- or 3-tuple describing the image sizes data_format - see 'format' parameter of glDrawPixels data_type - see 'type' parameter of glDrawPixels data - pointer to memory''' size = list(size) dimensions = len(size) binding = getattr(gl, 'GL_TEXTURE_BINDING_{0:d}D'.format(dimensions)) target = getattr(gl,'GL_TEXTURE_{0:d}D'.format(dimensions)) texImage = getattr(gl,'glTexImage{0:d}D'.format(dimensions)) oldbind = ctypes.c_uint(0) gl.glGetIntegerv(binding, ctypes.cast(ctypes.byref(oldbind), ctypes.POINTER(ctypes.c_int))) texid = ctypes.c_uint(0) gl.glEnable(target) gl.glGenTextures(1, ctypes.byref(texid)) gl.glBindTexture(target, texid) gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) args = [target, 0, internalformat] + size + [0, data_format, data_type, data] texImage(*args) gl.glBindTexture(target, oldbind) return texid
def interceptWinProc(self, interceptCollection, params): """ Called for each Windows message to the intercepted window. This is the ANSI-style method, wide-char is not supported. params -- WinProcParams object containing parameters the function can modify and a returnValue which can be set to prevent from calling interceptWinProc functions """ if params.uMsg == WM_CHANGECBCHAIN: if self.nextWnd == params.wParam: # repair the chain self.nextWnd = params.lParam if self.nextWnd: # Neither None nor 0 # pass the message to the next window in chain SendMessage(c_int(self.nextWnd), c_int(params.uMsg), c_uint(params.wParam), c_ulong(params.lParam)) elif params.uMsg == WM_DRAWCLIPBOARD: if self.ignoreNextCCMessage: self.ignoreNextCCMessage = False else: self.handleClipboardChange() if self.nextWnd: # Neither None nor 0 # pass the message to the next window in chain SendMessage(c_int(self.nextWnd), c_int(params.uMsg), c_uint(params.wParam), c_ulong(params.lParam))
def ant_colony_TSP_run(cities, params): dimension = len(cities[0]) cities_coord = ant_colony_TSP_cities() cities_coord.size = ct.c_uint(len(cities) * dimension) cities_coord.dimension = ct.c_uint(dimension) cities_coord.data = (ct.c_double * cities_coord.size)(); for i in range(0, cities_coord.size): cities_coord.data[i] =cities[i // dimension][i % dimension] cities_coord = ct.pointer(cities_coord); algorithm_params = ant_colony_TSP_params() algorithm_params.q = ct.c_double(params.q) algorithm_params.ro = ct.c_double(params.ro) algorithm_params.alpha = ct.c_double(params.alpha) algorithm_params.beta = ct.c_double(params.beta) algorithm_params.gamma = ct.c_double(params.gamma) algorithm_params.qinitial_pheramone = ct.c_double(params.qinitial_pheramone) algorithm_params.iterations = ct.c_uint(params.iterations) algorithm_params.count_ants_in_iteration = ct.c_uint(params.count_ants_in_iteration) algorithm_params = ct.pointer(algorithm_params) ccore = ct.cdll.LoadLibrary(PATH_DLL_CCORE_WIN64) result = ccore.ant_colony_TSP(cities_coord, algorithm_params) result = ct.cast(result, ct.POINTER(ant_colony_TSP_result))[0] #result = result[0] return result
def SetValue(self, value): # set object type otype = None size = 8 if type(value) == str: otype = ASN_OCTET_STR size = len(value) value = ctypes.c_char_p(value) elif type(value) == int: otype = ASN_INTEGER value = ctypes.pointer(ctypes.c_int(value)) elif type(value) == float: otype = ASN_APP_FLOAT value = ctypes.pointer(ctypes.c_float(value)) elif type(value) == SnmpIpAddress: otype = ASN_IPADDRESS size = 4 value = ctypes.c_char_p(socket.inet_aton(value)) elif type(value) == SnmpCounter32: otype = ASN_COUNTER32 value = ctypes.pointer(ctypes.c_uint(value)) elif type(value) == SnmpGauge32: otype = ASN_UNSIGNED value = ctypes.pointer(ctypes.c_uint(value)) axl.snmp_set_var_typed_value(self.__request.requestvb, otype, ctypes.cast(value, ctypes.POINTER(ctypes.c_ubyte)), size) self.value = value
def createmesh(n, vertices, normals, colors): """ This function creates a int from vertex position, normal and color data. Returns a mesh. **Parameters:** `vertices` : the vertex positions `normals` : the vertex normals `colors` : the vertex colors, they should be white (1,1,1) if you want to change the color for each drawn mesh `n` : the number of vertices in the mesh **Raises:** `gr3.GR3_Error.GR3_ERROR_EXPORT`: Raises GR3_Exception +----------------------+-------------------------------+ | GR3_ERROR_NONE | on success | +----------------------+-------------------------------+ | GR3_ERROR_OPENGL_ERR | if an OpenGL error occured | +----------------------+-------------------------------+ | GR3_ERROR_OUT_OF_MEM | if a memory allocation failed | +----------------------+-------------------------------+ """ _mesh = c_uint(0) vertices = floatarray(vertices) normals = floatarray(normals) colors = floatarray(colors) err = _gr3.gr3_createmesh(byref(_mesh), c_uint(n), vertices.data, normals.data, colors.data) if err: raise GR3_Exception(err) return _mesh
def __new__(cls, name, bases, classdict): # figure out which members of the class are enum items _members = {} _rev_members = {} for k, v in iteritems(classdict): if not k.startswith('_'): try: c_uint(v) except TypeError: pass else: if not k == k.upper(): raise ValueError("Enum values must be all-uppercase") classdict[k] = _members[k] = v _rev_members[v] = k # construct the class classdict['_members'] = _members classdict['_rev_members'] = _rev_members the_type = type(c_uint).__new__(cls, name, bases, classdict) # now that the class is finalized, switch members to be of the class for k, v in iteritems(_members): as_class = the_type(v) the_type._members[k] = as_class setattr(the_type, k, as_class) return the_type
def runApp(self): self.getter.start() getpid=self.getter.pid procget=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(getpid)) kernel.SetPriorityClass(procget, 0x0100) self.processer.start() procpid=self.processer.pid procproc=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(procpid)) kernel.SetPriorityClass(procproc, 0x0100) data_dict=dict({"F3":[], "F4":[], "T7":[], "T8":[]}) try: while self.getter.is_alive(): data=self.q.recv() #print(data) for i in data_dict: data_dict[i].append(data[i][0][2]) if len(data_dict["F3"])==24: for i in data_dict: del data_dict[i][0] jj=self.livedataclass.test_classifiers_ret(data_dict) if jj>=0.85: print("You moved") print(jj) #print(data_dict) print(time.time()) self.system_up_time+=16/128 except: self.getter.terminate() self.processer.terminate() raise
def get_buffer(self, bytes): '''Fill and return an OpenAL buffer''' frames = ctypes.c_uint(bytes / self.bytes_per_frame) flags = ctypes.c_uint() buffer = (ctypes.c_byte * bytes)() audio_buffer_list = AudioBufferList() audio_buffer_list.mNumberBuffers = 1 audio_buffer_list.mBuffers[0].mNumberChannels = self.channels audio_buffer_list.mBuffers[0].mDataByteSize = bytes audio_buffer_list.mBuffers[0].mData = \ ctypes.cast(buffer, ctypes.c_void_p) result = quicktime.MovieAudioExtractionFillBuffer( self.extraction_session_ref, ctypes.byref(frames), ctypes.byref(audio_buffer_list), ctypes.byref(flags)) _oscheck(result) if frames.value == 0: return None size = audio_buffer_list.mBuffers[0].mDataByteSize albuffer = openal.buffer_pool.get(self.time) al.alBufferData(albuffer, self.format, audio_buffer_list.mBuffers[0].mData, size, int(self.sample_rate)) self.time += self.seconds_per_byte * size return albuffer
def read(self, timeout=0): """Read a CAN message and metadata. Reads a message from the receive buffer. If no message is available, the function waits until a message arrives or a timeout occurs. Args: timeout (int): Timeout in milliseconds, -1 gives an infinite timeout. Returns: id_ (int): CAN identifier msg (bytes): CAN data - max length 8 dlc (int): Data Length Code flag (int): Flags, a combination of the canMSG_xxx and canMSGERR_xxx values time (float): Timestamp from hardware """ self.canlib.fn = inspect.currentframe().f_code.co_name # msg will be replaced by class when CAN FD is supported _MAX_SIZE = 8 msg = ct.create_string_buffer(_MAX_SIZE) id_ = ct.c_long() dlc = ct.c_uint() flag = ct.c_uint() time = ct.c_ulong() self.dll.canReadWait(self.handle, id_, msg, dlc, flag, time, timeout) length = min(_MAX_SIZE, dlc.value) return(id_.value, bytearray(msg.raw[:length]), dlc.value, flag.value, time.value)
def config_maps(self): # program id prog_id_pem = 1 prog_id_br1 = 2 prog_id_br2 = 3 # initial port id and table pointers curr_pem_pid = 0 curr_br1_pid = 0 curr_br2_pid = 0 # configure jump table self.jump[c_uint(prog_id_pem)] = c_uint(self.pem_fn.fd) self.jump[c_uint(prog_id_br1)] = c_uint(self.br1_fn.fd) self.jump[c_uint(prog_id_br2)] = c_uint(self.br2_fn.fd) # connect pem and br1 curr_pem_pid = curr_pem_pid + 1 curr_br1_pid = curr_br1_pid + 1 self.connect_ports(prog_id_pem, prog_id_br1, curr_pem_pid, curr_br1_pid, self.br1_dest, self.br1_mac, self.ns1_eth_out.index, self.vm1_mac, self.vm1_ip) # connect pem and br2 curr_pem_pid = curr_pem_pid + 1 curr_br2_pid = curr_br2_pid + 1 self.connect_ports(prog_id_pem, prog_id_br2, curr_pem_pid, curr_br2_pid, self.br2_dest, self.br2_mac, self.ns2_eth_out.index, self.vm2_mac, self.vm2_ip) # connect <br1, rtr> and <br2, rtr> self.br1_rtr[c_uint(0)] = c_uint(self.nsrtr_eth0_out.index) self.br2_rtr[c_uint(0)] = c_uint(self.nsrtr_eth1_out.index)
def setresuid(ruid=-1, euid=-1, suid=-1): ruid = ctypes.c_uint(ruid) euid = ctypes.c_uint(euid) suid = ctypes.c_uint(suid) res = _libc.setresuid(ruid, euid, suid) if res: raise OSError(_errno.value, os.strerror(_errno.value))
def setresgid(rgid=-1, egid=-1, sgid=-1): rgid = ctypes.c_uint(rgid) egid = ctypes.c_uint(egid) sgid = ctypes.c_uint(sgid) res = _libc.setresgid(rgid, egid, sgid) if res: raise OSError(_errno.value, os.strerror(_errno.value))
def get_frame(nEvent, ctx): if nEvent == TOUPCAM_EVENT_IMAGE: w, h = ctypes.c_uint(), ctypes.c_uint() bits = ctypes.c_int(self.bits) # if self._cnt == 4: # for i,row in enumerate(self._data): # print i, row[10] # # self._cnt+=1 lib.Toupcam_PullImage(self.cam, ctypes.c_void_p(self._data.ctypes.data), bits, ctypes.byref(w), ctypes.byref(h)) elif nEvent == TOUPCAM_EVENT_STILLIMAGE: w, h = self.get_size() h, w = h.value, w.value dtype = uint32 shape = (h, w) still = zeros(shape, dtype=dtype) bits = ctypes.c_int(self.bits) lib.Toupcam_PullStillImage(self.cam, ctypes.c_void_p(still.ctypes.data), bits, None, None) self._do_save(still)
def track_memory(self): ''' Calculates the induced voltage energy kick to particles taking into account multi-turn induced voltage plus inductive impedance contribution. ''' # Contribution from multi-turn induced voltage. self.array_memory *= np.exp(self.omegaj_array_memory * self.rev_time_array[self.counter_turn]) induced_voltage = irfft(self.array_memory + rfft(self.slices.n_macroparticles, self.n_points_fft) * self.sum_impedances_memory, self.n_points_fft) self.induced_voltage = self.coefficient * induced_voltage[:self.slices.n_slices] induced_voltage[self.len_array_memory:]=0 self.array_memory = rfft(induced_voltage, self.n_points_fft) # Contribution from inductive impedance if self.inductive_impedance_on: self.induced_voltage_list[self.index_inductive_impedance].induced_voltage_generation(self.beam, 'slice_frame') self.induced_voltage += self.induced_voltage_list[self.index_inductive_impedance].induced_voltage # Induced voltage energy kick to particles through linear interpolation libfib.linear_interp_kick(self.beam.dt.ctypes.data_as(ctypes.c_void_p), self.beam.dE.ctypes.data_as(ctypes.c_void_p), self.induced_voltage.ctypes.data_as(ctypes.c_void_p), self.slices.bin_centers.ctypes.data_as(ctypes.c_void_p), ctypes.c_uint(self.slices.n_slices), ctypes.c_uint(self.beam.n_macroparticles), ctypes.c_double(0.)) # Counter update self.counter_turn += 1
def decompress(in_buf, out_size): dll = ctypes.CDLL(_find_native()) with decomp_context(dll) as ctx: in_size = len(in_buf) compressed_position = 0 compressed_todo = in_size decompressed_position = 0 decompressed_todo = out_size s_in_buf = ctypes.create_string_buffer(in_buf, in_size) s_out_buf = ctypes.create_string_buffer(out_size) while decompressed_todo > 0 and compressed_todo > 0: compressed_size = in_size - compressed_position decompressed_size = out_size - decompressed_position s_compressed_size = ctypes.c_uint(compressed_size) s_decompressed_size = ctypes.c_uint(decompressed_size) err = dll.Decompress(ctx, ctypes.byref(s_out_buf, decompressed_position), ctypes.byref(s_decompressed_size), ctypes.byref(s_in_buf, compressed_position), ctypes.byref(s_compressed_size)) r_compressed_size = int(s_compressed_size.value) r_decompressed_size = int(s_decompressed_size.value) if err: raise IOError("Decompress failed: {}".format(err)) if r_compressed_size == 0 and r_decompressed_size == 0: raise IOError("Decompress failed") compressed_position += r_compressed_size decompressed_position += r_decompressed_size compressed_todo -= r_compressed_size decompressed_todo -= r_decompressed_size return s_out_buf.raw
def SetProcessPriority(pid, priority): ret = 0 hProcess = OpenProcess(c_uint(PROCESS_SET_INFORMATION), 0, c_uint(pid)) if hProcess: ret = SetPriorityClass(hProcess, c_uint(priority)) CloseHandle(hProcess) return ret
def getFileVersionInfo(name, *attributes): """Gets the specified file version info attributes from the provided file.""" if not isinstance(name, text_type): raise TypeError("name must be an unicode string") if not os.path.exists(name): raise RuntimeError("The file %s does not exist" % name) fileVersionInfo = {} # Get size needed for buffer (0 if no info) size = ctypes.windll.version.GetFileVersionInfoSizeW(name, None) if not size: raise RuntimeError("No version information") # Create buffer res = ctypes.create_string_buffer(size) # Load file informations into buffer res ctypes.windll.version.GetFileVersionInfoW(name, None, size, res) r = ctypes.c_uint() l = ctypes.c_uint() # Look for codepages ctypes.windll.version.VerQueryValueW(res, u'\\VarFileInfo\\Translation', ctypes.byref(r), ctypes.byref(l)) if not l.value: raise RuntimeError("No codepage") # Take the first codepage (what else ?) codepage = array.array('H', ctypes.string_at(r.value, 4)) codepage = "%04x%04x" % tuple(codepage) for attr in attributes: if not ctypes.windll.version.VerQueryValueW(res, u'\\StringFileInfo\\%s\\%s' % (codepage, attr), ctypes.byref(r), ctypes.byref(l) ): log.warning("Invalid or unavailable version info attribute for %r: %s" % (name, attr)) fileVersionInfo[attr] = None else: fileVersionInfo[attr] = ctypes.wstring_at(r.value, l.value-1) return fileVersionInfo
def GetProcessPriority(pid): ret = 0 hProcess = OpenProcess(c_uint(PROCESS_QUERY_INFORMATION), 0, c_uint(pid)) if hProcess: ret = GetPriorityClass(hProcess) CloseHandle(hProcess) return ret
def Cpp_dAgamma0_dZeta(zetaSrc,mSrc,nSrc,gamma0,zetaTgt,mTgt,nTgt,dAgam0,imageMeth=False): """@details Wrapper for cpp_wrap_dAgamma0_dZeta. @param zetaSrc Source grid points. @param mSrc Chordwise panels. @param nSrc Spanwise. @param gamma0 Reference circulation distribution. @param zetaTgt Target grid points. @param mTgt Chordwise panels. @param nTgt Spanwise. @return dAgam0 variation of influence coefficient matrix times gamma.""" # make sure y>=0 for all zetas if imageMeth: assert np.all( zetaSrc[1::3] >= 0.0 ), "source grid defintion in negative y" assert np.all( zetaTgt[1::3] >= 0.0 ), "target grid defintion in negative y" # end if cpp_dAgamma0_dZeta(zetaSrc.ctypes.data_as(ct.POINTER(ct.c_double)), ct.byref(ct.c_uint(mSrc)), ct.byref(ct.c_uint(nSrc)), gamma0.ctypes.data_as(ct.POINTER(ct.c_double)), zetaTgt.ctypes.data_as(ct.POINTER(ct.c_double)), ct.byref(ct.c_uint(mTgt)), ct.byref(ct.c_uint(nTgt)), ct.byref(ct.c_bool(imageMeth)), dAgam0.ctypes.data_as(ct.POINTER(ct.c_double)))
def Cpp_AIC3s(zetaSrc,mSrc,nSrc,zetaTgt,mTgt,nTgt,AIC3,imageMeth=False): """@details Wrapper for cpp_wrap_AICnoTE. @param zetaSrc Source grid points. @param mSrc Chordwise panels. @param nSrc Spanwise. @param zetaTgt Target grid points. @param mTgt Chordwise panels. @param nTgt Spanwise. @param imageMeth Image method across x-z plane. @return AIC3 3-component influence coefficient matrix at segment midpoints.""" # make sure y>=0 for all zetas if imageMeth: assert np.all( zetaSrc[1::3] >= 0.0 ), "source grid defintion in negative y" assert np.all( zetaTgt[1::3] >= 0.0 ), "target grid defintion in negative y" # end if cpp_AIC3s(zetaSrc.ctypes.data_as(ct.POINTER(ct.c_double)), ct.byref(ct.c_uint(mSrc)), ct.byref(ct.c_uint(nSrc)), zetaTgt.ctypes.data_as(ct.POINTER(ct.c_double)), ct.byref(ct.c_uint(mTgt)), ct.byref(ct.c_uint(nTgt)), ct.byref(ct.c_bool(imageMeth)), AIC3.ctypes.data_as(ct.POINTER(ct.c_double)))
def frame_fn(nEvent, ctx): if nEvent == 4: w, h = ctypes.c_uint(), ctypes.c_uint() result = lib.Toupcam_PullImage(cobj, ctypes.c_void_p(data.ctypes.data), bits, ctypes.byref(w), ctypes.byref(h)) if success(result): draw_cb(data)
def createtubemesh(n, points, colors, radii, num_steps=10, num_segments=20): """ Create a mesh object in the shape of a tube following a path given by a list of points. The colors and radii arrays specify the color and radius at each point. **Parameters:** `n` : the number of points given `points` : the points the tube should go through `colors` : the color at each point `radii` : the desired tube radius at each point `num_steps` : the number of steps between each point, allowing for a more smooth tube `num_segments` : the number of segments each ring of the tube consists of, e.g. 3 would yield a triangular tube """ _mesh = c_uint(0) points = floatarray(points) colors = floatarray(colors) radii = floatarray(radii) err = _gr3.gr3_createtubemesh(byref(_mesh), c_uint(n), points.data, colors.data, radii.data, c_int(num_steps), c_int(num_segments)) if err: raise GR3_Exception(err) return _mesh
def init_x11lib(self): x_library_location = ctypes.util.find_library('X11') self.libX11 = ctypes.CDLL(x_library_location) self.libX11.XOpenDisplay.restype = ctypes.POINTER(Display) self.xkb_use_core_kbd = ctypes.c_uint(0x0100) # Two threads, two displays and two event masks: # 1. Main thread for get, set and icon UI events # 2. Spawned thread, for kb and other processes' events mask_mt = ctypes.c_uint(1 << 2) mask_et = ctypes.c_uint(1 << 11) self.display_mt = self.libX11.XOpenDisplay(None) self.display_et = self.libX11.XOpenDisplay(None) self.libX11.XkbSelectEvents( self.display_mt, self.xkb_use_core_kbd, mask_mt, mask_mt, ) self.libX11.XkbSelectEvents( self.display_et, self.xkb_use_core_kbd, mask_et, mask_et, ) Thread(target=self.poll).start()
def _init_op_module(root_namespace, module_name, make_op_func): """ Registers op functions created by `make_op_func` under `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. make_op_func : function Function for creating op functions for `ndarray` and `symbol` modules. """ plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist))) op_names = [] for i in range(size.value): op_names.append(py_str(plist[i])) module_op = sys.modules["%s.%s.op" % (root_namespace, module_name)] module_internal = sys.modules["%s.%s._internal" % (root_namespace, module_name)] # contrib module in the old format (deprecated) # kept here for backward compatibility # use mx.nd.contrib or mx.sym.contrib from now on contrib_module_name_old = "%s.contrib.%s" % (root_namespace, module_name) contrib_module_old = sys.modules[contrib_module_name_old] submodule_dict = {} for op_name_prefix in _OP_NAME_PREFIX_LIST: submodule_dict[op_name_prefix] =\ sys.modules["%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])] for name in op_names: hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) op_name_prefix = _get_op_name_prefix(name) module_name_local = module_name if len(op_name_prefix) > 0: func_name = name[len(op_name_prefix):] cur_module = submodule_dict[op_name_prefix] module_name_local = "%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1]) elif name.startswith('_'): func_name = name cur_module = module_internal else: func_name = name cur_module = module_op function = make_op_func(hdl, name, func_name) function.__module__ = module_name_local setattr(cur_module, function.__name__, function) cur_module.__all__.append(function.__name__) if op_name_prefix == '_contrib_': hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) func_name = name[len(op_name_prefix):] function = make_op_func(hdl, name, func_name) function.__module__ = contrib_module_name_old setattr(contrib_module_old, function.__name__, function) contrib_module_old.__all__.append(function.__name__)
def _get_lib_version(): major = c_uint() minor = c_uint() buf = create_string_buffer(8) _get_library_version(_byref(major), _byref(minor), buf) return (major.value, minor.value, buf.value.decode("ascii"))
def get_color(self): return uint2rgb( ctypes.c_uint(self.lib.CF_CM_itemColor(self.cm, self.index)).value)
def convert_pmids_to_ctypes(self, pmids): from ctypes import c_uint pmidA = (c_uint * len(pmids))() for i, p in enumerate(pmids): pmidA[i] = c_uint(p) return pmidA
def __init__(self, frame_source_types, audio=True): # recipe to get address of surface: http://archives.seul.org/pygame/users/Apr-2008/msg00218.html is_64bits = sys.maxsize > 2**32 if not is_64bits: self.Py_ssize_t = ctypes.c_int else: self.Py_ssize_t = ctypes.c_int64 self._32_bit_max = numpy.finfo(numpy.float32).max self._PyObject_AsWriteBuffer = ctypes.pythonapi.PyObject_AsWriteBuffer self._PyObject_AsWriteBuffer.restype = ctypes.c_int self._PyObject_AsWriteBuffer.argtypes = [ ctypes.py_object, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(self.Py_ssize_t) ] #self._color_frame_ready = PyKinectV2._event() #self._depth_frame_ready = PyKinectV2._event() #self._body_frame_ready = PyKinectV2._event() #self._body_index_frame_ready = PyKinectV2._event() #self._infrared_frame_ready = PyKinectV2._event() #self._long_exposure_infrared_frame_ready = PyKinectV2._event() #self._audio_frame_ready = PyKinectV2._event() self._close_event = ctypes.windll.kernel32.CreateEventW( None, False, False, None) self._color_frame_arrived_event = 0 self._depth_frame_arrived_event = 0 self._body_frame_arrived_event = 0 self._body_index_frame_arrived_event = 0 self._infrared_frame_arrived_event = 0 self._long_exposure_infrared_frame_arrived_event = 0 self._audio_frame_arrived_event = 0 self._color_frame_lock = thread.allocate() self._depth_frame_lock = thread.allocate() self._body_frame_lock = thread.allocate() self._body_index_frame_lock = thread.allocate() self._infrared_frame_lock = thread.allocate() self._long_exposure_infrared_frame_lock = thread.allocate() self._audio_frame_lock = thread.allocate() #initialize sensor self._sensor = ctypes.POINTER(PyKinectV2.IKinectSensor)() hres = ctypes.windll.kinect20.GetDefaultKinectSensor( ctypes.byref(self._sensor)) hres = self._sensor.Open() self._mapper = self._sensor.CoordinateMapper self.frame_source_types = frame_source_types self.max_body_count = KINECT_MAX_BODY_COUNT self._handles = (ctypes.c_voidp * 8)() self._handles[0] = self._close_event self._handles[1] = self._close_event self._handles[2] = self._close_event self._handles[3] = self._close_event self._handles[4] = self._close_event self._handles[5] = self._close_event self._handles[6] = self._close_event self._handles[7] = self._close_event self._waitHandleCount = 1 self._color_source = self._sensor.ColorFrameSource self.color_frame_desc = self._color_source.FrameDescription self._depth_source = self._sensor.DepthFrameSource self.depth_frame_desc = self._depth_source.FrameDescription self._body_index_source = self._sensor.BodyIndexFrameSource self.body_index_frame_desc = self._body_index_source.FrameDescription self._body_source = self._sensor.BodyFrameSource self._body_frame_data = ctypes.POINTER(ctypes.POINTER(IBody)) self.max_body_count = self._body_source.BodyCount self._audio_source = self._sensor.AudioSource self._color_frame_data = None self._depth_frame_data = None self._body_frame_data = None self._body_index_frame_data = None self._infrared_frame_data = None self._long_exposure_infrared_frame_data = None self._audio_frame_data = None # Ryan Kirkbride audio if audio: self._audio_subframes = [] self._audio_frame_data = ctypes.POINTER(ctypes.c_ubyte) self._audio_frame_data_capacity = ctypes.c_uint( self._audio_source.SubFrameLengthInBytes) self._audio_frame_data_type = ctypes.c_ubyte * self._audio_frame_data_capacity.value self._audio_frame_data = ctypes.cast( self._audio_frame_data_type(), ctypes.POINTER(ctypes.c_ubyte)) self._audio_frame_reader = self._audio_source.OpenReader() self._audio_frame_arrived_event = self._audio_frame_reader.SubscribeFrameArrived( ) self._handles[ self._waitHandleCount] = self._audio_frame_arrived_event self._waitHandleCount += 1 if (self.frame_source_types & FrameSourceTypes_Color): self._color_frame_data = ctypes.POINTER(ctypes.c_ubyte) self._color_frame_data_capacity = ctypes.c_uint( self.color_frame_desc.Width * self.color_frame_desc.Height * 4) self._color_frame_data_type = ctypes.c_ubyte * self._color_frame_data_capacity.value self._color_frame_data = ctypes.cast( self._color_frame_data_type(), ctypes.POINTER(ctypes.c_ubyte)) self._color_frame_reader = self._color_source.OpenReader() self._color_frame_arrived_event = self._color_frame_reader.SubscribeFrameArrived( ) self._handles[ self._waitHandleCount] = self._color_frame_arrived_event self._waitHandleCount += 1 if (self.frame_source_types & FrameSourceTypes_Depth): self._depth_frame_data = ctypes.POINTER(ctypes.c_ushort) self._depth_frame_data_capacity = ctypes.c_uint( self.depth_frame_desc.Width * self.depth_frame_desc.Height) self._depth_frame_data_type = ctypes.c_ushort * self._depth_frame_data_capacity.value self._depth_frame_data = ctypes.cast( self._depth_frame_data_type(), ctypes.POINTER(ctypes.c_ushort)) self._depth_frame_reader = self._depth_source.OpenReader() self._depth_frame_arrived_event = self._depth_frame_reader.SubscribeFrameArrived( ) self._handles[ self._waitHandleCount] = self._depth_frame_arrived_event self._waitHandleCount += 1 if (self.frame_source_types & FrameSourceTypes_BodyIndex): self._body_index_frame_data = ctypes.POINTER(ctypes.c_ubyte) self._body_index_frame_data_capacity = ctypes.c_uint( self.body_index_frame_desc.Width * self.body_index_frame_desc.Height) self._body_index_frame_data_type = ctypes.c_ubyte * self._body_index_frame_data_capacity.value self._body_index_frame_data = ctypes.cast( self._body_index_frame_data_type(), ctypes.POINTER(ctypes.c_ubyte)) self._body_index_frame_reader = self._body_index_source.OpenReader( ) self._body_index_frame_arrived_event = self._body_index_frame_reader.SubscribeFrameArrived( ) self._handles[ self._waitHandleCount] = self._body_index_frame_arrived_event self._waitHandleCount += 1 self._body_frame_data = None if (self.frame_source_types & FrameSourceTypes_Body): self._body_frame_data_capacity = ctypes.c_uint(self.max_body_count) self._body_frame_data_type = ctypes.POINTER( IBody) * self._body_frame_data_capacity.value self._body_frame_data = ctypes.cast( self._body_frame_data_type(), ctypes.POINTER(ctypes.POINTER(IBody))) self._body_frame_reader = self._body_source.OpenReader() self._body_frame_arrived_event = self._body_frame_reader.SubscribeFrameArrived( ) self._body_frame_bodies = None self._handles[ self._waitHandleCount] = self._body_frame_arrived_event self._waitHandleCount += 1 thread.start_new_thread(self.kinect_frame_thread, ()) self._last_color_frame = None self._last_depth_frame = None self._last_body_frame = None self._last_body_index_frame = None self._last_infrared_frame = None self._last_long_exposure_infrared_frame = None self._last_audio_frame = None start_clock = time.clock() self._last_color_frame_access = self._last_color_frame_time = start_clock self._last_body_frame_access = self._last_body_frame_time = start_clock self._last_body_index_frame_access = self._last_body_index_frame_time = start_clock self._last_depth_frame_access = self._last_depth_frame_time = start_clock self._last_infrared_frame_access = self._last_infrared_frame_time = start_clock self._last_long_exposure_infrared_frame_access = self._last_long_exposure_infrared_frame_time = start_clock self._last_audio_frame_access = self._last_audio_frame_time = start_clock
#!/usr/bin/env python3 import ctypes import binascii num = 0x21DD09EC b = 269488144 a = num - b * 4 b = ctypes.c_uint(b).value a = ctypes.c_uint(a).value print(b.to_bytes(4, 'little') * 4 + a.to_bytes(4, 'little')) fp = open('exp', 'wb') fp.write(b.to_bytes(4, 'little') * 4) fp.write(a.to_bytes(4, 'little')) fp.close
def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func): """ Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. op_code_gen_func : function Function for creating op functions for `ndarray` and `symbol` modules. """ def get_module_file(module_name): """Return the generated module file based on module name.""" path = os.path.dirname(__file__) module_path = module_name.split('.') module_path[-1] = 'gen_'+module_path[-1] file_name = os.path.join(path, '..', *module_path) + '.py' module_file = open(file_name, 'w') dependencies = {'symbol': ['from ._internal import SymbolBase', 'from ..base import _Null'], 'ndarray': ['from ._internal import NDArrayBase', 'from ..base import _Null']} module_file.write('# File content is auto-generated. Do not modify.'+os.linesep) module_file.write('# pylint: skip-file'+os.linesep) module_file.write(os.linesep.join(dependencies[module_name.split('.')[1]])) return module_file def write_all_str(module_file, module_all_list): """Write the proper __all__ based on available operators.""" module_file.write(os.linesep) module_file.write(os.linesep) all_str = '__all__ = [' + ', '.join(["'%s'"%s for s in module_all_list]) + ']' module_file.write(all_str) plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist))) op_names = [] for i in range(size.value): op_names.append(py_str(plist[i])) module_op_file = get_module_file("%s.%s.op" % (root_namespace, module_name)) module_op_all = [] module_internal_file = get_module_file("%s.%s._internal"%(root_namespace, module_name)) module_internal_all = [] submodule_dict = {} for op_name_prefix in _OP_NAME_PREFIX_LIST: submodule_dict[op_name_prefix] =\ (get_module_file("%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])), []) for name in op_names: hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) op_name_prefix = _get_op_name_prefix(name) if len(op_name_prefix) > 0: func_name = name[len(op_name_prefix):] cur_module_file, cur_module_all = submodule_dict[op_name_prefix] elif name.startswith('_'): func_name = name cur_module_file = module_internal_file cur_module_all = module_internal_all else: func_name = name cur_module_file = module_op_file cur_module_all = module_op_all code, _ = op_code_gen_func(hdl, name, func_name, True) cur_module_file.write(os.linesep) cur_module_file.write(code) cur_module_all.append(func_name) for (submodule_f, submodule_all) in submodule_dict.values(): write_all_str(submodule_f, submodule_all) submodule_f.close() write_all_str(module_op_file, module_op_all) module_op_file.close() write_all_str(module_internal_file, module_internal_all) module_internal_file.close()
def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func): """ Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Second level module name, `ndarray` and `symbol` in the current cases. op_code_gen_func : function Function for creating op functions for `ndarray` and `symbol` modules. """ license_lines = [ '# Licensed to the Apache Software Foundation (ASF) under one', '# or more contributor license agreements. See the NOTICE file', '# distributed with this work for additional information', '# regarding copyright ownership. The ASF licenses this file', '# to you under the Apache License, Version 2.0 (the', '# "License"); you may not use this file except in compliance', '# with the License. You may obtain a copy of the License at', '#', '# http://www.apache.org/licenses/LICENSE-2.0', '#', '# Unless required by applicable law or agreed to in writing,', '# software distributed under the License is distributed on an', '# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY', '# KIND, either express or implied. See the License for the', '# specific language governing permissions and limitations', '# under the License.', '', ] license_str = os.linesep.join(license_lines) def get_module_file(module_name): """Return the generated module file based on module name.""" path = os.path.dirname(__file__) module_path = module_name.split('.') module_path[-1] = 'gen_' + module_path[-1] file_name = os.path.join(path, '..', *module_path) + '.py' module_file = open(file_name, 'w', encoding="utf-8") dependencies = { 'symbol': ['from ._internal import SymbolBase', 'from ..base import _Null'], 'ndarray': ['from ._internal import NDArrayBase', 'from ..base import _Null'] } module_file.write('# coding: utf-8') module_file.write(license_str) module_file.write('# File content is auto-generated. Do not modify.' + os.linesep) module_file.write('# pylint: skip-file' + os.linesep) module_file.write( os.linesep.join(dependencies[module_name.split('.')[1]])) return module_file def write_all_str(module_file, module_all_list): """Write the proper __all__ based on available operators.""" module_file.write(os.linesep) module_file.write(os.linesep) all_str = '__all__ = [' + ', '.join( ["'%s'" % s for s in module_all_list]) + ']' module_file.write(all_str) plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist))) op_names = [] for i in range(size.value): op_name = py_str(plist[i]) if not _is_np_op(op_name): op_names.append(op_name) module_op_file = get_module_file("%s.%s.op" % (root_namespace, module_name)) module_op_all = [] module_internal_file = get_module_file("%s.%s._internal" % (root_namespace, module_name)) module_internal_all = [] submodule_dict = {} for op_name_prefix in _OP_NAME_PREFIX_LIST: submodule_dict[op_name_prefix] =\ (get_module_file("%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])), []) for name in op_names: hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) op_name_prefix = _get_op_name_prefix(name) if len(op_name_prefix) > 0: func_name = name[len(op_name_prefix):] cur_module_file, cur_module_all = submodule_dict[op_name_prefix] elif name.startswith('_'): func_name = name cur_module_file = module_internal_file cur_module_all = module_internal_all else: func_name = name cur_module_file = module_op_file cur_module_all = module_op_all code, _ = op_code_gen_func(hdl, name, func_name, True) cur_module_file.write(os.linesep) cur_module_file.write(code) cur_module_all.append(func_name) for (submodule_f, submodule_all) in submodule_dict.values(): write_all_str(submodule_f, submodule_all) submodule_f.close() write_all_str(module_op_file, module_op_all) module_op_file.close() write_all_str(module_internal_file, module_internal_all) module_internal_file.close()
def make_hdiag_csf(h1e, eri, norb, nelec, transformer, hdiag_det=None): smult = transformer.smult if hdiag_det is None: hdiag_det = make_hdiag_det(None, h1e, eri, norb, nelec) eri = ao2mo.restore(1, eri, norb) tlib = wlib = 0 neleca, nelecb = _unpack_nelec(nelec) min_npair, npair_csd_offset, npair_dconf_size, npair_sconf_size, npair_sdet_size = get_csdaddrs_shape( norb, neleca, nelecb) _, npair_csf_offset, _, _, npair_csf_size = get_csfvec_shape( norb, neleca, nelecb, smult) npair_econf_size = npair_dconf_size * npair_sconf_size max_npair = min(neleca, nelecb) ncsf_all = count_all_csfs(norb, neleca, nelecb, smult) ndeta_all = cistring.num_strings(norb, neleca) ndetb_all = cistring.num_strings(norb, nelecb) ndet_all = ndeta_all * ndetb_all hdiag_csf = np.ascontiguousarray(np.zeros(ncsf_all, dtype=np.float64)) hdiag_csf_check = np.ones(ncsf_all, dtype=np.bool) for npair in range(min_npair, max_npair + 1): ipair = npair - min_npair nconf = npair_econf_size[ipair] ndet = npair_sdet_size[ipair] ncsf = npair_csf_size[ipair] if ncsf == 0: continue nspin = neleca + nelecb - 2 * npair csd_offset = npair_csd_offset[ipair] csf_offset = npair_csf_offset[ipair] hdiag_conf = np.ascontiguousarray( np.zeros((nconf, ndet, ndet), dtype=np.float64)) det_addr = transformer.csd_mask[csd_offset:][:nconf * ndet] if ndet == 1: # Closed-shell singlets assert (ncsf == 1) hdiag_csf[csf_offset:][:nconf] = hdiag_det[det_addr.flat] hdiag_csf_check[csf_offset:][:nconf] = False continue det_addra, det_addrb = divmod(det_addr, ndetb_all) det_stra = np.ascontiguousarray( cistring.addrs2str(norb, neleca, det_addra).reshape(nconf, ndet, order='C')) det_strb = np.ascontiguousarray( cistring.addrs2str(norb, nelecb, det_addrb).reshape(nconf, ndet, order='C')) det_addr = det_addr.reshape(nconf, ndet, order='C') hdiag_conf = np.ascontiguousarray( np.zeros((nconf, ndet, ndet), dtype=np.float64)) hdiag_conf_det = np.ascontiguousarray(hdiag_det[det_addr], dtype=np.float64) t1 = time.clock() w1 = time.time() libcsf.FCICSFhdiag(hdiag_conf.ctypes.data_as(ctypes.c_void_p), hdiag_conf_det.ctypes.data_as(ctypes.c_void_p), eri.ctypes.data_as(ctypes.c_void_p), det_stra.ctypes.data_as(ctypes.c_void_p), det_strb.ctypes.data_as(ctypes.c_void_p), ctypes.c_uint(norb), ctypes.c_uint(nconf), ctypes.c_uint(ndet)) tlib += time.clock() - t1 wlib += time.time() - w1 umat = get_spin_evecs(nspin, neleca, nelecb, smult) hdiag_conf = np.tensordot(hdiag_conf, umat, axes=1) hdiag_conf *= umat[np.newaxis, :, :] hdiag_csf[csf_offset:][:nconf * ncsf] = hdiag_conf.sum(1).ravel(order='C') hdiag_csf_check[csf_offset:][:nconf * ncsf] = False assert (np.count_nonzero(hdiag_csf_check) == 0 ), np.count_nonzero(hdiag_csf_check) #print ("Time in hdiag_csf library: {}, {}".format (tlib, wlib)) return hdiag_csf
def _init_np_op_module(root_module_name, np_module_name, mx_module_name, make_op_func): """ Register numpy operators in namespaces `mxnet.numpy`, `mxnet.ndarray.numpy` and `mxnet.symbol.numpy`. They are used in imperative mode, Gluon APIs w/o hybridization, and Gluon APIs w/ hybridization, respectively. Essentially, operators with the same name registered in three namespaces, respectively share the same functionality in C++ backend. Different namespaces are needed for dispatching operator calls in Gluon's `HybridBlock` by `F`. Parameters ---------- root_module_name : str Top level module name, `mxnet` in the current cases. np_module_name : str Second level module name, `numpy` or `numpy_extension` in the current case. make_op_func : function Function for creating op functions. """ from . import _numpy_op_doc as _np_op_doc if np_module_name == 'numpy': op_name_prefix = _NP_OP_PREFIX submodule_name_list = _NP_OP_SUBMODULE_LIST op_implemented_set = _NP_OP_IMPLEMENTED_SET elif np_module_name == 'numpy_extension': op_name_prefix = _NP_EXT_OP_PREFIX submodule_name_list = _NP_EXT_OP_SUBMODULE_LIST op_implemented_set = _NP_EXT_OP_IMPLEMENTED_SET elif np_module_name == 'numpy._internal': op_name_prefix = _NP_INTERNAL_OP_PREFIX submodule_name_list = [] op_implemented_set = set() else: raise ValueError( 'unsupported np module name {}'.format(np_module_name)) plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist))) op_names = [] for i in range(size.value): name = py_str(plist[i]) if mx_module_name != 'symbol': if name.startswith( op_name_prefix) and name not in op_implemented_set: op_names.append(name) else: if name.startswith(op_name_prefix): op_names.append(name) if mx_module_name is None: # register np/npx ops for imperative programming op_module_name = "%s.%s._op" % (root_module_name, np_module_name ) # e.g. mxnet.numpy._op op_submodule_name = "%s.%s" % (root_module_name, np_module_name ) # e.g. mxnet.numpy.random elif mx_module_name in ('ndarray', 'symbol'): # register numpy internal ops and np/npx ops for use in Gluon # np internal ops are registered in mxnet.ndarray/symbol.numpy._internal # np ops are registered in mxnet.ndarray/symbol.numpy._op # npx ops are registered in mxnet.ndarray/symbol.numpy_extension._op op_module_name = "%s.%s.%s" % (root_module_name, mx_module_name, np_module_name) if op_name_prefix != _NP_INTERNAL_OP_PREFIX: op_module_name += '._op' # e.g. mxnet.symbol.numpy.random op_submodule_name = "%s.%s.%s" % (root_module_name, mx_module_name, np_module_name) else: raise ValueError('unsupported mxnet module {}'.format(mx_module_name)) op_submodule_name += '.%s' op_module = sys.modules[op_module_name] submodule_dict = {} for submodule_name in submodule_name_list: submodule_dict[submodule_name] = sys.modules[op_submodule_name % submodule_name[1:-1]] for name in op_names: hdl = OpHandle() check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl))) submodule_name = _get_op_submodule_name(name, op_name_prefix, submodule_name_list) if len(submodule_name) > 0: func_name = name[(len(op_name_prefix) + len(submodule_name)):] cur_module = submodule_dict[submodule_name] module_name_local = op_submodule_name % submodule_name[1:-1] else: func_name = name[len(op_name_prefix):] cur_module = op_module module_name_local =\ op_module_name[:-len('._op')] if op_module_name.endswith('._op') else op_module_name function = make_op_func(hdl, name, func_name) function.__module__ = module_name_local setattr(cur_module, function.__name__, function) cur_module.__all__.append(function.__name__) if hasattr(_np_op_doc, name): function.__doc__ = getattr(_np_op_doc, name).__doc__ else: function.__doc__ = re.sub('NDArray', 'ndarray', function.__doc__)
def write(self, lp_base_address: int, value: int): write_buffer = ctypes.c_uint(value) lp_buffer = ctypes.byref(write_buffer) n_size = ctypes.sizeof(write_buffer) lp_number_of_bytes_written = ctypes.c_ulong(0) ctypes.windll.kernel32.WriteProcessMemory(self.handle, lp_base_address, lp_buffer, n_size, lp_number_of_bytes_written)
def get_nvml_info(device_id): """ Gets info from NVML for the given device Returns a dict of dicts from different NVML functions """ device = get_device(device_id) if device is None: return None nvml = get_nvml() if nvml is None: return None rc = nvml.nvmlInit() if rc != 0: raise RuntimeError('nvmlInit() failed with error #%s' % rc) try: # get device handle handle = c_nvmlDevice_t() rc = nvml.nvmlDeviceGetHandleByPciBusId( ctypes.c_char_p(device.pciBusID_str), ctypes.byref(handle)) if rc != 0: raise RuntimeError( 'nvmlDeviceGetHandleByPciBusId() failed with error #%s' % rc) # Grab info for this device from NVML info = {'minor_number': device_id, 'product_name': device.name} uuid = ' ' * 41 rc = nvml.nvmlDeviceGetUUID(handle, ctypes.c_char_p(uuid), 41) if rc == 0: info['uuid'] = uuid[:-1] temperature = ctypes.c_int() rc = nvml.nvmlDeviceGetTemperature(handle, 0, ctypes.byref(temperature)) if rc == 0: info['temperature'] = temperature.value speed = ctypes.c_uint() rc = nvml.nvmlDeviceGetFanSpeed(handle, ctypes.byref(speed)) if rc == 0: info['fan'] = speed.value power_draw = ctypes.c_uint() rc = nvml.nvmlDeviceGetPowerUsage(handle, ctypes.byref(power_draw)) if rc == 0: info['power_draw'] = power_draw.value power_limit = ctypes.c_uint() rc = nvml.nvmlDeviceGetPowerManagementLimit(handle, ctypes.byref(power_limit)) if rc == 0: info['power_limit'] = power_limit.value memory = c_nvmlMemory_t() rc = nvml.nvmlDeviceGetMemoryInfo(handle, ctypes.byref(memory)) if rc == 0: info['memory_total'] = memory.total info['memory_used'] = memory.used utilization = c_nvmlUtilization_t() rc = nvml.nvmlDeviceGetUtilizationRates(handle, ctypes.byref(utilization)) if rc == 0: info['gpu_util'] = utilization.gpu return info finally: rc = nvml.nvmlShutdown() if rc != 0: pass
def reshape(self, partial_shaping=False, allow_up_sizing=False, **kwargs): """Return a new executor with the same symbol and shared memory, but different input/output shapes. For runtime reshaping, variable length sequences, etc. The returned executor shares state with the current one, and cannot be used in parallel with it. Parameters ---------- partial_shaping : bool Whether to allow changing the shape of unspecified arguments. allow_up_sizing : bool Whether to allow allocating new ndarrays that's larger than the original. kwargs : dict of string to tuple of int New shape for arguments. Returns ------- exec : Executor A new executor that shares memory with self. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.Variable('b') >>> c = 2 * a + b >>> texec = c.bind(mx.cpu(), {'a': mx.nd.zeros((2, 1)), 'b': mx.nd.ones((2,1))}) >>> new_shape = {'a': (4, 2), 'b': (4, 2)} >>> texec.reshape(allow_up_sizing=True, **new_shape) """ # pylint: disable=too-many-branches provided_arg_shape_data = [] # shape data # argument shape index in sdata, # e.g. [sdata[indptr[0]], sdata[indptr[1]]) is the shape of the first arg provided_arg_shape_idx = [0] provided_arg_shape_names = [] # provided argument names for k, v in kwargs.items(): if isinstance(v, tuple): provided_arg_shape_names.append(k) provided_arg_shape_data.extend(v) provided_arg_shape_idx.append(len(provided_arg_shape_data)) ctx_map_keys = [] ctx_map_dev_types = [] ctx_map_dev_ids = [] if self._group2ctx: for key, val in self._group2ctx.items(): ctx_map_keys.append(key) ctx_map_dev_types.append(val.device_typeid) ctx_map_dev_ids.append(val.device_id) handle = ExecutorHandle() shared_handle = self.handle num_in_args = ctypes.c_uint() in_arg_handles = ctypes.POINTER(NDArrayHandle)() arg_grad_handles = ctypes.POINTER(NDArrayHandle)() num_aux_states = ctypes.c_uint() aux_state_handles = ctypes.POINTER(NDArrayHandle)() check_call( _LIB.MXExecutorReshapeEx( ctypes.c_int(int(partial_shaping)), ctypes.c_int(int(allow_up_sizing)), ctypes.c_int(self._ctx.device_typeid), ctypes.c_int(self._ctx.device_id), mx_uint(len(ctx_map_keys)), c_str_array(ctx_map_keys), c_array_buf(ctypes.c_int, py_array('i', ctx_map_dev_types)), c_array_buf(ctypes.c_int, py_array('i', ctx_map_dev_ids)), mx_uint(len(provided_arg_shape_names)), c_str_array(provided_arg_shape_names), c_array_buf(mx_int, py_array('i', provided_arg_shape_data)), c_array_buf(mx_uint, py_array('I', provided_arg_shape_idx)), ctypes.byref(num_in_args), ctypes.byref(in_arg_handles), ctypes.byref(arg_grad_handles), ctypes.byref(num_aux_states), ctypes.byref(aux_state_handles), shared_handle, ctypes.byref(handle))) arg_arrays = [ _ndarray_cls(NDArrayHandle(in_arg_handles[i])) for i in range(num_in_args.value) ] grad_arrays = [ _ndarray_cls(NDArrayHandle(arg_grad_handles[i])) if arg_grad_handles[i] is not None else None for i in range(num_in_args.value) ] aux_arrays = [ _ndarray_cls(NDArrayHandle(aux_state_handles[i])) for i in range(num_aux_states.value) ] executor = Executor(handle, self._symbol, self._ctx, self._grad_req, self._group2ctx) executor.arg_arrays = arg_arrays executor.grad_arrays = grad_arrays executor.aux_arrays = aux_arrays return executor
def castfloat(value): return ctypes.c_float.from_buffer(ctypes.c_uint(int(value, base=2))).value
def integrator_whfast_safe_mode(self, value): self.ri_whfast.safe_mode = c_uint(value)
def rand(): srand.r[srand.k] = srand.r[(srand.k - 31) % 34] + srand.r[(srand.k - 3) % 34] r = c_uint(srand.r[srand.k]).value >> 1 srand.k = (srand.k + 1) % 34 return r
def read(hDev, max_len=256): buf = ctypes.create_string_buffer(max_len) pRead = ctypes.c_uint(0) rc = ausb_read64(hDev, buf, max_len, pRead) return (rc, buf[:pRead.value])
def integrator_whfast_recalculate_jacobi_this_timestep(self, value): self.ri_whfast.recalculate_jacobi_this_timestep = c_uint(value)
def flags(self): flags = ctypes.c_uint() self.call('GetFlags', self.device_idx, ctypes.byref(flags)) return flags.value
def integrator_whfast_corrector(self, value): self.ri_whfast.corrector = c_uint(value)
import ctypes from ctypes.wintypes import * import os from argparse import * os.chdir('C:\\Program Files (x86)\\Qualcomm\\QDART\\bin') lib = ctypes.CDLL('QMSL_MSVC10R') #iWait_ms = ctypes.c_ulong(25) iComPort = ctypes.c_uint(4) #to double check that connection with com_port_auto returns the same result (handle) as the one with a known port com_port_auto=ctypes.c_int(0xFFFF) handle = lib.QLIB_ConnectServer(iComPort) gResourceContext = HANDLE(handle) channel = ctypes.c_int(5500) phyID = ctypes.c_int(0) #opcode = _OP_TX = 1 opCode = ctypes.create_string_buffer(b"1") lib.QLIB_FTM_WLAN_TLV2_Create(gResourceContext, opCode) lib.QLIB_FTM_WLAN_TLV2_AddParam(gResourceContext, ctypes.byref(ctypes.create_string_buffer(b"channel")), ctypes.byref(ctypes.create_string_buffer(b"5500"))) lib.QLIB_FTM_WLAN_TLV2_AddParam(gResourceContext, ctypes.byref(ctypes.create_string_buffer(b"txMode")), ctypes.byref(ctypes.create_string_buffer(b"0"))) lib.QLIB_FTM_WLAN_TLV2_AddParam(gResourceContext, ctypes.byref(ctypes.create_string_buffer(b"phyId")), ctypes.byref(ctypes.create_string_buffer(b"0"))) lib.QLIB_FTM_WLAN_TLV2_Complete(gResourceContext)
def open(MYID): hDev = ctypes.c_uint(0) rc = ausb_open(hDev, MYID) return (rc, hDev)
def cuda_detect(): '''Attempt to detect the version of CUDA present in the operating system. On Windows and Linux, the CUDA library is installed by the NVIDIA driver package, and is typically found in the standard library path, rather than with the CUDA SDK (which is optional for running CUDA apps). On macOS, the CUDA library is only installed with the CUDA SDK, and might not be in the library path. Returns: version string (Ex: '9.2') or None if CUDA not found. ''' # platform specific libcuda location import platform system = platform.system() if system == 'Darwin': lib_filenames = [ 'libcuda.dylib', # check library path first '/usr/local/cuda/lib/libcuda.dylib' ] elif system == 'Linux': lib_filenames = [ 'libcuda.so', # check library path first '/usr/lib64/nvidia/libcuda.so', # Redhat/CentOS/Fedora '/usr/lib/x86_64-linux-gnu/libcuda.so', # Ubuntu ] elif system == 'Windows': lib_filenames = ['nvcuda.dll'] else: return None # CUDA not available for other operating systems # open library import ctypes if system == 'Windows': dll = ctypes.windll else: dll = ctypes.cdll libcuda = None for lib_filename in lib_filenames: try: libcuda = dll.LoadLibrary(lib_filename) break except: pass if libcuda is None: return None # Get CUDA version try: cuInit = libcuda.cuInit flags = ctypes.c_uint(0) ret = cuInit(flags) if ret != 0: return None cuDriverGetVersion = libcuda.cuDriverGetVersion version_int = ctypes.c_int(0) ret = cuDriverGetVersion(ctypes.byref(version_int)) if ret != 0: return None # Convert version integer to version string value = version_int.value return '%d.%d' % (value // 1000, (value % 1000) // 10) except: return None
def enable(self, yes=True): v = ctypes.c_uint(1) if yes else ctypes.c_uint(0) self.lt.toaster_setActivate(v)
#QPST is the library mode = true libMode = ctypes.c_uint8(1) #libMode = ctypes.c_wchar_p('true') #libMode = ctypes.create_string_buffer(b"true") #libMode = ctypes.create_string_buffer(b"TRUE") lib.QLIB_SetLibraryMode(libMode) libMode.value #APQ = 1 targetType = ctypes.c_uint8(1) #targetType = ctypes.create_string_buffer(b"1") lib.QLIB_SetTargetType(targetType) iWait_ms = ctypes.c_ulong(5000) iComPort = ctypes.c_uint(4) #to double check that connection with com_port_auto returns the same result (handle) as the one with a known port com_port_auto = ctypes.c_int(0xFFFF) # handle = lib.QLIB_ConnectServer(iComPort) handle = lib.QLIB_ConnectServerWithWait(iComPort, iWait_ms) gResourceContext = HANDLE(handle) time.sleep(3) print('wait for connection 5s') ################################################################################################# #Set the WLAN module type if not called assumes a wrong module eModuletype = ctypes.c_uint32(1) lib.QLIB_FTM_WLAN_SetModuleType(gResourceContext, eModuletype) #try creating string_buffer and pass byref
header_status[ind] = 0 # Generate triggers if software trig is used if (trig_type == 1): for trig in range( number_of_records * 2 ): #twice as needed to handle that ADQ14OCT currently misses some software triggers ADQAPI.ADQ_SWTrig(adq_cu, adq_num) print('Waiting for data...') # Collect data until all requested records have been recieved records_completed = [0, 0, 0, 0] headers_completed = [0, 0, 0, 0] records_completed_cnt = 0 ltime = time.time() buffers_filled = ct.c_uint(0) # Read out data until records_completed for ch A is number_of_records while (number_of_records > records_completed[0]): buffers_filled.value = 0 collect_result = 1 poll_time_diff_prev = time.time() # Wait for next data buffer while ((buffers_filled.value == 0) and (collect_result)): collect_result = ADQAPI.ADQ_GetTransferBufferStatus( adq_cu, adq_num, ct.byref(buffers_filled)) poll_time_diff = time.time() if ((poll_time_diff - poll_time_diff_prev) > flush_timeout): # Force flush print('No data for {}s, flushing the DMA buffer.'.format(
def instances(self): num_instances = ct.c_uint() result = libcoreir_c.COREDirectedModuleGetInstances(self.ptr, ct.byref(num_instances)) return [DirectedInstance(result[i], self.context) for i in range(num_instances.value)]
def fetch_operands(self, reader): self.index = ctypes.c_uint(reader.read_uint8()).value self.const = ctypes.c_int32(reader.read_int8()).value
def make_glMultiDrawArrays(glDrawArrays): ''' //MSVC: /O1 /Wall /wd4668 /wd4711 /wd4127 /EHsc /link /DefaultLib:OpenGL32.lib /Machine:I386 /Entry:main //Compiler: 0 // "%VS90COMNTOOLS%..\..\VC\bin\amd64\dumpbin" /disasm:bytes "Temp.exe" // I386: "U\x8b\xecS\x8b]\x18\x85\xdbt\x1dV\x8bu\x10W\x8b}\x14\xff7\xff6\xffu\x0c\xffU\x08\x83\xc6\x04\x83\xc7\x04Ku\xed_^[]\xc3" // AMD64: "HSUVWATH\x83\xec \x8bt$pI\x8b\xd9I\x8b\xf8\x85\xf6\x8b\xeaL\x8b\xe1t\x16D\x8b\x03\x8b\x17\x8b\xcdA\xff\xd4H\x83\xc7\x04H\x83\xc3\x04\xff\xceu\xeaH\x83\xc4 A\\_^][\xc3" #include <Windows.h> #include <GL/gl.h> __declspec(dllexport) void __cdecl glMultiDrawArrays(void __stdcall glDrawArrays(GLenum mode, GLint first, GLsizei count), GLenum mode, GLint *first, GLsizei *count, GLsizei primcount) { while (primcount) { glDrawArrays(mode, *first, *count); ++first; ++count; --primcount; } } int main() { glMultiDrawArrays(glDrawArrays, 0, 0, 0, 0); return 0; } ''' code32 = b"U\x8b\xecS\x8b]\x18\x85\xdbt\x1dV\x8bu\x10W\x8b}\x14\xff7\xff6\xffu\x0c\xffU\x08\x83\xc6\x04\x83\xc7\x04Ku\xed_^[]\xc3" code64 = b"HSUVWATH\x83\xec \x8bt$pI\x8b\xd9I\x8b\xf8\x85\xf6\x8b\xeaL\x8b\xe1t\x16D\x8b\x03\x8b\x17\x8b\xcdA\xff\xd4H\x83\xc7\x04H\x83\xc3\x04\xff\xceu\xeaH\x83\xc4 A\\_^][\xc3" code = code32 if ctypes.sizeof(ctypes.c_void_p) <= ctypes.sizeof( ctypes.c_int) else code64 glMultiDrawArrays_t = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint) bincode = ctypes.create_string_buffer(code) def callback(mode, first, count, primcount): first_p = ctypes.cast(first, ctypes.POINTER(ctypes.c_int)) count_p = ctypes.cast(count, ctypes.POINTER(ctypes.c_uint)) for i in range(primcount): glDrawArrays(mode, first_p[i], count_p[i]) success = False if not success: try: old = ctypes.c_uint() success = ctypes.windll.kernel32.VirtualProtect( bincode, ctypes.c_uint(len(bincode)), 0x40, ctypes.byref(old)) != 0 except AttributeError: pass if not success: try: success = ctypes.pythonapi.mprotect(bincode, len(buffer), 0x1 | 0x2 | 0x4) == 0 except AttributeError: pass if success: def callback(mode, first, count, primcount, glMultiDrawArrays=glMultiDrawArrays_t( ctypes.addressof(bincode)), _keep_alive=bincode): return glMultiDrawArrays(glDrawArrays, mode, first, count, primcount) return callback
def unset_caps_lock(): display = X11.XOpenDisplay(None) X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)) X11.XCloseDisplay(display)