Raise an exception if the value is not a valid package name
    as defined in the EthPM-Spec.
182147
def validate_package_name(pkg_name: str) -> None:
    
    if not bool(re.match(PACKAGE_NAME_REGEX, pkg_name)):
        raise ValidationError(f"{pkg_name} is not a valid package name.")
437142
def handle_integrity_error(cls, exception):
        """"""

        m = re.match(cls.MYSQL_INSERT_ERROR_REGEX,
                     exception.statement)

        if not m:
            raise exception

        model = find_model_by_table_name(m.group('table'))

        if not model:
            raise exception

        m = re.match(cls.MYSQL_DUPLICATE_ENTRY_ERROR_REGEX,
                     exception.orig.args[1])

        if not m:
            raise exception

        entity = model.__name__
        eid = m.group('value')

        raise AlreadyExistsError(entity=entity, eid=eid)
424394
def version_is_valid(version_str):
    
    try:
        packaging.version.Version(version_str)
    except packaging.version.InvalidVersion:
        return False
    return True
284165
def validate_spec(self, key, value):
        """"""
        if self.spec and self.spec != value:
            raise OAISetSpecUpdateError("Updating spec is not allowed.")
        return value
959724
def future_raise(self, tp, value=None, tb=None):
        """"""
        if value is not None and isinstance(tp, Exception):
            raise TypeError("instance exception may not have a separate value")
        if value is not None:
            exc = tp(value)
        else:
            exc = tp
        if exc.__traceback__ is not tb:
            raise exc.with_traceback(tb)
        raise exc
586375
def reason(self, reason):
        
        if reason is None:
            raise ValueError("Invalid value for `reason`, must not be `None`")
        allowed_values = ["reservation", "reservation_release", "reservation_termination", "package_creation", "package_renewal", "package_termination"]
        if reason not in allowed_values:
            raise ValueError(
                "Invalid value for `reason` ({0}), must be one of {1}"
                .format(reason, allowed_values)
            )

        self._reason = reason
711192
def packageExists(self, package):
		
		url = "%s/packages" % self.base_url
		params = {"pattern": package}
		response = requests.get(url, params=params)
		if response.status_code != requests.codes.ok:
			return False

		return True
277561
def check_package_set(package_set, should_ignore=None):
    # type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult
    
    if should_ignore is None:
        def should_ignore(name):
            return False

    missing = dict()
    conflicting = dict()

    for package_name in package_set:
        # Info about dependencies of package_name
        missing_deps = set()  # type: Set[Missing]
        conflicting_deps = set()  # type: Set[Conflicting]

        if should_ignore(package_name):
            continue

        for req in package_set[package_name].requires:
            name = canonicalize_name(req.project_name)  # type: str

            # Check if it's missing
            if name not in package_set:
                missed = True
                if req.marker is not None:
                    missed = req.marker.evaluate()
                if missed:
                    missing_deps.add((name, req))
                continue

            # Check if there's a conflict
            version = package_set[name].version  # type: str
            if not req.specifier.contains(version, prereleases=True):
                conflicting_deps.add((name, version, req))

        if missing_deps:
            missing[package_name] = sorted(missing_deps, key=str)
        if conflicting_deps:
            conflicting[package_name] = sorted(conflicting_deps, key=str)

    return missing, conflicting
703944
def isValidSemver(version):
    """"""
    if version and isinstance(version, string_types):
        try:
            semver.parse(version)
        except (TypeError,ValueError):
            return False
        else:
            return True
    return False
663157
def _exception_raise(self):
        
        exc = self.exc_info()[:]
        try:
            exc_type, exc_value, exc_traceback = exc
        except ValueError:
            exc_type, exc_value = exc
            exc_traceback = None

        # raise exc_type(exc_value).with_traceback(exc_traceback)
        if sys.version_info[0] == 2:
            exec("raise exc_type, exc_value, exc_traceback")
        else: #  sys.version_info[0] == 3:
            if isinstance(exc_value, Exception): #hasattr(exc_value, 'with_traceback'):
                # If exc_value is an exception, then just reraise
                exec("raise exc_value.with_traceback(exc_traceback)")
            else:
                # else we'll create an exception using the value and raise that
                exec("raise exc_type(exc_value).with_traceback(exc_traceback)")
561187
def validate_owner_repo_package(ctx, param, value):
    """"""
    # pylint: disable=unused-argument
    form = "OWNER/REPO/PACKAGE"
    return validate_slashes(param, value, minimum=3, maximum=3, form=form)
1005620
boolean isValidPackageName(String s) {
        if (s.contains("/")) {
            String[] a = s.split("/");
            if (a.length == 2) {
                 return isValidPackageName0(a[0]) && isValidPackageName0(a[1]);
            }
            return false;
        }
        return isValidPackageName0(s);
    }
1044690
def type(self, type):
        
        if type is None:
            raise ValueError("Invalid value for `type`, must not be `None`")
        allowed_values = ["reservation", "reservation_release", "reservation_termination", "package_renewal", "package_creation", "package_termination"]
        if type not in allowed_values:
            raise ValueError(
                "Invalid value for `type` ({0}), must be one of {1}"
                .format(type, allowed_values)
            )

        self._type = type
344667
def proper_case(package_name):
    """"""
    # Hit the simple API.
    r = _get_requests_session().get(
        "https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
    )
    if not r.ok:
        raise IOError(
            "Unable to find package {0} in PyPI repository.".format(package_name)
        )

    r = parse.parse("https://pypi.org/pypi/{name}/json", r.url)
    good_name = r["name"]
    return good_name
