mcanoglu/cwe-class-group huggingface dataset:
error_t tja1101Init(NetInterface *interface)
{
   uint16_t value;

   //Debug message
   TRACE_INFO("Initializing TJA1101...\r\n");

   //Undefined PHY address?
   if(interface->phyAddr >= 32)
   {
      //Use the default address
      interface->phyAddr = TJA1101_PHY_ADDR;
   }

   //Initialize serial management interface
   if(interface->smiDriver != NULL)
   {
      interface->smiDriver->init();
   }

   //Initialize external interrupt line driver
   if(interface->extIntDriver != NULL)
   {
      interface->extIntDriver->init();
   }

   //Reset PHY transceiver
   tja1101WritePhyReg(interface, TJA1101_BASIC_CTRL,
      TJA1101_BASIC_CTRL_RESET);

   //Wait for the reset to complete
   while(tja1101ReadPhyReg(interface, TJA1101_BASIC_CTRL) &
      TJA1101_BASIC_CTRL_RESET)
   {
   }

   //Dump PHY registers for debugging purpose
   tja1101DumpPhyReg(interface);

   //Enable configuration register access
   value = tja1101ReadPhyReg(interface, TJA1101_EXTENDED_CTRL);
   value |= TJA1101_EXTENDED_CTRL_CONFIG_EN;
   tja1101WritePhyReg(interface, TJA1101_EXTENDED_CTRL, value);

   //Select RMII mode (25MHz XTAL)
   value = tja1101ReadPhyReg(interface, TJA1101_CONFIG1);
   value &= ~TJA1101_CONFIG1_MII_MODE;
   value |= TJA1101_CONFIG1_MII_MODE_RMII_25MHZ;
   tja1101WritePhyReg(interface, TJA1101_CONFIG1, value);

   //The PHY is configured for autonomous operation
   value = tja1101ReadPhyReg(interface, TJA1101_COMM_CTRL);
   value |= TJA1101_COMM_CTRL_AUTO_OP;
   tja1101WritePhyReg(interface, TJA1101_COMM_CTRL, value);

   //Force the TCP/IP stack to poll the link state at startup
   interface->phyEvent = TRUE;
   //Notify the TCP/IP stack of the event
   osSetEvent(&netEvent);

   //Successful initialization
   return NO_ERROR;
}

// Vulnerability class: CWE-20
def check_password(password, encoded, setter=None, preferred='default'):
    """
    Returns a boolean of whether the raw password matches the three
    part encoded digest.

    If setter is specified, it'll be called when you need to
    regenerate the password.
    """
    if password is None or not is_password_usable(encoded):
        return False

    preferred = get_hasher(preferred)
    hasher = identify_hasher(encoded)

    must_update = hasher.algorithm != preferred.algorithm
    if not must_update:
        must_update = preferred.must_update(encoded)
    is_correct = hasher.verify(password, encoded)
    if setter and is_correct and must_update:
        setter(password)
    return is_correct

// Vulnerability class: CWE-200
def test_filename(self):
        tmpname = mktemp('', 'mmap')
        fp = memmap(tmpname, dtype=self.dtype, mode='w+',
                       shape=self.shape)
        abspath = os.path.abspath(tmpname)
        fp[:] = self.data[:]
        self.assertEqual(abspath, fp.filename)
        b = fp[:1]
        self.assertEqual(abspath, b.filename)
        del b
        del fp
        os.unlink(tmpname)

