libusb low level
16917
private static String printInfo(final Device device)
	{
		final int bus = LibUsb.getBusNumber(device);
		final int address = LibUsb.getDeviceAddress(device);
		int vendor = 0;
		int product = 0;

		final DeviceDescriptor d = new DeviceDescriptor();
		int err = LibUsb.getDeviceDescriptor(device, d);
		if (err == 0) {
			vendor = d.idVendor() & 0xffff;
			product = d.idProduct() & 0xffff;
		}

		final StringBuilder sb = new StringBuilder();
		final String item = vendor != 0 ? toDeviceId(vendor, product) : "";
		sb.append("Bus ").append(bus).append(" Device ").append(address).append(": ID ").append(item);

		final String ind = "    ";
		final DeviceHandle dh = new DeviceHandle();
		err = LibUsb.open(device, dh);
		if (err == 0) {
			try {
				final String man = LibUsb.getStringDescriptor(dh, d.iManufacturer());
				final String prodname = LibUsb.getStringDescriptor(dh, d.iProduct());
				String desc = ind;
				if (prodname != null)
					desc += prodname;
				if (man != null)
					desc += " (" + man + ")";
				if (!desc.equals(ind))
					sb.append("\n").append(desc);
			}
			finally {
				LibUsb.close(dh);
			}
		}

		String attach = "";
		final Device parent = LibUsb.getParent(device);
		if (parent != null) {
			// ??? not necessary in my understanding of the USB tree structure, the bus
			// has to be the same as the child one's
			final int parentBus = LibUsb.getBusNumber(parent);
			final int parentAddress = LibUsb.getDeviceAddress(parent);
			attach = "Parent Hub " + parentBus + ":" + parentAddress;
		}
		final int port = LibUsb.getPortNumber(device);
		if (port != 0)
			attach += (attach.isEmpty() ? "Attached at port " : ", attached at port ") + port;

		// try to show the full path of port numbers from root for this device
		final ByteBuffer path = ByteBuffer.allocateDirect(8);
        final int result = LibUsb.getPortNumbers(device, path);
		if (result > 0)
			attach += IntStream.range(0, result).map(path::get).mapToObj(Integer::toString)
					.collect(Collectors.joining("/", " (/bus:" + LibUsb.getBusNumber(device) + "/", ")"));

		if (!attach.isEmpty())
			sb.append("\n").append(ind).append(attach);

		final int speed = LibUsb.getDeviceSpeed(device);
		if (speed != LibUsb.SPEED_UNKNOWN)
			sb.append("\n").append(ind).append(DescriptorUtils.getSpeedName(speed)).append(" Speed USB");
		return sb.toString();
	}
21775
def scan():
    

    # Initiate the low level drivers
    cflib.crtp.init_drivers(enable_debug_driver=False)

    # Scan for Crazyflies
    print('Scanning interfaces for Crazyflies...')
    available = cflib.crtp.scan_interfaces()
    interfaces = [uri for uri, _ in available]

    if not interfaces:
        return None
    return choose(interfaces, 'Crazyflies found:', 'Select interface: ')
1255962
def _loadlib(lib='standard'):
    """"""
    global _LIB
    if _LIB is not None:
        warnings.warn('rabit.int call was ignored because it has'\
                          ' already been initialized', level=2)
        return
    if lib == 'standard':
        _LIB = ctypes.cdll.LoadLibrary(WRAPPER_PATH % '')
    elif lib == 'mock':
        _LIB = ctypes.cdll.LoadLibrary(WRAPPER_PATH % '_mock')
    elif lib == 'mpi':
        _LIB = ctypes.cdll.LoadLibrary(WRAPPER_PATH % '_mpi')
    else:
        raise Exception('unknown rabit lib %s, can be standard, mock, mpi' % lib)
    _LIB.RabitGetRank.restype = ctypes.c_int
    _LIB.RabitGetWorldSize.restype = ctypes.c_int
    _LIB.RabitVersionNumber.restype = ctypes.c_int
