Read openvswitch certificate from disk
335544
def get_certificate():
    '''  '''
    if os.path.exists(CERT_PATH):
        log('Reading ovs certificate from {}'.format(CERT_PATH))
        with open(CERT_PATH, 'r') as cert:
            full_cert = cert.read()
            begin_marker = "-----BEGIN CERTIFICATE-----"
            end_marker = "-----END CERTIFICATE-----"
            begin_index = full_cert.find(begin_marker)
            end_index = full_cert.rfind(end_marker)
            if end_index == -1 or begin_index == -1:
                raise RuntimeError("Certificate does not contain valid begin"
                                   " and end markers.")
            full_cert = full_cert[begin_index:(end_index + len(end_marker))]
            return full_cert
    else:
        log('Certificate not found', level=WARNING)
        return None
516391
function findWindowsPortRange() {
  var deferredRange = promise.defer();
  // First, check if we're running on XP.  If this initial command fails,
  // we just fallback on the default IANA range.
  return execute('cmd.exe /c ver').then(function(stdout) {
    if (/Windows XP/.test(stdout)) {
      // TODO: Try to read these values from the registry.
      return {min: 1025, max: 5000};
    } else {
      return execute('netsh int ipv4 show dynamicport tcp').
          then(function(stdout) {
            /* > netsh int ipv4 show dynamicport tcp
              Protocol tcp Dynamic Port Range
              ---------------------------------
              Start Port : 49152
              Number of Ports : 16384
             */
            var range = stdout.split(/\n/).filter(function(line) {
              return /.*:\s*\d+/.test(line);
            }).map(function(line) {
              return Number(line.split(/:\s*/)[1]);
            });

            return {
              min: range[0],
              max: range[0] + range[1]
            };
          });
    }
  });
}
696641
def find_vc_pdir(msvc_version):
    """"""
    root = 'Software\\'
    try:
        hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
    except KeyError:
        debug("Unknown version of MSVC: %s" % msvc_version)
        raise UnsupportedVersion("Unknown version %s" % msvc_version)

    for hkroot, key in hkeys:
        try:
            comps = None
            if not key:
                comps = find_vc_pdir_vswhere(msvc_version)
                if not comps:
                    debug('find_vc_dir(): no VC found via vswhere for version {}'.format(repr(key)))
                    raise SCons.Util.WinError
            else:
                if common.is_win64():
                    try:
                        # ordinally at win64, try Wow6432Node first.
                        comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot)
                    except SCons.Util.WinError as e:
                        # at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node
                        pass
                if not comps:
                    # not Win64, or Microsoft Visual Studio for Python 2.7
                    comps = common.read_reg(root + key, hkroot)
        except SCons.Util.WinError as e:
            debug('find_vc_dir(): no VC registry key {}'.format(repr(key)))
        else:
            debug('find_vc_dir(): found VC in registry: {}'.format(comps))
            if os.path.exists(comps):
                return comps
            else:
                debug('find_vc_dir(): reg says dir is {}, but it does not exist. (ignoring)'.format(comps))
                raise MissingConfiguration("registry dir {} not found on the filesystem".format(comps))
    return None
273340
def get_bond(iface):
    '''
    
    '''
    path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
    return _read_file(path)
1269561
def read_file(filename):
    
    sanitized_filename = sanitize(filename)

    f = open(sanitized_filename)

    specs = None

    try:
        specs = _parse_tsplib(f)
    except ParseException:
        raise
    finally: # 'finally' is executed even when we re-raise exceptions
        f.close()

    if specs['TYPE'] != 'CVRP':
        raise Exception('Not a CVRP TSPLIB problem. Found: {}'.format(specs['TYPE']))
    
    #additional params for graph/network (temporary)
    specs['VOLTAGE'] = 20000
    specs['CABLETYPE'] = 1

    #return (Graph(specs), specs)
    return Graph(specs)