// Vulnerability class: CWE-20
def _expand(self, key_material):
        output = [b""]
        counter = 1

        while (self._algorithm.digest_size // 8) * len(output) < self._length:
            h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
            h.update(output[-1])
            h.update(self._info)
            h.update(six.int2byte(counter))
            output.append(h.finalize())
            counter += 1

        return b"".join(output)[:self._length]

// Vulnerability class: CWE-20
def _update_load_status(self, ok: bool) -> None:
        """Update the load status after a page finished loading.

        Needs to be called by subclasses to trigger a load status update, e.g.
        as a response to a loadFinished signal.
        """
        if ok and not self._has_ssl_errors:
            if self.url().scheme() == 'https':
                self._set_load_status(usertypes.LoadStatus.success_https)
            else:
                self._set_load_status(usertypes.LoadStatus.success)
        elif ok:
            self._set_load_status(usertypes.LoadStatus.warn)
        else:
            self._set_load_status(usertypes.LoadStatus.error)

// Vulnerability class: CWE-684
async def on_GET(self, origin, _content, query, context, user_id):
        """
        Args:
            origin (unicode): The authenticated server_name of the calling server

            _content (None): (GETs don't have bodies)

            query (dict[bytes, list[bytes]]): Query params from the request.

            **kwargs (dict[unicode, unicode]): the dict mapping keys to path
                components as specified in the path match regexp.

        Returns:
            Tuple[int, object]: (response code, response object)
        """
        versions = query.get(b"ver")
        if versions is not None:
            supported_versions = [v.decode("utf-8") for v in versions]
        else:
            supported_versions = ["1"]

        content = await self.handler.on_make_join_request(
            origin, context, user_id, supported_versions=supported_versions
        )
        return 200, content

// Vulnerability class: CWE-400
def testValuesInVariable(self):
    indices = constant_op.constant([[1]], dtype=dtypes.int64)
    values = variables.Variable([1], trainable=False, dtype=dtypes.float32)
    shape = constant_op.constant([1], dtype=dtypes.int64)

    sp_input = sparse_tensor.SparseTensor(indices, values, shape)
    sp_output = sparse_ops.sparse_add(sp_input, sp_input)

    with test_util.force_cpu():
      self.evaluate(variables.global_variables_initializer())
      output = self.evaluate(sp_output)
      self.assertAllEqual(output.values, [2])

// Vulnerability class: CWE-20
def skip(self, type):
        if type == TType.STOP:
            return
        elif type == TType.BOOL:
            self.readBool()
        elif type == TType.BYTE:
            self.readByte()
        elif type == TType.I16:
            self.readI16()
        elif type == TType.I32:
            self.readI32()
        elif type == TType.I64:
            self.readI64()
        elif type == TType.DOUBLE:
            self.readDouble()
        elif type == TType.FLOAT:
            self.readFloat()
        elif type == TType.STRING:
            self.readString()
        elif type == TType.STRUCT:
            name = self.readStructBegin()
            while True:
                (name, type, id) = self.readFieldBegin()
                if type == TType.STOP:
                    break
                self.skip(type)
                self.readFieldEnd()
            self.readStructEnd()
        elif type == TType.MAP:
            (ktype, vtype, size) = self.readMapBegin()
            for _ in range(size):
                self.skip(ktype)
                self.skip(vtype)
            self.readMapEnd()
        elif type == TType.SET:
            (etype, size) = self.readSetBegin()
            for _ in range(size):
                self.skip(etype)
            self.readSetEnd()
        elif type == TType.LIST:
            (etype, size) = self.readListBegin()
            for _ in range(size):
                self.skip(etype)
            self.readListEnd()

// Vulnerability class: CWE-755
def _new_fixed_fetch(validate_certificate):

    def fixed_fetch(
        url,
        payload=None,
        method="GET",
        headers={},
        allow_truncated=False,
        follow_redirects=True,
        deadline=None,
    ):
        return fetch(
            url,
            payload=payload,
            method=method,
            headers=headers,
            allow_truncated=allow_truncated,
            follow_redirects=follow_redirects,
            deadline=deadline,
            validate_certificate=validate_certificate,
        )

    return fixed_fetch

// Vulnerability class: CWE-400
def _parse_cache_control(headers):
    retval = {}
    if "cache-control" in headers:
        parts = headers["cache-control"].split(",")
        parts_with_args = [
            tuple([x.strip().lower() for x in part.split("=", 1)])
            for part in parts
            if -1 != part.find("=")
        ]
        parts_wo_args = [
            (name.strip().lower(), 1) for name in parts if -1 == name.find("=")
        ]
        retval = dict(parts_with_args + parts_wo_args)
    return retval

// Vulnerability class: CWE-400
def _updateCache(request_headers, response_headers, content, cache, cachekey):
    if cachekey:
        cc = _parse_cache_control(request_headers)
        cc_response = _parse_cache_control(response_headers)
        if "no-store" in cc or "no-store" in cc_response:
            cache.delete(cachekey)
        else:
            info = email.message.Message()
            for key, value in response_headers.items():
                if key not in ["status", "content-encoding", "transfer-encoding"]:
                    info[key] = value

            # Add annotations to the cache to indicate what headers
            # are variant for this request.
            vary = response_headers.get("vary", None)
            if vary:
                vary_headers = vary.lower().replace(" ", "").split(",")
                for header in vary_headers:
                    key = "-varied-%s" % header
                    try:
                        info[key] = request_headers[header]
                    except KeyError:
                        pass

            status = response_headers.status
            if status == 304:
                status = 200

            status_header = "status: %d\r\n" % status

            try:
                header_str = info.as_string()
            except UnicodeEncodeError:
                setattr(info, "_write_headers", _bind_write_headers(info))
                header_str = info.as_string()

            header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
            text = b"".join(
                [status_header.encode("utf-8"), header_str.encode("utf-8"), content]
            )

            cache.set(cachekey, text)

// Vulnerability class: CWE-400
def test_digest_object():
    credentials = ("joe", "password")
    host = None
    request_uri = "/test/digest/"
    headers = {}
    response = {
        "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'
    }
    content = b""

    d = httplib2.DigestAuthentication(
        credentials, host, request_uri, headers, response, content, None
    )
    d.request("GET", request_uri, headers, content, cnonce="33033375ec278a46")
    our_request = "authorization: " + headers["authorization"]
    working_request = (
        'authorization: Digest username="joe", realm="myrealm", '
        'nonce="KBAA=35", uri="/test/digest/"'
        + ', algorithm=MD5, response="de6d4a123b80801d0e94550411b6283f", '
        'qop=auth, nc=00000001, cnonce="33033375ec278a46"'
    )
    assert our_request == working_request

// Vulnerability class: CWE-400
def parse_jwt_token(request: func.HttpRequest) -> Result[UserInfo]:
    """Obtains the Access Token from the Authorization Header"""
    token_str = get_auth_token(request)
    if token_str is None:
        return Error(
            code=ErrorCode.INVALID_REQUEST,
            errors=["unable to find authorization token"],
        )

    # This token has already been verified by the azure authentication layer
    token = jwt.decode(token_str, options={"verify_signature": False})

    application_id = UUID(token["appid"]) if "appid" in token else None
    object_id = UUID(token["oid"]) if "oid" in token else None
    upn = token.get("upn")
    return UserInfo(application_id=application_id, object_id=object_id, upn=upn)

// Vulnerability class: CWE-346
def main() -> None:
    formatter = argparse.ArgumentDefaultsHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=formatter)
    parser.add_argument("resource_group")
    parser.add_argument("storage_account")
    parser.add_argument("admins", type=UUID, nargs="*")
    args = parser.parse_args()

    client = get_client_from_cli_profile(StorageManagementClient)
    storage_keys = client.storage_accounts.list_keys(
        args.resource_group, args.storage_account
    )
    table_service = TableService(
        account_name=args.storage_account, account_key=storage_keys.keys[0].value
    )
    update_admins(table_service, args.resource_group, args.admins)

