Create a Device instance from object path.
7806
def get(self, object_path, interfaces_and_properties=None):
        """"""
        # check this before creating the DBus object for more
        # controlled behaviour:
        if not interfaces_and_properties:
            interfaces_and_properties = self._objects.get(object_path)
            if not interfaces_and_properties:
                return None
        property_hub = PropertyHub(interfaces_and_properties)
        method_hub = MethodHub(
            self._proxy.object.bus.get_object(object_path))
        return Device(self, object_path, property_hub, method_hub)
535468
static DeviceInfo initialize(Context context) {
        if (thisInstance_ == null) {
            thisInstance_ = new DeviceInfo(context);
        }
        return thisInstance_;
    }
519368
def use_device(cls, device):
        """"""
        if device == cls.ops.device:
            yield
        else:
            curr_Ops, curr_ops = (cls.Ops, cls.ops)
            cls.Ops = get_ops(device)
            cls.ops = cls.Ops()
            yield
            cls.Ops = curr_Ops
            cls.ops = curr_ops
525160
def _get_property(device_path: Union[Path, str], property_name: str) -> str:
    """"""
    with open(str(Path(device_path, property_name))) as file:
        return file.readline().strip()
961784
def create_instance(credentials, project, zone, name,
                    startup_script=None, startup_script_url=None,
                    metadata=None,
                    machine_type='f1-micro', tags=None,
                    disk_size_gb=10, wait_until_done=False):
    """"""

    if startup_script is not None and startup_script_url is not None:
        raise ValueError('Cannot specify a startup script string and URL '
                         'at the same time!')

    access_token = credentials.get_access_token()

    if metadata is None:
        metadata = {}
    meta_items = [{'key': k, 'value': v} for k, v in metadata.items()]

    if tags is None:
        tags = []

    if startup_script is not None:
        meta_items.insert(
            0, {'key': 'startup-script', 'value': startup_script}
        )
    elif startup_script_url is not None:
        meta_items.insert(
            0, {'key': 'startup-script-url', 'value': startup_script_url})

    payload = {
        "name": name,
        "zone": "projects/%s/zones/%s" % (project, zone),
        "machineType": "projects/%s/zones/%s/machineTypes/%s"
                       % (project, zone, machine_type),
        "metadata": {
            "items": meta_items
        },
        "tags": {
            "items": tags
        },
        "disks": [
            {
                "type": "PERSISTENT",
                "boot": True,
                "mode": "READ_WRITE",
                "autoDelete": True,
                "deviceName": name,
                "initializeParams": {
                    "sourceImage": "projects/ubuntu-os-cloud/global/images/ubuntu-1604-xenial-v20170815a",
                    "diskType": "projects/%s/zones/%s/diskTypes/pd-standard" % (project, zone),
                    "diskSizeGb": str(disk_size_gb)
                }
            }
        ],
        "canIpForward": False,
        "networkInterfaces": [
            {
                "network": "projects/%s/global/networks/default" % project,
                "subnetwork": "projects/%s/regions/%s/subnetworks/default" % (project, zone[:-2]),
                "accessConfigs": [
                    {
                        "name": "External NAT", "type": "ONE_TO_ONE_NAT"
                    }
                ]
            }
        ],
        "description": "",
        "scheduling": {
            "preemptible": False,
            "onHostMaintenance": "MIGRATE",
            "automaticRestart": True
        },
        "serviceAccounts": [
            {
                "email": "default",
                "scopes": [
                    'https://www.googleapis.com/auth/compute',
                    "https://www.googleapis.com/auth/devstorage.read_write",
                    "https://www.googleapis.com/auth/logging.write",
                    "https://www.googleapis.com/auth/monitoring.write",
                    "https://www.googleapis.com/auth/servicecontrol",
                    "https://www.googleapis.com/auth/service.management.readonly",
                    "https://www.googleapis.com/auth/trace.append"
                ]
            }
        ]
    }
    #header = 'Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg'
    headers = {
        'Authorization': 'Bearer %s' % access_token.access_token
    }

    #print('Test:', json.dumps(payload, indent=4, sort_keys=True))
    
    _LOGGER.debug('Access token: %s' % access_token.access_token)

    _LOGGER.debug('Payload: %s', json.dumps(payload, sort_keys=True, indent=4))


    r = requests.post('https://www.googleapis.com/compute/v1/'
                      'projects/%s/zones/%s/instances' % (project, zone),
                      headers=headers, json=payload)

    r.raise_for_status()

    op_name = r.json()['name']

    _LOGGER.info('Submitted request to create intsance '
                '(HTTP code: %d).',
                r.status_code)

    if wait_until_done:
        _LOGGER.info('Waiting until operation is done...')
        wait_for_zone_op(access_token, project, zone, op_name)

    return op_name