211008
def get_certificate(self, filename):
        
        pkcs7message = self.get_file(filename)

        message, _ = decode(pkcs7message)
        cert = encode(message[1][3])
        # Remove the first identifier·
        # byte 0 == identifier, skip
        # byte 1 == length. If byte1 & 0x80 > 1, we have long format
        #                   The length of to read bytes is then coded
        #                   in byte1 & 0x7F
        cert = cert[2 + (cert[1] & 0x7F) if cert[1] & 0x80 > 1 else 2:]

        certificate = x509.load_der_x509_certificate(cert, default_backend())

        return certificate
55183
def get_diskinfo(opts, show_all=False, debug=False, local_only=False):
    ''' 
    '''
    outunit = opts.outunit
    disks = []
    try:
        label_map = get_label_map(opts)
        lines = run(diskcmd).splitlines()[1:]   # dump header
        for line in lines:
            tokens  = line.split()
            mntp = b' '.join(tokens[8:])
            dev = basename(tokens[0])
            disk = DiskInfo()
            if (dev in devfilter) or (mntp in mntfilter):
                if show_all:
                    if dev == b'map':           # fix alignment :-/
                        dev = tokens[0] = b'%b %b' % (dev, tokens[1])
                        del tokens[1]
                    disk.isram = True
                else:
                    continue

            # convert to bytes as integer, then output units
            disk.dev    = dev = dev.decode('ascii')
            disk.ocap   = float(tokens[1]) * 1024
            disk.cap    = disk.ocap / outunit
            disk.free   = float(tokens[3]) * 1024 / outunit
            disk.pcnt   = int(tokens[4][:-1])
            disk.used   = float(tokens[2]) * 1024 / outunit

            disk.mntp   = mntp.decode('utf8')
            disk.label  = label_map.get(disk.mntp)
            disk.ismntd = bool(disk.mntp)
            disk.isnet  = ':' in dev  # cheesy but may work? (macos)
            if local_only and disk.isnet:
                continue
            if disk.ismntd:
                if disk.mntp == '/':
                    disk.rw = True
                else:
                    disk.rw = os.access(disk.mntp, os.W_OK)

            # ~ disk.isopt  = None  # TODO: not sure how to get these
            # ~ disk.isrem  = None
            disks.append(disk)
    except IOError as err:
        print(err)
        return None

    if opts.debug:
        print()
        for disk in disks:
            print(disk.dev, disk)
            print()
    disks.sort()
    return disks
71167
def cli(env, identifier):
    """"""

    manager = SoftLayer.SSLManager(env.client)
    certificate = manager.get_certificate(identifier)

    write_cert(certificate['commonName'] + '.crt', certificate['certificate'])
    write_cert(certificate['commonName'] + '.key', certificate['privateKey'])

    if 'intermediateCertificate' in certificate:
        write_cert(certificate['commonName'] + '.icc',
                   certificate['intermediateCertificate'])

    if 'certificateSigningRequest' in certificate:
        write_cert(certificate['commonName'] + '.csr',
                   certificate['certificateSigningRequest'])
836254
def _get_state(self):
        

        result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
        for info in result.splitlines():
            if '=' in info:
                name, value = info.split('=', 1)
                if name == "VMState":
                    return value.strip('"')
        return "unknown"
