Add a Package object to the policy with action=install.

        Args:
            pkg: A Package object to add.
            action_type (str, optional): One of "Install", "Cache", or
                "Install Cached".  Defaults to "Install".
493105
def add_package(self, pkg, action_type="Install"):
        
        if isinstance(pkg, Package):
            if action_type not in ("Install", "Cache", "Install Cached"):
                raise ValueError
            package = self.add_object_to_path(
                pkg, "package_configuration/packages")
            # If there's already an action specified, get it, then
            # overwrite. Otherwise, make a new subelement.
            action = package.find("action")
            if not action:
                action = ElementTree.SubElement(package, "action")
            action.text = action_type
        else:
            raise ValueError("Please pass a Package object to parameter: "
                             "pkg.")
737622
def register_pkg(name, formula_def, conn=None):
    '''
    
    '''
    close = False
    if conn is None:
        close = True
        conn = init()

    conn.execute('INSERT INTO packages VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
        name,
        formula_def['version'],
        formula_def['release'],
        datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'),
        formula_def.get('os', None),
        formula_def.get('os_family', None),
        formula_def.get('dependencies', None),
        formula_def.get('os_dependencies', None),
        formula_def.get('os_family_dependencies', None),
        formula_def['summary'],
        formula_def['description'],
    ))
    if close:
        conn.close()
414854
def install(self):
        
        packages = self.packages()
        if packages:
            print("")   # new line at start
            for pkg in packages:
                ver = SBoGrep(pkg).version()
                prgnam = "{0}-{1}".format(pkg, ver)
                if find_package(prgnam, self.meta.output):
                    binary = slack_package(prgnam)
                    PackageManager(binary).upgrade(flag="--install-new")
                else:
                    print("\nPackage {0} not found in the {1} for "
                          "installation\n".format(prgnam, self.meta.output))
        else:
            print("\nPackages not found in the queue for installation\n")
            raise SystemExit(1)
1373916
public static function add($fslTypeHandle, $fslTypeName, $pkg = false)
    {
        $em = \ORM::entityManager();
        $o = new \Concrete\Core\Entity\File\StorageLocation\Type\Type();
        $o->fslTypeHandle = $fslTypeHandle;
        $o->fslTypeName = $fslTypeName;
        if ($pkg instanceof \Concrete\Core\Package\Package || $pkg instanceof \Concrete\Core\Entity\Package) {
            $o->pkgID = $pkg->getPackageID();
        }
        $em->persist($o);
        $em->flush();

        return $o;
    }
895763
def install_package(context):
    """"""

    if not context.dry_run and build_distributions(context):
        with util.mktmpdir() as tmp_dir:
            venv.create_venv(tmp_dir=tmp_dir)
            for distribution in Path('dist').files():
                try:
                    venv.install(distribution, tmp_dir)
                    log.info('Successfully installed %s', distribution)
                    if context.test_command and verification.run_test_command(context):
                        log.info(
                            'Successfully ran test command: %s', context.test_command
                        )
                except Exception as e:
                    raise Exception(
                        'Error installing distribution %s' % distribution, e
                    )
    else:
        log.info('Dry run, skipping installation')
1264240
def add(self, effect=None, act=None, obj=None,
            policy=None, policies=None):
        
        if policies is not None:
            for p in policies:
                self.add(policy=p)
        elif policy is not None:
            for e, a, o in policy:
                self.add(e, a, o)
        else:
            objc = obj.components if obj is not None else []
            self.tree[act.components + objc] = effect
436591
private void installPackage() {
        AndPermission.with(this)
            .install()
            .file(new File(Environment.getExternalStorageDirectory(), "android.apk"))
            .rationale(new InstallRationale())
            .onGranted(new Action<File>() {
                @Override
                public void onAction(File data) {
                    // Installing.
                    toast(R.string.successfully);
                }
            })
            .onDenied(new Action<File>() {
                @Override
                public void onAction(File data) {
                    // The user refused to install.
                    toast(R.string.failure);
                }
            })
            .start();
    }
12400
protected void addPackageUse(PackageDoc pkg, Content contentTree) throws IOException {
        Content tdFirst = HtmlTree.TD(HtmlStyle.colFirst,
                getHyperLink(pkg.name(), new StringContent(Util.getPackageName(pkg))));
        contentTree.addContent(tdFirst);
        HtmlTree tdLast = new HtmlTree(HtmlTag.TD);
        tdLast.addStyle(HtmlStyle.colLast);
        addSummaryComment(pkg, tdLast);
        contentTree.addContent(tdLast);
    }