// Vulnerability class: CWE-285
def test_bad_request(settings):
    class BadRequestSpider(ResponseSpider):
        custom_settings = {'HTTPERROR_ALLOW_ALL': True}

        def start_requests(self):
            yield SplashRequest(self.url, endpoint='execute',
                                args={'lua_source': DEFAULT_SCRIPT, 'wait': 'bar'})

    class GoodRequestSpider(ResponseSpider):
        custom_settings = {'HTTPERROR_ALLOW_ALL': True}

        def start_requests(self):
            yield SplashRequest(self.url, endpoint='execute',
                                args={'lua_source': DEFAULT_SCRIPT})


    items, url, crawler = yield crawl_items(BadRequestSpider, HelloWorld,
                                            settings)
    resp = items[0]['response']
    assert resp.status == 400
    assert resp.splash_response_status == 400

    items, url, crawler = yield crawl_items(GoodRequestSpider, Http400Resource,
                                            settings)
    resp = items[0]['response']
    assert resp.status == 400
    assert resp.splash_response_status == 200

// Vulnerability class: CWE-200
def test_adjust_timeout():
    mw = _get_mw()
    req1 = scrapy.Request("http://example.com", meta = {
        'splash': {'args': {'timeout': 60, 'html': 1}},

        # download_timeout is always present,
        # it is set by DownloadTimeoutMiddleware
        'download_timeout': 30,
    })
    req1 = mw.process_request(req1, None)
    assert req1.meta['download_timeout'] > 60

    req2 = scrapy.Request("http://example.com", meta = {
        'splash': {'args': {'html': 1}},
        'download_timeout': 30,
    })
    req2 = mw.process_request(req2, None)
    assert req2.meta['download_timeout'] == 30

// Vulnerability class: CWE-200
def render_GET(self, request):
        request.setHeader(b'content-type', to_bytes(self.content_type))
        for name, value in self.extra_headers.items():
            request.setHeader(to_bytes(name), to_bytes(value))
        request.setResponseCode(self.status_code)
        return to_bytes(self.html)

// Vulnerability class: CWE-200
def test_session_with_cookie_followed_by_another_header(self, httpbin):
        """
        Make sure headers don’t get mutated — <https://github.com/httpie/httpie/issues/1126>
        """
        self.start_session(httpbin)
        session_data = {
            "headers": {
                "cookie": "...",
                "zzz": "..."
            }
        }
        session_path = self.config_dir / 'session-data.json'
        session_path.write_text(json.dumps(session_data))
        r = http('--session', str(session_path), 'GET', httpbin.url + '/get',
                 env=self.env())
        assert HTTP_OK in r
        assert 'Zzz' in r