285730
def lsb_release(self,
	                loglevel=logging.DEBUG):
		
		#          v the space is intentional, to avoid polluting bash history.
		shutit = self.shutit
		d = {}
		self.send(ShutItSendSpec(self,
		                         send=' command lsb_release -a',
		                         check_exit=False,
		                         echo=False,
		                         loglevel=loglevel,
		                         ignore_background=True))
		res = shutit.match_string(self.pexpect_child.before, r'^Distributor[\s]*ID:[\s]*(.*)$')
		if isinstance(res, str):
			dist_string = res
			d['distro']       = dist_string.lower().strip()
			try:
				d['install_type'] = (package_map.INSTALL_TYPE_MAP[dist_string.lower()])
			except KeyError:
				raise Exception("Distribution '%s' is not supported." % dist_string)
		else:
			return d
		res = shutit.match_string(self.pexpect_child.before, r'^Release:[\s*](.*)$')
		if isinstance(res, str):
			version_string = res
			d['distro_version'] = version_string
		return d
966088
def d2Sbus_dV2(Ybus, V, lam):
    
    n = len(V)
    Ibus = Ybus * V
    diaglam = spdiag(lam)
    diagV = spdiag(V)

    A = spmatrix(mul(lam, V), range(n), range(n))
    B = Ybus * diagV
    C = A * conj(B)
    D = Ybus.H * diagV
    E = conj(diagV) * (D * diaglam - spmatrix(D*lam, range(n), range(n)))
    F = C - A * spmatrix(conj(Ibus), range(n), range(n))
    G = spmatrix(div(matrix(1.0, (n, 1)), abs(V)), range(n), range(n))

    Gaa = E + F
    Gva = 1j * G * (E - F)
    Gav = Gva.T
    Gvv = G * (C + C.T) * G

    return Gaa, Gav, Gva, Gvv
637005
def _lib(self, name, only_if_have=False):
        
        emit = True
        if only_if_have:
            emit = self.env.get('HAVE_LIB' + self.env_key(name))
        if emit:
            return '-l' + name
        return ''
11946
def _load_lib():
    """"""
    lib_path = _find_lib_path()
    lib = ctypes.cdll.LoadLibrary(lib_path[0])
    # DMatrix functions
    lib.MXGetLastError.restype = ctypes.c_char_p
    return lib
336378
def _load_lib():
    """"""
    lib_path = find_lib_path()
    if len(lib_path) == 0:
        return None
    lib = ctypes.cdll.LoadLibrary(lib_path[0])
    lib.LGBM_GetLastError.restype = ctypes.c_char_p
    return lib
921853
def set_option(option, *args)
      if Call.respond_to?(:libusb_set_option)
        # Available since libusb-1.0.22

        ffi_args = case option
          when :OPTION_LOG_LEVEL, LIBUSB::OPTION_LOG_LEVEL
            expect_option_args(1, args.length)
            [:libusb_log_level, args[0]]
          when :OPTION_USE_USBDK, LIBUSB::OPTION_USE_USBDK
            expect_option_args(0, args.length)
            []
          else
            raise ArgumentError, "unknown option #{option.inspect}"
        end

        res = Call.libusb_set_option(@ctx, option, *ffi_args)
        LIBUSB.raise_error res, "in libusb_set_option" if res<0

      else
        # Fallback to deprecated function, if the gem is linked to an older libusb.

        raise ArgumentError, "unknown option #{option.inspect}" unless [:OPTION_LOG_LEVEL, LIBUSB::OPTION_LOG_LEVEL].include?(option)
        Call.libusb_set_debug(@ctx, *args)
      end
    end