962925
def from_context(cls, context):
        """"""
        return cls(id=context.id, context=context.to_dict())
253141
def _device_to_sysfs_path(device):
    """"""
    return '%s-%s' % (
        device.getBusNumber(),
        '.'.join([str(item) for item in device.GetPortNumberList()]))
1368713
def p_mp_createInstance(p):
    """"""
    inst = p[1]
    if p.parser.verbose:
        p.parser.log(
            _format("Creating instance of {0!A}.", inst.classname))
    try:
        p.parser.handle.CreateInstance(inst)
    except CIMError as ce:
        if ce.status_code == CIM_ERR_ALREADY_EXISTS:
            if p.parser.verbose:
                p.parser.log(
                    _format("Instance of class {0!A} already exist. "
                            "Modifying...", inst.classname))
            try:
                p.parser.handle.ModifyInstance(inst)
            except CIMError as ce:
                if ce.status_code == CIM_ERR_NOT_SUPPORTED:
                    if p.parser.verbose:
                        p.parser.log(
                            _format("ModifyInstance not supported. "
                                    "Deleting instance of {0!A}: {1}",
                                    inst.classname, inst.path))
                    p.parser.handle.DeleteInstance(inst.path)
                    if p.parser.verbose:
                        p.parser.log(
                            _format("Creating instance of {0!A}.",
                                    inst.classname))
                    p.parser.handle.CreateInstance(inst)
        else:
            ce.file_line = (p.parser.file, p.lexer.lineno)
            raise
324988
def from_object(cls, obj):
        # type: (Any) -> UrlPath
        
        if isinstance(obj, UrlPath):
            return obj
        if isinstance(obj, _compat.string_types):
            return UrlPath.parse(obj)
        if isinstance(obj, PathParam):
            return UrlPath(obj)
        if isinstance(obj, (tuple, list)):
            return UrlPath(*obj)
        raise ValueError("Unable to convert object to UrlPath `%r`" % obj)