// Vulnerability class: CWE-200
def needs_clamp(t, encoding):
    if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
        return False
    if isinstance(t, (ByteArrayLike, DArrayType)):
        if encoding == Encoding.JSON_ABI:
            # don't have bytestring size bound from json, don't clamp
            return False
        return True
    if isinstance(t, BaseType) and t.typ not in ("int256", "uint256", "bytes32"):
        return True
    if isinstance(t, SArrayType):
        return needs_clamp(t.subtype, encoding)
    if isinstance(t, TupleLike):
        return any(needs_clamp(m, encoding) for m in t.tuple_members())
    return False

// Vulnerability class: CWE-119
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String encoding = request.getHeader("Accept-Encoding");
        boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
        SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
        if (st == null || st.isClosed()) {
            st = new SessionTerminal(getCommandProcessor(), getThreadIO());
            request.getSession().setAttribute("terminal", st);
        }
        String str = request.getParameter("k");
        String f = request.getParameter("f");
        String dump = st.handle(str, f != null && f.length() > 0);
        if (dump != null) {
            if (supportsGzip) {
                response.setHeader("Content-Encoding", "gzip");
                response.setHeader("Content-Type", "text/html");
                try {
                    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                    gzos.write(dump.getBytes());
                    gzos.close();
                } catch (IOException ie) {
                    LOG.info("Exception writing response: ", ie);
                }
            } else {
                response.getOutputStream().write(dump.getBytes());
            }
        }
    }

// Vulnerability class: CWE-287
protected ObjectStreamClass readClassDescriptor()
            throws IOException, ClassNotFoundException {
        int type = read();
        if (type < 0) {
            throw new EOFException();
        }
        switch (type) {
            case ThrowableObjectOutputStream.TYPE_EXCEPTION:
                return ObjectStreamClass.lookup(Exception.class);
            case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
                return ObjectStreamClass.lookup(StackTraceElement.class);
            case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
                return super.readClassDescriptor();
            case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
                String className = readUTF();
                Class<?> clazz = loadClass(className);
                return ObjectStreamClass.lookup(clazz);
            default:
                throw new StreamCorruptedException(
                        "Unexpected class descriptor type: " + type);
        }
    }

// Vulnerability class: CWE-74
public static SecretKey decryptCEK(final SecretKey kek,
					   final byte[] iv,
					   final AuthenticatedCipherText authEncrCEK,
					   final int keyLength,
					   final Provider provider)
		throws JOSEException {

		byte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider);

		if (ByteUtils.bitLength(keyBytes) != keyLength) {

			throw new KeyLengthException("CEK key length mismatch: " + ByteUtils.bitLength(keyBytes) + " != " + keyLength);
		}

		return new SecretKeySpec(keyBytes, "AES");
	}

// Vulnerability class: CWE-345
private String loginUser(URI hostUri) throws Throwable {
        URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
        // wait for factory availability
        this.host.waitForReplicatedFactoryServiceAvailable(usersLink);

        String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
        URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
        AuthenticationRequest login = new AuthenticationRequest();
        login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;

        String[] authToken = new String[1];
        authToken[0] = null;

        Date exp = this.host.getTestExpiration();
        while (new Date().before(exp)) {
            Operation loginPost = Operation.createPost(loginUri)
                    .setBody(login)
                    .addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
                    .forceRemote()
                    .setCompletion((op, ex) -> {
                        if (ex != null) {
                            this.host.completeIteration();
                            return;
                        }
                        authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
                        this.host.completeIteration();
                    });

            this.host.testStart(1);
            this.host.send(loginPost);
            this.host.testWait();

            if (authToken[0] != null) {
                break;
            }
            Thread.sleep(250);
        }

        if (new Date().after(exp)) {
            throw new TimeoutException();
        }

        assertNotNull(authToken[0]);

        return authToken[0];
    }

// Vulnerability class: CWE-732
private void displayVerificationWarningDialog(final Contact contact, final Invite invite) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.verify_omemo_keys);
		View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
		final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
		TextView warning = view.findViewById(R.id.warning);
		warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName()));
		builder.setView(view);
		builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
			if (isTrustedSource.isChecked() && invite.hasFingerprints()) {
				xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
			}
			switchToConversation(contact, invite.getBody());
		});
		builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());
		AlertDialog dialog = builder.create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());
		dialog.show();
	}