1336532
def deploy(self, package=None):
        
        if package is None:
            package = deployment_package.default()
        package.deploy()
        if self.proper_name in installed_functions():
            self.update(package)
        else:
            self.install(package)
26348
def install(self, name=None, prefix=None, pkgs=None, dep=True,
                channels=None, token=None):
        
        logger.debug(str((prefix, pkgs, channels)))

        # TODO: Fix temporal hack
        if not pkgs or not isinstance(pkgs, (list, tuple, str)):
            raise TypeError('must specify a list of one or more packages to '
                            'install into existing environment')

        cmd_list = ['install', '--yes', '--json', '--force-pscheck']
        if name:
            cmd_list.extend(['--name', name])
        elif prefix:
            cmd_list.extend(['--prefix', prefix])
        else:
            # Just install into the current environment, whatever that is
            pass

        # TODO: Check if correct
        if channels:
            cmd_list.extend(['--override-channels'])

            for channel in channels:
                cmd_list.extend(['--channel'])
                channel = self.parse_token_channel(channel, token)
                cmd_list.extend([channel])

        # TODO: Fix temporal hack
        if isinstance(pkgs, (list, tuple)):
            cmd_list.extend(pkgs)
        elif isinstance(pkgs, str):
            cmd_list.extend(['--file', pkgs])

        if not dep:
            cmd_list.extend(['--no-deps'])

        return self._call_and_parse(cmd_list)
594054
def add_argument(self, *args, **kwargs):
        
        if not (('action' in kwargs) and (kwargs['action'] == 'help')):
            # make sure required parameter options were defined
            try:
                name = kwargs['dest']
                param_type = kwargs['type']
                optional = kwargs['optional']
            except KeyError as e:
                detail = "%s option required. " % e
                raise KeyError(detail)
            if optional and ('default' not in kwargs):
                detail = "A default value is required for optional parameters %s." % name
                raise KeyError(detail)

            # grab the default and help values
            default = None
            if 'default' in kwargs:
                default = kwargs['default']
            param_help = ""
            if 'help' in kwargs:
                param_help = kwargs['help']

            # set the ArgumentParser's action
            if param_type not in (str, int, float, bool, ChrisApp.path):
                detail = "unsupported type: '%s'" % param_type
                raise ValueError(detail)
            action = 'store'
            if param_type == bool:
                action = 'store_false' if default else 'store_true'
                del kwargs['default'] # 'default' and 'type' not allowed for boolean actions
                del kwargs['type']
            kwargs['action'] = action

            # store the parameters internally (param_type.__name__ to enable json serialization)
            param = {'name': name, 'type': param_type.__name__, 'optional': optional,
                     'flag': args[0], 'action': action, 'help': param_help, 'default': default}
            self._parameters.append(param)

            # add the parameter to the parser
            del kwargs['optional']
        ArgumentParser.add_argument(self, *args, **kwargs)
374389
def setup(__pkg: ModuleType) -> Tuple[Callable[[str], str],
                                      Callable[[str, str, int], str]]:
    
    package_locale = path.join(path.dirname(__pkg.__file__), 'locale')
    gettext.install(__pkg.__name__, package_locale)

    return gettext.gettext, gettext.ngettext
985879
function addAndCommitDistDir() {
			if (commit.pkgPath && options.distDir && !/^(?:\.|\/)[^\.]/.test(options.distDir)) {
				// need to update the package included in the distribution
				pkgUpdate(path.join(options.distDir, commit.pkgPath), commit.pkgPathBower ? path.join(options.distDir,
						commit.pkgPathBower) : null, true, false);
			}
			if (options.distDir || athrsRtn || chgLogRtn) {
				if (options.distDir) {
					cmd('git add --force ' + options.distDir);
				}
				// Commit changes (needed to generate archive asset)
				cmd('git commit -q -m "' + tmpltData.distBranchPubMsg + '"');
			}
		}