536378
def run_init(device_type, args):
    """"""
    util.setup_logging(verbosity=args.verbose)
    log.warning('This GPG tool is still in EXPERIMENTAL mode, '
                'so please note that the API and features may '
                'change without backwards compatibility!')

    verify_gpg_version()

    # Prepare new GPG home directory for hardware-based identity
    device_name = os.path.basename(sys.argv[0]).rsplit('-', 1)[0]
    log.info('device name: %s', device_name)
    homedir = args.homedir
    if not homedir:
        homedir = os.path.expanduser('~/.gnupg/{}'.format(device_name))

    log.info('GPG home directory: %s', homedir)

    if os.path.exists(homedir):
        log.error('GPG home directory %s exists, '
                  'remove it manually if required', homedir)
        sys.exit(1)

    check_call(['mkdir', '-p', homedir])
    check_call(['chmod', '700', homedir])

    agent_path = util.which('{}-gpg-agent'.format(device_name))

    # Prepare GPG agent invocation script (to pass the PATH from environment).
    with open(os.path.join(homedir, 'run-agent.sh'), 'w') as f:
        f.write(r"""#!/bin/sh
export PATH={0}
{1} \
-vv \
--pin-entry-binary={pin_entry_binary} \
--passphrase-entry-binary={passphrase_entry_binary} \
--cache-expiry-seconds={cache_expiry_seconds} \
$*
""".format(os.environ['PATH'], agent_path, **vars(args)))
    check_call(['chmod', '700', f.name])
    run_agent_script = f.name

    # Prepare GPG configuration file
    with open(os.path.join(homedir, 'gpg.conf'), 'w') as f:
        f.write("""# Hardware-based GPG configuration
agent-program {0}
personal-digest-preferences SHA512
default-key \"{1}\"
""".format(run_agent_script, args.user_id))

    # Prepare a helper script for setting up the new identity
    with open(os.path.join(homedir, 'env'), 'w') as f:
        f.write("""#!/bin/bash
set -eu
export GNUPGHOME={0}
COMMAND=$*
if [ -z "${{COMMAND}}" ]
then
    ${{SHELL}}
else
    ${{COMMAND}}
fi
""".format(homedir))
    check_call(['chmod', '700', f.name])

    # Generate new GPG identity and import into GPG keyring
    pubkey = write_file(os.path.join(homedir, 'pubkey.asc'),
                        export_public_key(device_type, args))
    verbosity = ('-' + ('v' * args.verbose)) if args.verbose else '--quiet'
    check_call(keyring.gpg_command(['--homedir', homedir, verbosity,
                                    '--import', pubkey.name]))

    # Make new GPG identity with "ultimate" trust (via its fingerprint)
    out = check_output(keyring.gpg_command(['--homedir', homedir,
                                            '--list-public-keys',
                                            '--with-fingerprint',
                                            '--with-colons']))
    fpr = re.findall('fpr:::::::::([0-9A-F]+):', out)[0]
    f = write_file(os.path.join(homedir, 'ownertrust.txt'), fpr + ':6\n')
    check_call(keyring.gpg_command(['--homedir', homedir,
                                    '--import-ownertrust', f.name]))

    # Load agent and make sure it responds with the new identity
    check_call(keyring.gpg_command(['--homedir', homedir,
                                    '--list-secret-keys', args.user_id]))
315289
def create_uinput_device(mapping):
    """"""
    if mapping not in _mappings:
        raise DeviceError("Unknown device mapping: {0}".format(mapping))

    try:
        mapping = _mappings[mapping]
        device = UInputDevice(mapping)
    except UInputError as err:
        raise DeviceError(err)

    return device
723684
def create(self, object_name, size=0, hash=None, extra=None, meta_data=None):
        
        obj = BaseObject(container=self.container,
                         driver=self.driver,
                         name=object_name,
                         size=size,
                         hash=hash,
                         extra=extra,
                         meta_data=meta_data)
        return Object(obj=obj)
1052661
def CreateInstance(self, *args, **kwargs):
        

        inst = args[0] if args else kwargs['NewInstance']
        try:
            self.instances[self.default_namespace].append(inst)
        except KeyError:
            self.instances[self.default_namespace] = [inst]
        return inst.path
685578
def create_instance(self, parent):
        """"""
        self.kwargs['instantiate'] = True
        self.kwargs['parent'] = parent
        instance = self.cls(*self.args, **self.kwargs)
        instance._field_seqno = self._field_seqno
        return instance
837834
def create_client_from_path(self, path):
        """"""
        self.create_new_client()
        sw = self.get_current_shellwidget()
        sw.set_cwd(path)
1153505
def from_path(cls, conn, path):
        """"""
        path = path.strip(SEP)
        full_path = os.path.join(conn.abs_root, path)
        return cls(conn, path, 0, os.path.getsize(full_path))
1013651
private Device loadDevice() {
        //Initialise object with the content saved in shared pref file.
        SharedPreferences sharedPreferences = getSharedPreferences();
        return new Device()
                .setApiSpaceId(sharedPreferences.getString(KEY_API_SPACE_ID, null))
                .setAppVer(sharedPreferences.getInt(KEY_APP_VER, -1))
                .setInstanceId(sharedPreferences.getString(KEY_INSTANCE_ID, null))
                .setPushToken(sharedPreferences.getString(KEY_PUSH_TOKEN, null))
                .setDeviceId(sharedPreferences.getString(KEY_DEVICE_ID, null));
    }