// Vulnerability class: CWE-200
public void checkAccess(ThreadGroup g) {
		if (RobocodeProperties.isSecurityOff()) {
			return;
		}
		Thread c = Thread.currentThread();

		if (isSafeThread(c)) {
			return;
		}
		super.checkAccess(g);

		final ThreadGroup cg = c.getThreadGroup();

		if (cg == null) {
			// What the heck is going on here?  JDK 1.3 is sending me a dead thread.
			// This crashes the entire jvm if I don't return here.
			return;
		}

		// Bug fix #382 Unable to run robocode.bat -- Access Control Exception
		if ("SeedGenerator Thread".equals(c.getName()) && "SeedGenerator ThreadGroup".equals(cg.getName())) {
			return; // The SeedGenerator might create a thread, which needs to be silently ignored
		}
		
		IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);

		if (robotProxy == null) {
			throw new AccessControlException("Preventing " + c.getName() + " from access to " + g.getName());			
		}

		if (cg.activeCount() > 5) {
			String message = "Robots are only allowed to create up to 5 threads!";

			robotProxy.punishSecurityViolation(message);
			throw new AccessControlException(message);
		}
	}

// Vulnerability class: CWE-862
final void set(CharSequence name, String value) {
        final AsciiString normalizedName = normalizeName(name);
        requireNonNull(value, "value");
        final int h = normalizedName.hashCode();
        final int i = index(h);
        remove0(h, i, normalizedName);
        add0(h, i, normalizedName, value);
    }

// Vulnerability class: CWE-74
public void removingANameForASecondTimeShouldReturnFalse() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");
        headers.add("name2", "value2");
        assertThat(headers.remove("name2")).isTrue();
        assertThat(headers.remove("name2")).isFalse();
    }

// Vulnerability class: CWE-74
public void subsetOfHeadersShouldNotBeEquivalent() {
        final HttpHeadersBase headers1 = newEmptyHeaders();
        headers1.add("name1", "value1");
        headers1.add("name2", "value2");
        final HttpHeadersBase headers2 = newEmptyHeaders();
        headers1.add("name1", "value1");
        assertThat(headers1).isNotEqualTo(headers2);
    }

// Vulnerability class: CWE-74
public void testCopy() throws Exception {
        HttpHeadersBase headers = newEmptyHeaders();
        headers.addLong("long", Long.MAX_VALUE);
        headers.addInt("int", Integer.MIN_VALUE);
        headers.addDouble("double", Double.MAX_VALUE);
        headers.addFloat("float", Float.MAX_VALUE);
        final long millis = System.currentTimeMillis();
        headers.addTimeMillis("millis", millis);
        headers.addObject("object", "Hello World");
        headers.add("name", "value");

        final HttpHeadersBase oldHeaders = headers;
        headers = newEmptyHeaders();
        headers.add(oldHeaders);

        assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
        assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();

        assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
        assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();

        assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
        assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();

        assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
        assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();

        assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
        // This test doesn't work on midnight, January 1, 1970 UTC
        assertThat(headers.containsTimeMillis("millis", 0)).isFalse();

        assertThat(headers.containsObject("object", "Hello World")).isTrue();
        assertThat(headers.containsObject("object", "")).isFalse();

        assertThat(headers.contains("name", "value")).isTrue();
        assertThat(headers.contains("name", "value1")).isFalse();
    }

// Vulnerability class: CWE-74
public void multipleTestingOfSameClass() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
            .isEmpty();
        assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
            .isEmpty();
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .isEmpty();
    }

// Vulnerability class: CWE-74
public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException,
          NotFoundException {
    SearchResult result;
    try {
      result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId));
      if (result.getItems().length == 0) {
        logger.warn(
                "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.",
                mediaPackageId);
        return false;
      }
      logger.info("Removing mediapackage {} from search index", mediaPackageId);

      Date now = new Date();
      try {
        persistence.deleteMediaPackage(mediaPackageId, now);
        logger.info("Removed mediapackage {} from search persistence", mediaPackageId);
      } catch (NotFoundException e) {
        // even if mp not found in persistence, it might still exist in search index.
        logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.",
                mediaPackageId);
      } catch (SearchServiceDatabaseException e) {
        logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId);
        throw new SearchException(e);
      }

      return indexManager.delete(mediaPackageId, now);
    } catch (SolrServerException e) {
      logger.info("Could not delete media package with id {} from search index", mediaPackageId);
      throw new SearchException(e);
    }
  }