398866
def readin():
    """"""

    selection = sys.stdin.readline().strip("\n")
    MyBulbs.bulbs.sort(key=lambda x: x.label or x.mac_addr)
    lov=[ x for x in selection.split(" ") if x != ""]
    if lov:
        if MyBulbs.boi:
            #try:
            if True:
                if int(lov[0]) == 0:
                    MyBulbs.boi=None
                elif int(lov[0]) == 1:
                    if len(lov) >1:
                        MyBulbs.boi.set_power(lov[1].lower() in ["1","on","true"]) 
                        MyBulbs.boi=None
                    else:
                        print("Error: For power you must indicate on or off\n")
                elif int(lov[0]) == 2:
                    if len(lov) >2:
                        try:
                            MyBulbs.boi.set_color([58275,0, 
                                    int(round((float(lov[1])*65365.0)/100.0)),
                                    int(round(float(lov[2])))])
                            
                            MyBulbs.boi=None
                        except:
                            print("Error: For white brightness (0-100) and temperature (2500-9000) must be numbers.\n")
                    else:
                        print("Error: For white you must indicate brightness (0-100) and temperature (2500-9000)\n")
                elif int(lov[0]) == 3:
                    if len(lov) >3:
                        try:
                            MyBulbs.boi.set_color([int(round((float(lov[1])*65535.0)/360.0)),
                                    int(round((float(lov[2])*65535.0)/100.0)),
                                    int(round((float(lov[3])*65535.0)/100.0)),3500])
                            MyBulbs.boi=None
                        except:
                            print("Error: For colour hue (0-360), saturation (0-100) and brightness (0-100)) must be numbers.\n")
                    else:
                        print("Error: For colour you must indicate hue (0-360), saturation (0-100) and brightness (0-100))\n")
                        
                elif int(lov[0]) == 4: 
                    print(MyBulbs.boi.device_characteristics_str("    "))
                    print(MyBulbs.boi.device_product_str("    "))
                    MyBulbs.boi=None
                elif int(lov[0]) == 5: 
                    print(MyBulbs.boi.device_firmware_str("   "))
                    MyBulbs.boi=None
                elif int(lov[0]) == 6: 
                    mypartial=partial(MyBulbs.boi.device_radio_str)
                    MyBulbs.boi.get_wifiinfo(callb=lambda x,y:print("\n"+mypartial(y)))
                    MyBulbs.boi=None
                elif int(lov[0]) == 7: 
                    mypartial=partial(MyBulbs.boi.device_time_str)
                    MyBulbs.boi.get_hostinfo(callb=lambda x,y:print("\n"+mypartial(y)))
                    MyBulbs.boi=None
                elif int(lov[0]) == 8: 
                    if len(lov) >3:
                        try:
                            print ( "Sending {}".format([int(round((float(lov[1])*65535.0)/360.0)),
                                    int(round((float(lov[2])*65535.0)/100.0)),
                                    int(round((float(lov[3])*65535.0)/100.0)),3500]))
                            MyBulbs.boi.set_waveform({"color":[int(round((float(lov[1])*65535.0)/360.0)),
                                                               int(round((float(lov[2])*65535.0)/100.0)),
                                                               int(round((float(lov[3])*65535.0)/100.0)),
                                                               3500],
                                                      "transient":1, "period":100, "cycles":30,
                                                      "skew_ratio":0,"waveform":0})
                            MyBulbs.boi=None
                        except:
                            print("Error: For pulse hue (0-360), saturation (0-100) and brightness (0-100)) must be numbers.\n")
                    else:
                        print("Error: For pulse you must indicate hue (0-360), saturation (0-100) and brightness (0-100))\n")
            #except:
                #print ("\nError: Selection must be a number.\n")  
        else:
            try:
                if int(lov[0]) > 0:
                    if int(lov[0]) <=len(MyBulbs.bulbs):
                        MyBulbs.boi=MyBulbs.bulbs[int(lov[0])-1]
                    else:
                        print("\nError: Not a valid selection.\n")
            
            except:
                print ("\nError: Selection must be a number.\n")
        
    if MyBulbs.boi:
        print("Select Function for {}:".format(MyBulbs.boi.label))
        print("\t[1]\tPower (0 or 1)")
        print("\t[2]\tWhite (Brigthness Temperature)")
        print("\t[3]\tColour (Hue Saturation Brightness)")
        print("\t[4]\tInfo")
        print("\t[5]\tFirmware")
        print("\t[6]\tWifi")
        print("\t[7]\tUptime")
        print("\t[8]\tPulse")
        print("")
        print("\t[0]\tBack to bulb selection")
    else:
        idx=1
        print("Select Bulb:")
        for x in MyBulbs.bulbs:
            print("\t[{}]\t{}".format(idx,x.label or x.mac_addr))
            idx+=1
    print("")
    print("Your choice: ", end='',flush=True)