999357
def recv_file_from_host(src_file, dst_filename, filesize, dst_mode='wb'):
    """"""
    import sys
    import ubinascii
    if HAS_BUFFER:
        try:
            import pyb
            usb = pyb.USB_VCP()
        except:
            try:
                import machine
                usb = machine.USB_VCP()
            except:
                usb = None
        if usb and usb.isconnected():
            # We don't want 0x03 bytes in the data to be interpreted as a Control-C
            # This gets reset each time the REPL runs a line, so we don't need to
            # worry about resetting it ourselves
            usb.setinterrupt(-1)
    try:
        with open(dst_filename, dst_mode) as dst_file:
            bytes_remaining = filesize
            if not HAS_BUFFER:
                bytes_remaining *= 2  # hexlify makes each byte into 2
            buf_size = BUFFER_SIZE
            write_buf = bytearray(buf_size)
            read_buf = bytearray(buf_size)
            while bytes_remaining > 0:
                # Send back an ack as a form of flow control
                sys.stdout.write('\x06')
                read_size = min(bytes_remaining, buf_size)
                buf_remaining = read_size
                buf_index = 0
                while buf_remaining > 0:
                    if HAS_BUFFER:
                        bytes_read = sys.stdin.buffer.readinto(read_buf, read_size)
                    else:
                        bytes_read = sys.stdin.readinto(read_buf, read_size)
                    if bytes_read > 0:
                        write_buf[buf_index:bytes_read] = read_buf[0:bytes_read]
                        buf_index += bytes_read
                        buf_remaining -= bytes_read
                if HAS_BUFFER:
                    dst_file.write(write_buf[0:read_size])
                else:
                    dst_file.write(ubinascii.unhexlify(write_buf[0:read_size]))
                bytes_remaining -= read_size
        return True
    except:
        return False
926385
def _verify_cert(self, sock: ssl.SSLSocket):
        ''''''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
1132996
def get_sp_cert(self):
        
        cert = self.__sp.get('x509cert')
        cert_file_name = self.__paths['cert'] + 'sp.crt'

        if not cert and exists(cert_file_name):
            with open(cert_file_name) as f:
                cert = f.read()

        return cert or None
1276199
def _check_certificate(self):
        
        if (self.file_name.startswith("jdk-") and self.repo == "sbo" and
                self.downder == "wget"):
            certificate = (' --no-check-certificate --header="Cookie: '
                           'oraclelicense=accept-securebackup-cookie"')
            self.msg.template(78)
            print("| '{0}' need to go ahead downloading".format(
                certificate[:23].strip()))
            self.msg.template(78)
            print("")
            self.downder_options += certificate
            if not self.msg.answer() in ["y", "Y"]:
                raise SystemExit()
837223
def find_dvs_by_path(self,si ,path):
        
        dvs = self.get_folder(si, path)

        if not dvs:
            raise ValueError('Could not find Default DvSwitch in path {0}'.format(path))
        elif not isinstance(dvs, vim.dvs.VmwareDistributedVirtualSwitch):
            raise ValueError('The object in path {0} is {1} and not a DvSwitch'.format(path, type(dvs)))

        return dvs
543842
def export_certificate(ctx, slot, format, certificate):
    
    controller = ctx.obj['controller']
    try:
        cert = controller.read_certificate(slot)
    except APDUError as e:
        if e.sw == SW.NOT_FOUND:
            ctx.fail('No certificate found.')
        else:
            logger.error('Failed to read certificate from slot %s', slot,
                         exc_info=e)
    certificate.write(cert.public_bytes(encoding=format))
396284
def _get_vswitch_name(self, network_type, physical_network):
        """"""
        if network_type != constants.TYPE_LOCAL:
            vswitch_name = self._get_vswitch_for_physical_network(
                physical_network)
        else:
            vswitch_name = self._local_network_vswitch

        if vswitch_name:
            return vswitch_name

        err_msg = _("No vSwitch configured for physical network "
                    "'%(physical_network)s'. Neutron network type: "
                    "'%(network_type)s'.")
        raise exception.NetworkingHyperVException(
            err_msg % dict(physical_network=physical_network,
                           network_type=network_type))
1299865
def from_directory(cls, directory):
        """"""
        cert_path = os.path.join(directory, 'skein.crt')
        key_path = os.path.join(directory, 'skein.pem')
        for path, name in [(cert_path, 'cert'), (key_path, 'key')]:
            if not os.path.exists(path):
                raise context.FileNotFoundError(
                    "Security %s file not found at %r" % (name, path)
                )
        return Security(cert_file=cert_path, key_file=key_path)