// Vulnerability class: CWE-863
public boolean isValid(String value, ConstraintValidatorContext context) {
      long longValue = 0;
      boolean failed = false;
      String errorMessage = "";
      try {
        longValue = Long.parseLong(value);
      } catch (NumberFormatException ex) {
        failed = true;
        errorMessage = String.format("Invalid integer value: '%s'", value);
      }

      if (!failed && longValue < 0) {
        failed = true;
        errorMessage = String.format("Expected positive integer value, got: '%s'", value);
      }

      if (!failed) {
        return true;
      }

      LOG.warn(errorMessage);
      context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();

      return false;
    }

// Vulnerability class: CWE-74
public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() throws Exception {
        Modification lastCommit = hgCommand.latestOneModificationAsModifications().get(0);

        makeACommitToSecondBranch();
        hg(workingDirectory, "pull").runOrBomb(null);
        Modification actual = hgCommand.latestOneModificationAsModifications().get(0);
        assertThat(actual, is(lastCommit));
        assertThat(actual.getComment(), is(lastCommit.getComment()));
    }

// Vulnerability class: CWE-77
error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,
   size_t offset, NetTxAncillary *ancillary)
{
   error_t error;
   bool_t status;

   //Gather entropy
   netContext.entropy += netGetSystemTickCount();

#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
   //Retrieve the length of the packet
   size_t length = netBufferGetLength(buffer) - offset;

   //Debug message
   TRACE_DEBUG("Sending packet (%" PRIuSIZE " bytes)...\r\n", length);
   TRACE_DEBUG_NET_BUFFER("  ", buffer, offset, length);
#endif

   //Check whether the interface is enabled for operation
   if(interface->configured && interface->nicDriver != NULL)
   {
      //Loopback interface?
      if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)
      {
         //The loopback interface is always available
         status = TRUE;
      }
      else
      {
         //Wait for the transmitter to be ready to send
         status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);
      }

      //Check whether the specified event is in signaled state
      if(status)
      {
         //Disable interrupts
         interface->nicDriver->disableIrq(interface);

         //Send the packet
         error = interface->nicDriver->sendPacket(interface, buffer, offset,
            ancillary);

         //Re-enable interrupts if necessary
         if(interface->configured)
         {
            interface->nicDriver->enableIrq(interface);
         }
      }
      else
      {
         //If the transmitter is busy, then drop the packet
         error = NO_ERROR;
      }
   }
   else
   {
      //Report an error
      error = ERROR_INVALID_INTERFACE;
   }

   //Return status code
   return error;
}

// Vulnerability class: CWE-20
private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
        String parent) throws XWikiException
    {
        XWiki xwiki = context.getWiki();
        DocumentReferenceResolver<String> resolver = getCurrentMixedDocumentReferenceResolver();

        // Set the locale and default locale, considering that we're creating the original version of the document
        // (not a translation).
        newDocument.setLocale(Locale.ROOT);
        if (newDocument.getDefaultLocale() == Locale.ROOT) {
            newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
        }

        // Copy the template.
        DocumentReference templateReference = resolver.resolve(template);
        newDocument.readFromTemplate(templateReference, context);

        // Set the parent field.
        if (!StringUtils.isEmpty(parent)) {
            DocumentReference parentReference = resolver.resolve(parent);
            newDocument.setParentReference(parentReference);
        }

        // Set the document title
        if (title != null) {
            newDocument.setTitle(title);
        }

        // Set the author and creator.
        DocumentReference currentUserReference = context.getUserReference();
        newDocument.setAuthorReference(currentUserReference);
        newDocument.setCreatorReference(currentUserReference);

        // Make sure the user is allowed to make this modification
        xwiki.checkSavingDocument(currentUserReference, newDocument, context);

        xwiki.saveDocument(newDocument, context);
    }

// Vulnerability class: CWE-862
public void existingDocumentFromUIDeprecated() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI space=X&page=Y
        when(mockRequest.getParameter("space")).thenReturn("X");
        when(mockRequest.getParameter("page")).thenReturn("Y");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating X.Y since the deprecated parameters were creating terminal documents by default.
        verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
            context);
    }

// Vulnerability class: CWE-862
public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExists() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        String spaceReferenceString = "X";
        when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
        when(mockRequest.getParameter("name")).thenReturn("Y");
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

        // Mock 1 existing template provider that allows usage in target space.
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Arrays.asList("X"));

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note1: We are allowed to create anything under space X, be it a terminal or a non-terminal document.
        // Note2: We are creating X.Y and using the template extracted from the template provider.
        verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
            "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
    }