904566
def push(package, is_public=False, is_team=False, reupload=False, hash=None):
    
    team, owner, pkg, subpath = parse_package(package, allow_subpath=True)
    _check_team_id(team)
    session = _get_session(team)

    store, pkgroot = PackageStore.find_package(team, owner, pkg, pkghash=hash)
    if pkgroot is None:
        raise CommandException("Package {package} not found.".format(package=package))

    pkghash = hash_contents(pkgroot)
    if hash is not None:
        assert pkghash == hash
    contents = pkgroot

    for component in subpath:
        try:
            contents = contents.children[component]
        except (AttributeError, KeyError):
            raise CommandException("Invalid subpath: %r" % component)

    def _push_package(dry_run=False, sizes=dict()):
        data = json.dumps(dict(
            dry_run=dry_run,
            is_public=is_public,
            is_team=is_team,
            contents=contents,
            description="",  # TODO
            sizes=sizes
        ), default=encode_node)

        compressed_data = gzip_compress(data.encode('utf-8'))

        if subpath:
            return session.post(
                "{url}/api/package_update/{owner}/{pkg}/{subpath}".format(
                    url=get_registry_url(team),
                    owner=owner,
                    pkg=pkg,
                    subpath='/'.join(subpath)
                ),
                data=compressed_data,
                headers={
                    'Content-Encoding': 'gzip'
                }
            )
        else:
            return session.put(
                "{url}/api/package/{owner}/{pkg}/{hash}".format(
                    url=get_registry_url(team),
                    owner=owner,
                    pkg=pkg,
                    hash=pkghash
                ),
                data=compressed_data,
                headers={
                    'Content-Encoding': 'gzip'
                }
            )

    print("Fetching upload URLs from the registry...")
    resp = _push_package(dry_run=True)
    obj_urls = resp.json()['upload_urls']

    assert set(obj_urls) == set(find_object_hashes(contents))

    obj_sizes = {
        obj_hash: os.path.getsize(store.object_path(obj_hash)) for obj_hash in obj_urls
    }

    success = upload_fragments(store, obj_urls, obj_sizes, reupload=reupload)
    if not success:
        raise CommandException("Failed to upload fragments")

    print("Uploading package metadata...")
    resp = _push_package(sizes=obj_sizes)
    package_url = resp.json()['package_url']

    if not subpath:
        # Update the latest tag.
        print("Updating the 'latest' tag...")
        session.put(
            "{url}/api/tag/{owner}/{pkg}/{tag}".format(
                url=get_registry_url(team),
                owner=owner,
                pkg=pkg,
                tag=LATEST_TAG
            ),
            data=json.dumps(dict(
                hash=pkghash
            ))
        )

    print("Push complete. %s is live:\n%s" % (package, package_url))
1090555
def install_package_command(package_name):
    ''''''
    #TODO refactor python logic
    if sys.platform == "win32":
        cmds = 'python -m pip install --user {0}'.format(package_name)
    else:
        cmds = 'python3 -m pip install --user {0}'.format(package_name)
    call(cmds, shell=True)
1034294
def install(packagename, save, save_dev, save_test, filename):
    
    print('Installing ', packagename)
    print(sh_pip.install(packagename))
    if not filename:
        filename = get_filename(save, save_dev, save_test)
    try:
        add_requirements(packagename, filename)
    except AssertionError:
        print('Package already pinned in ', filename)
188203
@Override
	public Action install(Action action, Tree config) {

		// Is caching enabled?
		Tree cacheNode = config.get("cache");
		if (cacheNode == null || cacheNode.isNull()) {
			return null;
		}
		if (cacheNode.getType() == Boolean.class && !cacheNode.asBoolean()) {
			return null;
		}
		
		// Get cache keys
		Tree keyNode = cacheNode.get("keys");
		final String[] keys;
		if (keyNode == null) {
			keys = null;
		} else {
			List<String> list = keyNode.asList(String.class);
			if (list.isEmpty()) {
				keys = null;
			} else {
				keys = new String[list.size()];
				list.toArray(keys);
			}
		}

		// Get TTL (0 = use default TTL)
		final int ttl = cacheNode.get("ttl", 0);

		return new Action() {

			@Override
			public Object handler(Context ctx) throws Exception {
				String key = getCacheKey(ctx.name, ctx.params, keys);
				return new Promise(resolver -> {
					get(key).then(in -> {
						if (in == null || in.isNull()) {
							new Promise(action.handler(ctx)).then(tree -> {
								set(key, tree, ttl);
								resolver.resolve(tree);
							}).catchError(err -> {
								resolver.reject(err);
							});
						} else {
							resolver.resolve(in);
						}
					}).catchError(err -> {
						resolver.reject(err);
					});
				});
			}
		};
	}