980961
def _load_lib():
    """"""
    lib_paths = find_lib_path()
    if not lib_paths:
        return None
    try:
        pathBackup = os.environ['PATH'].split(os.pathsep)
    except KeyError:
        pathBackup = []
    lib_success = False
    os_error_list = []
    for lib_path in lib_paths:
        try:
            # needed when the lib is linked with non-system-available dependencies
            os.environ['PATH'] = os.pathsep.join(pathBackup + [os.path.dirname(lib_path)])
            lib = ctypes.cdll.LoadLibrary(lib_path)
            lib_success = True
        except OSError as e:
            os_error_list.append(str(e))
            continue
        finally:
            os.environ['PATH'] = os.pathsep.join(pathBackup)
    if not lib_success:
        libname = os.path.basename(lib_paths[0])
        raise XGBoostError(
            'XGBoost Library ({}) could not be loaded.\n'.format(libname) +
            'Likely causes:\n' +
            '  * OpenMP runtime is not installed ' +
            '(vcomp140.dll or libgomp-1.dll for Windows, ' +
            'libgomp.so for UNIX-like OSes)\n' +
            '  * You are running 32-bit Python on a 64-bit OS\n' +
            'Error message(s): {}\n'.format(os_error_list))
    lib.XGBGetLastError.restype = ctypes.c_char_p
    lib.callback = _get_log_callback_func()
    if lib.XGBRegisterLogCallback(lib.callback) != 0:
        raise XGBoostError(lib.XGBGetLastError())
    return lib
640112
def libs_for_binary(a_binary, visited=[])
    return [] if visited.include?(a_binary)
    visited << a_binary
    pre = Rake::Task[a_binary].prerequisites
    rv = []
    pre.each do |p|

      next if (File.extname(p) != '.a') && (File.extname(p) != '.so')
      next if p =~ /\-app\.a/

      rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '')
      rv += libs_for_binary(p, visited)   # Recursive call
    end

    reduce_libs_to_bare_minimum(rv.uniq)
  end
132908
def setup_external_libs(libs):
    
    PYPI_URL_PREFIX = "https://pypi.python.org/packages/source"
    SPARK_EC2_LIB_DIR = os.path.join(SPARK_EC2_DIR, "lib")

    if not os.path.exists(SPARK_EC2_LIB_DIR):
        print("Downloading external libraries that spark-ec2 needs from PyPI to {path}...".format(
            path=SPARK_EC2_LIB_DIR
        ))
        print("This should be a one-time operation.")
        os.mkdir(SPARK_EC2_LIB_DIR)

    for lib in libs:
        versioned_lib_name = "{n}-{v}".format(n=lib["name"], v=lib["version"])
        lib_dir = os.path.join(SPARK_EC2_LIB_DIR, versioned_lib_name)

        if not os.path.isdir(lib_dir):
            tgz_file_path = os.path.join(SPARK_EC2_LIB_DIR, versioned_lib_name + ".tar.gz")
            print(" - Downloading {lib}...".format(lib=lib["name"]))
            download_stream = urlopen(
                "{prefix}/{first_letter}/{lib_name}/{lib_name}-{lib_version}.tar.gz".format(
                    prefix=PYPI_URL_PREFIX,
                    first_letter=lib["name"][:1],
                    lib_name=lib["name"],
                    lib_version=lib["version"]
                )
            )
            with open(tgz_file_path, "wb") as tgz_file:
                tgz_file.write(download_stream.read())
            with open(tgz_file_path, "rb") as tar:
                if hashlib.md5(tar.read()).hexdigest() != lib["md5"]:
                    print("ERROR: Got wrong md5sum for {lib}.".format(lib=lib["name"]), file=stderr)
                    sys.exit(1)
            tar = tarfile.open(tgz_file_path)
            tar.extractall(path=SPARK_EC2_LIB_DIR)
            tar.close()
            os.remove(tgz_file_path)
            print(" - Finished downloading {lib}.".format(lib=lib["name"]))
        sys.path.insert(1, lib_dir)
301784
def load_library(self,libname):
        """"""
        paths = self.getpaths(libname)

        for path in paths:
            if os.path.exists(path):
                return self.load(path)

        raise ImportError("%s not found." % libname)