// Vulnerability class: CWE-862
public String invokeServletAndReturnAsString(String url, XWikiContext xwikiContext)
    {

        HttpServletRequest servletRequest = xwikiContext.getRequest();
        HttpServletResponse servletResponse = xwikiContext.getResponse();

        try {
            return IncludeServletAsString.invokeServletAndReturnAsString(url, servletRequest, servletResponse);
        } catch (Exception e) {
            LOGGER.warn("Exception including url: " + url, e);
            return "Exception including \"" + url + "\", see logs for details.";
        }

    }

// Vulnerability class: CWE-862
public void translate(ServerEntityHeadLookPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }

        if (entity == null) return;

        entity.updateHeadLookRotation(session, packet.getHeadYaw());
    }

// Vulnerability class: CWE-287
public void translate(ServerPlayerActionAckPacket packet, GeyserSession session) {
        ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition());
        if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) {
            LevelEventPacket stopBreak = new LevelEventPacket();
            stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK);
            stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
            stopBreak.setData(0);
            session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID);
            session.sendUpstreamPacket(stopBreak);
        }
    }

// Vulnerability class: CWE-287
public void translate(ServerSetSubtitleTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.SUBTITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }

// Vulnerability class: CWE-287
public void translate(ServerSetTitleTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.TITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }

// Vulnerability class: CWE-287
public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (entity == null) {
            return;
        }

        UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();
        updateEquipPacket.setWindowId((short) packet.getWindowId());
        updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());
        updateEquipPacket.setUniqueEntityId(entity.getGeyserId());

        NbtMapBuilder builder = NbtMap.builder();
        List<NbtMap> slots = new ArrayList<>();

        InventoryTranslator inventoryTranslator;
        if (entity instanceof LlamaEntity) {
            inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());
            slots.add(CARPET_SLOT);
        } else if (entity instanceof ChestedHorseEntity) {
            inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
        } else {
            inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
            slots.add(ARMOR_SLOT);
        }

        // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)
        builder.putList("slots", NbtType.COMPOUND, slots);

        updateEquipPacket.setTag(builder.build());
        session.sendUpstreamPacket(updateEquipPacket);

        session.setInventoryTranslator(inventoryTranslator);
        InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));
    }

// Vulnerability class: CWE-287
private static boolean validateChainData(JsonNode data) throws Exception {
        ECPublicKey lastKey = null;
        boolean validChain = false;
        for (JsonNode node : data) {
            JWSObject jwt = JWSObject.parse(node.asText());

            if (!validChain) {
                validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
            }

            if (lastKey != null) {
                if (!EncryptionUtils.verifyJwt(jwt, lastKey)) return false;
            }

            JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());
            JsonNode ipkNode = payloadNode.get("identityPublicKey");
            Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
            lastKey = EncryptionUtils.generateKey(ipkNode.asText());
        }
        return validChain;
    }

// Vulnerability class: CWE-287
setImmediate(() => {
            if (!this.pendingPublishRequestCount) {
                return;
            }
            const starving_subscription = this._find_starving_subscription();
            if (starving_subscription) {
                doDebug && debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId  = "), starving_subscription.id);
                starving_subscription.process_subscription();
            }
        });

// Vulnerability class: CWE-400
public DataSource createNewDataSource(Map<String, ?> params) throws IOException {
        String refName = (String) JNDI_REFNAME.lookUp(params);
        try {
            return (DataSource) GeoTools.getInitialContext().lookup(refName);
        } catch (Exception e) {
            throw new DataSourceException("Could not find the specified data source in JNDI", e);
        }
    }

// Vulnerability class: CWE-20
protected DataSource createDataSource() throws SQLException {
        InitialContext context = null;
        DataSource source = null;
        try {
            context = GeoTools.getInitialContext();
            source = (DataSource) context.lookup(datasourceName);
        } catch (IllegalArgumentException | NoInitialContextException exception) {
            // Fall back on 'return null' below.
        } catch (NamingException exception) {
            registerInto = context;
            // Fall back on 'return null' below.
        }
        return source;
    }