780401
function validatePackageInformation( $package, $http, $currentStepID, &$stepMap, &$persistentData, &$errorList )
    {
        $packageName = false;
        $packageSummary = false;
        $packageVersion = false;
        $packageDescription = false;
        $packageLicence = 'GPL';
        $packageHost = false;
        $packagePackager = false;
        if ( $http->hasPostVariable( 'PackageName' ) )
        {
            $packageName = trim( $http->postVariable( 'PackageName' ) );
        }
        if ( $http->hasPostVariable( 'PackageSummary' ) )
            $packageSummary = $http->postVariable( 'PackageSummary' );
        if ( $http->hasPostVariable( 'PackageDescription' ) )
            $packageDescription = $http->postVariable( 'PackageDescription' );
        if ( $http->hasPostVariable( 'PackageVersion' ) )
            $packageVersion = trim( $http->postVariable( 'PackageVersion' ) );
        if ( $http->hasPostVariable( 'PackageLicence' ) )
            $packageLicence = $http->postVariable( 'PackageLicence' );
        if ( $http->hasPostVariable( 'PackageHost' ) )
            $packageHost = $http->postVariable( 'PackageHost' );
        if ( $http->hasPostVariable( 'PackagePackager' ) )
            $packagePackager = $http->postVariable( 'PackagePackager' );

        $persistentData['name'] = $packageName;
        $persistentData['summary'] = $packageSummary;
        $persistentData['description'] = $packageDescription;
        $persistentData['version'] = $packageVersion;
        $persistentData['licence'] = $packageLicence;
        $persistentData['host'] = $packageHost;
        $persistentData['packager'] = $packagePackager;

        $result = true;
        if ( $packageName == '' )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Package name' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'Package name is missing' ) );
            $result = false;
        }
        else
        {
            $existingPackage = eZPackage::fetch( $packageName, false, true );
            if ( $existingPackage )
            {
                $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Package name' ),
                                      'description' => ezpI18n::tr( 'kernel/package', 'A package named %packagename already exists, please give another name', false, array( '%packagename' => $packageName ) ) );
                $result = false;
            }
            else
            {
                // Make sure the package name contains only valid characters
                $trans = eZCharTransform::instance();
                $validPackageName = $trans->transformByGroup( $packageName, 'identifier' );
                if ( strcmp( $validPackageName, $packageName ) != 0 )
                {
                    $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Package name' ),
                                          'description' => ezpI18n::tr( 'kernel/package', "The package name %packagename is not valid, it can only contain characters in the range a-z, 0-9 and underscore.", false, array( '%packagename' => $packageName ) ) );
                    $result = false;
                }
            }
        }
        if ( !$packageSummary )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Summary' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'Summary is missing' ) );
            $result = false;
        }
        if ( !preg_match( "#^[0-9](\.[0-9]([a-zA-Z]+[0-9]*)?)*$#", $packageVersion ) )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Version' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'The version must only contain numbers (optionally followed by text) and must be delimited by dots (.), e.g. 1.0, 3.4.0beta1' ) );
            $result = false;
        }
        return $result;
    }
689035
def prepare_package(err, path, expectation=0, for_appversions=None,
                    timeout=-1):
    

    package = None
    try:
        # Test that the package actually exists. I consider this Tier 0
        # since we may not even be dealing with a real file.
        if not os.path.isfile(path):
            err.error(('main', 'prepare_package', 'not_found'),
                      'The package could not be found')
            return

        # Pop the package extension.
        package_extension = os.path.splitext(path)[1]
        package_extension = package_extension.lower()

        def timeout_handler(signum, frame):
            raise validator.ValidationTimeout(timeout)

        if timeout != -1:
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.setitimer(signal.ITIMER_REAL, timeout)

        if package_extension == '.xml':
            test_search(err, path, expectation)
        elif package_extension not in ('.xpi', '.jar'):
            err.error(('main', 'prepare_package', 'unrecognized'),
                      'The package is not of a recognized type.')
        else:
            package = open(path, 'rb')
            test_package(err, package, path, expectation, for_appversions)

        err.metadata['is_extension'] = err.detected_type == PACKAGE_EXTENSION

    except validator.ValidationTimeout:
        err.system_error(
            msg_id='validation_timeout',
            message='Validation has timed out',
            signing_severity='high',
            description=('Validation was unable to complete in the allotted '
                         'time. This is most likely due to the size or '
                         'complexity of your add-on.',
                         'This timeout has been logged, but please consider '
                         'filing an issue report here: '
                         'https://bit.ly/1POrYYU'),
            exc_info=sys.exc_info())

    except Exception:
        err.system_error(exc_info=sys.exc_info())

    finally:
        # Remove timers and signal handlers regardless of whether
        # we've completed successfully or the timer has fired.
        if timeout != -1:
            signal.setitimer(signal.ITIMER_REAL, 0)
            signal.signal(signal.SIGALRM, signal.SIG_DFL)

        if package:
            package.close()

        decorator.cleanup()
113645
def _ensure_value_is_valid(self, value):
        """"""
        if not isinstance(value, self.__class__.value_type):
            raise TypeError('{0} is not valid collection value, instance '
                            'of {1} required'.format(
                                value, self.__class__.value_type))
        return value