656540
def EmitLibSymlinks(env, symlinks, libnode, **kw):
    """"""
    Verbose = False

    # nodes involved in process... all symlinks + library
    nodes = list(set([ x for x,y in symlinks ] + [libnode]))

    clean_targets = kw.get('clean_targets', [])
    if not SCons.Util.is_List(clean_targets):
        clean_targets = [ clean_targets ]

    for link, linktgt in symlinks:
        env.SideEffect(link, linktgt)
        if(Verbose):
            print("EmitLibSymlinks: SideEffect(%r,%r)" % (link.get_path(), linktgt.get_path()))
        clean_list = [x for x in nodes if x != linktgt]
        env.Clean(list(set([linktgt] + clean_targets)), clean_list)
        if(Verbose):
            print("EmitLibSymlinks: Clean(%r,%r)" % (linktgt.get_path(), [x.get_path() for x in clean_list]))
1369545
def find_lib_fpath(libname, root_dir, recurse_down=True, verbose=False, debug=False):
    

    def get_lib_fname_list(libname):
        """
        input <libname>: library name (e.g. 'hesaff', not 'libhesaff')
        returns <libnames>: list of plausible library file names
        """
        if sys.platform.startswith('win32'):
            libnames = ['lib' + libname + '.dll', libname + '.dll']
        elif sys.platform.startswith('darwin'):
            libnames = ['lib' + libname + '.dylib']
        elif sys.platform.startswith('linux'):
            libnames = ['lib' + libname + '.so']
        else:
            raise Exception('Unknown operating system: %s' % sys.platform)
        return libnames

    def get_lib_dpath_list(root_dir):
        """
        input <root_dir>: deepest directory to look for a library (dll, so, dylib)
        returns <libnames>: list of plausible directories to look.
        """
        'returns possible lib locations'
        get_lib_dpath_list = [root_dir,
                              join(root_dir, 'lib'),
                              join(root_dir, 'build'),
                              join(root_dir, 'build', 'lib')]
        return get_lib_dpath_list

    lib_fname_list = get_lib_fname_list(libname)
    tried_fpaths = []
    while root_dir is not None:
        for lib_fname in lib_fname_list:
            for lib_dpath in get_lib_dpath_list(root_dir):
                lib_fpath = normpath(join(lib_dpath, lib_fname))
                if exists(lib_fpath):
                    if verbose:
                        print('\n[c] Checked: '.join(tried_fpaths))
                    if debug:
                        print('using: %r' % lib_fpath)
                    return lib_fpath
                else:
                    # Remember which candiate library fpaths did not exist
                    tried_fpaths.append(lib_fpath)
            _new_root = dirname(root_dir)
            if _new_root == root_dir:
                root_dir = None
                break
            else:
                root_dir = _new_root
        if not recurse_down:
            break

    msg = ('\n[C!] load_clib(libname=%r root_dir=%r, recurse_down=%r, verbose=%r)' %
           (libname, root_dir, recurse_down, verbose) +
           '\n[c!] Cannot FIND dynamic library')
    print(msg)
    print('\n[c!] Checked: '.join(tried_fpaths))
    raise ImportError(msg)
278236
def build_library(tile, libname, chip):
    """"""

    dirs = chip.build_dirs()

    output_name = '%s_%s.a' % (libname, chip.arch_name())

    # Support both firmware/src and just src locations for source code
    if os.path.exists('firmware'):
        VariantDir(dirs['build'], os.path.join('firmware', 'src'), duplicate=0)
    else:
        VariantDir(dirs['build'], 'src', duplicate=0)

    library_env = setup_environment(chip)
    library_env['OUTPUT'] = output_name
    library_env['OUTPUT_PATH'] = os.path.join(dirs['build'], output_name)
    library_env['BUILD_DIR'] = dirs['build']

    # Check for any dependencies this library has
    tilebus_defs = setup_dependencies(tile, library_env)

    # Create header files for all tilebus config variables and commands that are defined in ourselves
    # or in our dependencies
    tilebus_defs += tile.find_products('tilebus_definitions')
    compile_tilebus(tilebus_defs, library_env, header_only=True)

    SConscript(os.path.join(dirs['build'], 'SConscript'), exports='library_env')

    library_env.InstallAs(os.path.join(dirs['output'], output_name), os.path.join(dirs['build'], output_name))

    # See if we should copy any files over to the output:
    for src, dst in chip.property('copy_files', []):
        srcpath = os.path.join(*src)
        destpath = os.path.join(dirs['output'], dst)
        library_env.InstallAs(destpath, srcpath)

    return os.path.join(dirs['output'], output_name)