Create instance with startup script.

    TODO: docstring
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
234581
def run_init(args):
    
    root = args.root
    if root is None:
        root = '.'
    root = os.path.abspath(root)

    project_data = _get_package_data()
    project_name = project_data['project_name']

    directories = [os.path.join(root, 'bin'),
                   os.path.join(root, 'docs'),
                   os.path.join(root, 'tests'),
                   os.path.join(root, project_name),
                   ]
    for dir_path in directories:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

    script_paths = [os.path.join(root, 'README.md'),
                    os.path.join(root, 'tests/__init__.py'),
                    ]
    for script_path in script_paths:
        if not os.path.exists(script_path):
            os.mknod(script_path)

    copy_samples = [(resource_filename('mpu', 'package/templates/tox.ini.txt'),
                     os.path.join(root, 'tox.ini')),
                    (resource_filename('mpu',
                                       'package/templates/setup.cfg.txt'),
                     os.path.join(root, 'setup.cfg')),
                    (resource_filename('mpu',
                                       'package/templates/setup.py.txt'),
                     os.path.join(root, 'setup.py')),
                    (resource_filename('mpu',
                                       'package/templates/_version.py.txt'),
                     os.path.join(root, project_name + '/_version.py')),
                    (resource_filename('mpu',
                                       'package/templates/coveragerc.txt'),
                     os.path.join(root, '.coveragerc')),
                    (resource_filename('mpu', 'package/templates/init.py.txt'),
                     os.path.join(root, project_name + '/__init__.py')),
                    ]
    translate = {'[[project_name]]': project_data['project_name'],
                 '[[license]]': project_data['license'],
                 '[[author]]': project_data['author'],
                 '[[email]]': project_data['email'],
                 }
    for source, destination in copy_samples:
        if not os.path.exists(destination):
            copyfile(source, destination)
            _adjust_template(destination, translate)
1200154
def create(cls, path):
        """"""
        try:
            os.makedirs(path)
        except OSError as e:
            if not e.errno == errno.EEXIST:
                raise
        cmd = [SVNADMIN, 'create', path]
        subprocess.check_call(cmd)
        return cls(path)
390847
protected Instance createInstance()
        throws InstallationException
    {
        final Insert insert;
        try {
            insert = new Insert(getCiType());
            insert.add("Name", this.programName);
            if (getEFapsUUID() != null) {
                insert.add("UUID", getEFapsUUID().toString());
            }
            insert.execute();
        } catch (final EFapsException e)  {
            throw new InstallationException("Could not create " + getCiType() + " " + getProgramName(), e);
        }
        return insert.getInstance();
    }
536242
def instantiate(config):

    

    for handle, cfg in list(config["apps"].items()):
        if not cfg.get("enabled", True):
            continue
        app = get_application(handle)
        instances[app.handle] = app(cfg)
1186220
def startup_script(self, startup_script):
        

        try:
            startup_script_path = os.path.join(self.working_dir, 'startup.vpc')
            with open(startup_script_path, "w+", encoding='utf-8') as f:
                if startup_script is None:
                    f.write('')
                else:
                    startup_script = startup_script.replace("%h", self._name)
                    f.write(startup_script)
        except OSError as e:
            raise VPCSError('Cannot write the startup script file "{}": {}'.format(startup_script_path, e))
1108720
def create(self):
        
        self.add_handlers({'^E': self.quit, '^Q': self.quit})
        to_delete = self.old_instances - self.new_instances
        self.add(npyscreen.Textfield, value='Select which instances to delete'
                 ' (you must select ' + str(to_delete) +
                 ' instance(s) to delete):', editable=False, color='GOOD')
        self.del_instances = self.add(InstanceSelect,
                                      values=self.cur_instances,
                                      scroll_exit=True, rely=3,
                                      instance_num=to_delete)
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
261030
def start(context, mip_config, email, priority, dryrun, command, start_with, family):
    """"""
    mip_cli = MipCli(context.obj['script'])
    mip_config = mip_config or context.obj['mip_config']
    email = email or environ_email()
    kwargs = dict(config=mip_config, family=family, priority=priority, email=email, dryrun=dryrun, start_with=start_with)
    if command:
        mip_command = mip_cli.build_command(**kwargs)
        click.echo(' '.join(mip_command))
    else:
        try:
            mip_cli(**kwargs)
            if not dryrun:
                context.obj['store'].add_pending(family, email=email)
        except MipStartError as error:
            click.echo(click.style(error.message, fg='red'))
1373704
def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env:
        
        settings = self.get_preset(preset)
        return wrapped_env_maker(self.envname, seed, serial_id, **settings)
844454
def add_init_script(self, file, name):
        
        f_path = os.path.join("/etc/init.d", name)
        f = open(f_path, "w")
        f.write(file)
        f.close()
        os.chmod(f_path, stat.S_IREAD| stat.S_IWRITE | stat.S_IEXEC)
        self.run("/usr/sbin/update-rc.d %s defaults" % name)
1169838
private void initializeInstance() {
		this.processHelper = Programs.as(this.jobInstance);

		if (this.launchId == null) {
			this.launchId = UUID.randomUUID();
		}
		this.launchResult = new LaunchResult();
	}
662253
def add_script(nc, line):
    """"""

    assert type(nc) == dict

    nc["startup"] = nc.get("startup") or ""

    if not nc["startup"].endswith("\n"):
        nc["startup"] += "\n"
    nc["startup"] += line + "\n"
440188
def start
      puts "\n******************************************************************************************************************************************\n\n"
      puts "  JumpStarting....\n".purple
      check_setup
      execute_install_command
      run_scripts_from_yaml(:run_after_install_command)
      parse_template_dir
      create_dirs
      populate_files_from_whole_templates
      populate_files_from_append_templates
      populate_files_from_line_templates
      remove_unwanted_files
      run_scripts_from_yaml(:run_after_jumpstart)
      check_for_strings_to_replace
      run_scripts_from_yaml(:run_after_string_replace)
      check_local_nginx_configuration
      exit_with_success
    end
769963
def start(self, *args):
        

        if self.volumes: 
            volumes = " --bind " + " --bind ".join(self.volumes)
        else:
            volumes = ""
        
        self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The container ID is printed below.".format(self.name, self.time_out))
        utils.xrun("singularity instance.start", 
                        list(args) + [volumes,
#                        "-c",
                        self.image, self.name])

        self.status = "created"

        return 0
964380
def create(example):
    """"""
    try:
        this_dir = os.path.dirname(os.path.realpath(__file__))
        example_dir = os.path.join(this_dir, os.pardir, "examples", example)
        shutil.copytree(example_dir, os.path.join(os.getcwd(), example))
        log("Example created.", delay=0)
    except TypeError:
        click.echo("Example '{}' does not exist.".format(example))
    except OSError:
        click.echo("Example '{}' already exists here.".format(example))
1341460
def create(cls, fields=None, **fields_kwargs):
        
        # NOTE -- you cannot use hydrate/populate here because populate alters modified fields
        instance = cls(fields, **fields_kwargs)
        instance.save()
        return instance