// Vulnerability class: CWE-20
static int intel_pmu_handle_irq(struct pt_regs *regs)
{
	struct perf_sample_data data;
	struct cpu_hw_events *cpuc;
	int bit, loops;
	u64 status;
	int handled;

	perf_sample_data_init(&data, 0);

	cpuc = &__get_cpu_var(cpu_hw_events);

	/*
	 * Some chipsets need to unmask the LVTPC in a particular spot
	 * inside the nmi handler.  As a result, the unmasking was pushed
	 * into all the nmi handlers.
	 *
	 * This handler doesn't seem to have any issues with the unmasking
	 * so it was left at the top.
	 */
	apic_write(APIC_LVTPC, APIC_DM_NMI);

	intel_pmu_disable_all();
	handled = intel_pmu_drain_bts_buffer();
	status = intel_pmu_get_status();
	if (!status) {
		intel_pmu_enable_all(0);
		return handled;
	}

	loops = 0;
again:
	intel_pmu_ack_status(status);
	if (++loops > 100) {
		WARN_ONCE(1, "perfevents: irq loop stuck!\n");
		perf_event_print_debug();
		intel_pmu_reset();
		goto done;
	}

	inc_irq_stat(apic_perf_irqs);

	intel_pmu_lbr_read();

	/*
	 * PEBS overflow sets bit 62 in the global status register
	 */
	if (__test_and_clear_bit(62, (unsigned long *)&status)) {
		handled++;
		x86_pmu.drain_pebs(regs);
	}

	for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
		struct perf_event *event = cpuc->events[bit];

		handled++;

		if (!test_bit(bit, cpuc->active_mask))
			continue;

		if (!intel_pmu_save_and_restart(event))
			continue;

		data.period = event->hw.last_period;

		if (perf_event_overflow(event, 1, &data, regs))
			x86_pmu_stop(event, 0);
	}

	/*
	 * Repeat if there is more work to be done:
	 */
	status = intel_pmu_get_status();
	if (status)
		goto again;

done:
	intel_pmu_enable_all(0);
	return handled;
}

// Vulnerability class: CWE-400
mptctl_fw_download(unsigned long arg)
{
	struct mpt_fw_xfer __user *ufwdl = (void __user *) arg;
	struct mpt_fw_xfer	 kfwdl;

	if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {
		printk(KERN_ERR MYNAM "%s@%d::_ioctl_fwdl - "
				"Unable to copy mpt_fw_xfer struct @ %p\n",
				__FILE__, __LINE__, ufwdl);
		return -EFAULT;
	}

	return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);
}

// Vulnerability class: CWE-362
compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,
			unsigned long arg)
{
	struct mpt_fw_xfer32 kfw32;
	struct mpt_fw_xfer kfw;
	MPT_ADAPTER *iocp = NULL;
	int iocnum, iocnumX;
	int nonblock = (filp->f_flags & O_NONBLOCK);
	int ret;


	if (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))
		return -EFAULT;

	/* Verify intended MPT adapter */
	iocnumX = kfw32.iocnum & 0xFF;
	if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
	    (iocp == NULL)) {
		printk(KERN_DEBUG MYNAM "::compat_mptfwxfer_ioctl @%d - ioc%d not found!\n",
			__LINE__, iocnumX);
		return -ENODEV;
	}

	if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
		return ret;

	dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mptfwxfer_ioctl() called\n",
	    iocp->name));
	kfw.iocnum = iocnum;
	kfw.fwlen = kfw32.fwlen;
	kfw.bufp = compat_ptr(kfw32.bufp);

	ret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);

	mutex_unlock(&iocp->ioctl_cmds.mutex);

	return ret;
}

// Vulnerability class: CWE-362
inline typename V::VectorType FBUnserializer<V>::unserializeList() {
  p_ += CODE_SIZE;

  // the list size is written so we can reserve it in the vector
  // in future. Skip past it for now.
  unserializeInt64();

  typename V::VectorType ret = V::createVector();

  size_t code = nextCode();
  while (code != FB_SERIALIZE_STOP) {
    V::vectorAppend(ret, unserializeThing());
    code = nextCode();
  }
  p_ += CODE_SIZE;
  return ret;
}

// Vulnerability class: CWE-674
static Variant HHVM_FUNCTION(simplexml_import_dom,
  const Object& node,
  const String& class_name /* = "SimpleXMLElement" */) {
  auto domnode = Native::data<DOMNode>(node);
  xmlNodePtr nodep = domnode->nodep();

  if (nodep) {
    if (nodep->doc == nullptr) {
      raise_warning("Imported Node must have associated Document");
      return init_null();
    }
    if (nodep->type == XML_DOCUMENT_NODE ||
        nodep->type == XML_HTML_DOCUMENT_NODE) {
      nodep = xmlDocGetRootElement((xmlDocPtr) nodep);
    }
  }

  if (nodep && nodep->type == XML_ELEMENT_NODE) {
    auto cls = class_from_name(class_name, "simplexml_import_dom");
    if (!cls) {
      return init_null();
    }
    Object obj = create_object(cls->nameStr(), Array(), false);
    auto sxe = Native::data<SimpleXMLElement>(obj.get());
    sxe->node = libxml_register_node(nodep);
    return obj;
  } else {
    raise_warning("Invalid Nodetype to import");
    return init_null();
  }
  return false;
}

// Vulnerability class: CWE-345