code
stringlengths
31
2.05k
label_name
stringclasses
5 values
label
int64
0
4
public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }
Base
1
public void setSort(Integer sort) { this.sort = sort; }
Base
1
public void setId(Integer id) { this.id = id; }
Base
1
public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; }
Base
1
public Long getUpdateUserId() { return updateUserId; }
Base
1
public String getLinkUrl() { return linkUrl; }
Base
1
public Integer getSort() { return sort; }
Base
1
public Long getCreateUserId() { return createUserId; }
Base
1
public void setIsOpen(Integer isOpen) { this.isOpen = isOpen; }
Base
1
public void setCreateTime(Date createTime) { this.createTime = createTime; }
Base
1
public static CBORObject RandomCBORMap(IRandomGenExtended rand, int depth) { int x = rand.GetInt32(100); int count = (x < 80) ? 2 : ((x < 93) ? 1 : ((x < 98) ? 0 : 10)); CBORObject cborRet = CBORObject.NewMap(); for (var i = 0; i < count; ++i) { CBORObject key = RandomCBORObject(rand...
Class
2
private static bool ByteArraysEqual(byte[] arr1, byte[] arr2) { if (arr1 == null) { return arr2 == null; } if (arr2 == null) { return false; } if (arr1.Length != arr2.Length) { return false; } for (var i = 0; i < arr1.Length; ++i) { if (arr1[...
Class
2
def _configure_templating(cls, app): tempdir = app.config["PYLOAD_API"].get_cachedir() cache_path = os.path.join(tempdir, "jinja") os.makedirs(cache_path, exist_ok=True) app.create_jinja_environment() # NOTE: enable autoescape for all file extensions (included .js) ...
Base
1
def _configure_handlers(cls, app): """ Register error handlers. """ for exc, fn in cls.FLASK_ERROR_HANDLERS: app.register_error_handler(exc, fn)
Base
1
def get_events(self, uuid): """ Lists occured events, may be affected to changes in future. :param uuid: :return: list of `Events` """ events = self.pyload.event_manager.get_events(uuid) new_events = [] def conv_dest(d): return (Destinati...
Base
1
def is_authenticated(session=flask.session): return session.get("name") and session.get( "authenticated" ) # NOTE: why checks name?
Base
1
def cast(self, typ, value): """ cast value to given format. """ if typ == "int": return int(value) elif typ == "float": return float(value) elif typ == "str": return "" if value is None else str(value) elif typ == "bytes"...
Class
2
def init_handle(self): """ sets common options to curl handle. """ self.c.setopt(pycurl.FOLLOWLOCATION, 1) self.c.setopt(pycurl.MAXREDIRS, 10) self.c.setopt(pycurl.CONNECTTIMEOUT, 30) self.c.setopt(pycurl.NOSIGNAL, 1) self.c.setopt(pycurl.NOPROGRESS, 1...
Base
1
def login(): user = flask.request.form["username"] password = flask.request.form["password"] api = flask.current_app.config["PYLOAD_API"] user_info = api.check_auth(user, password) if not user_info: log.error(f"Login failed for user '{user}'") return jsonify(False) s = set_ses...
Class
2
def login(): api = flask.current_app.config["PYLOAD_API"] next = get_redirect_url(fallback=flask.url_for("app.dashboard")) if flask.request.method == "POST": user = flask.request.form["username"] password = flask.request.form["password"] user_info = api.check_auth(user, password) ...
Class
2
def _configure_session(cls, app): tempdir = app.config["PYLOAD_API"].get_cachedir() cache_path = os.path.join(tempdir, "flask") os.makedirs(cache_path, exist_ok=True) app.config["SESSION_FILE_DIR"] = cache_path app.config["SESSION_TYPE"] = "filesystem" app.config["SE...
Compound
4
def get_throttles(self): throttles = super().get_throttles() if self.action == "reset_password": throttles.append(PasswordResetRequestThrottle()) return throttles
Class
2
def clean_identity(self): v = self.cleaned_data["identity"] if len(v) > 254: raise forms.ValidationError("Address is too long.") if User.objects.filter(email=v).exists(): raise forms.ValidationError( "An account with this email address already exists....
Base
1
def test_it_checks_for_existing_users(self): alice = User(username="alice", email="alice@example.org") alice.save() form = {"identity": "alice@example.org", "tz": ""} r = self.client.post("/accounts/signup/", form) self.assertContains(r, "already exists")
Base
1
def test_it_ignores_bad_tz(self): form = {"identity": "alice@example.org", "tz": "Foo/Bar"} r = self.client.post("/accounts/signup/", form) self.assertContains(r, "Account created") self.assertIn("auto-login", r.cookies) profile = Profile.objects.get() self.assertEq...
Base
1
def test_it_works(self): form = {"identity": "alice@example.org", "tz": "Europe/Riga"} r = self.client.post("/accounts/signup/", form) self.assertContains(r, "Account created") self.assertIn("auto-login", r.cookies) # An user should have been created user = User.obj...
Base
1
def login(request): form = forms.PasswordLoginForm() magic_form = forms.EmailLoginForm() if request.method == "POST": if request.POST.get("action") == "login": form = forms.PasswordLoginForm(request.POST) if form.is_valid(): return _check_2fa(request, form.us...
Base
1
def signup(request): if not settings.REGISTRATION_OPEN: return HttpResponseForbidden() ctx = {} form = forms.SignupForm(request.POST) if form.is_valid(): email = form.cleaned_data["identity"] tz = form.cleaned_data["tz"] user = _make_user(email, tz) profile = Pro...
Base
1
def _validate_source(source: str, run_id: str) -> None: if not is_local_uri(source): return if run_id: store = _get_tracking_store() run = store.get_run(run_id) source = pathlib.Path(local_file_uri_to_path(source)).resolve() run_artifact_dir = pathlib.Path(local_file_uri...
Variant
0
def is_local_uri(uri): """Returns true if this is a local file path (/foo or file:/foo).""" if uri == "databricks": return False if is_windows() and uri.startswith("\\\\"): # windows network drive path looks like: "\\<server name>\path\..." return False parsed_uri = urllib.pars...
Variant
0
def _init_server(backend_uri, root_artifact_uri): """ Launch a new REST server using the tracking store specified by backend_uri and root artifact directory specified by root_artifact_uri. :returns A tuple (url, process) containing the string URL of the server and a handle to the server pro...
Variant
0
def test_create_model_version_with_path_source(mlflow_client): name = "mode" mlflow_client.create_registered_model(name) exp_id = mlflow_client.create_experiment("test") run = mlflow_client.create_run(experiment_id=exp_id) response = requests.post( f"{mlflow_client.tracking_uri}/api/2.0/mlf...
Base
1
def predict(self, model_uri, input_path, output_path, content_type): """ Generate predictions using generic python model saved with MLflow. The expected format of the input JSON is the Mlflow scoring format. Return the prediction results as a JSON. """ local_path = _d...
Base
1
def predict(self, model_uri, input_path, output_path, content_type): """ Generate predictions using generic python model saved with MLflow. The expected format of the input JSON is the Mlflow scoring format. Return the prediction results as a JSON. """ local_path = _d...
Base
1
def get_cmd( model_uri: str, port: int = None, host: int = None, timeout: int = None, nworkers: int = None ) -> Tuple[str, Dict[str, str]]: local_uri = path_to_local_file_uri(model_uri) timeout = timeout or MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT.get() # NB: Absolute windows paths do not work with mlflow ...
Base
1
def get_cmd( model_uri: str, port: int = None, host: int = None, timeout: int = None, nworkers: int = None ) -> Tuple[str, Dict[str, str]]: local_uri = path_to_local_file_uri(model_uri) timeout = timeout or MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT.get() # NB: Absolute windows paths do not work with mlflow ...
Base
1
def create_user(): content_type = request.headers.get("Content-Type") if content_type == "application/x-www-form-urlencoded": username = request.form["username"] password = request.form["password"] if store.has_user(username): flash(f"Username has already been taken: {userna...
Base
1
def to_html(self) -> str: """ Returns a rendered HTML representing the content of the tab. :return: a HTML string """ import jinja2 j2_env = jinja2.Environment(loader=jinja2.BaseLoader()).from_string(self.template) return j2_env.render({**self._context})
Base
1
def is_local_uri(uri, is_tracking_or_registry_uri=True): """ Returns true if the specified URI is a local file path (/foo or file:/foo). :param uri: The URI. :param is_tracking_uri: Whether or not the specified URI is an MLflow Tracking or MLflow Model Registry URI. Examples...
Variant
0
def validate_path_is_safe(path): """ Validates that the specified path is safe to join with a trusted prefix. This is a security measure to prevent path traversal attacks. A valid path should: not contain separators other than '/' not contain .. to navigate to parent dir in path ...
Base
1
def validate_path_is_safe(path): """ Validates that the specified path is safe to join with a trusted prefix. This is a security measure to prevent path traversal attacks. A valid path should: not contain separators other than '/' not contain .. to navigate to parent dir in path ...
Variant
0
def test_list_artifacts_malicious_path(http_artifact_repo, path): with mock.patch( "mlflow.store.artifact.http_artifact_repo.http_request", return_value=MockResponse( { "files": [ {"path": path, "is_dir": False, "file_size": 1}, ] ...
Base
1
def test_list_artifacts_malicious_path(http_artifact_repo, path): with mock.patch( "mlflow.store.artifact.http_artifact_repo.http_request", return_value=MockResponse( { "files": [ {"path": path, "is_dir": False, "file_size": 1}, ] ...
Variant
0
def test_validate_path_is_safe_windows_good(path): validate_path_is_safe(path)
Base
1
def test_validate_path_is_safe_windows_good(path): validate_path_is_safe(path)
Variant
0
def assert_response(resp): assert resp.status_code == 400 assert response.json() == { "error_code": "INVALID_PARAMETER_VALUE", "message": f"Invalid path: {invalid_path}", }
Base
1
def assert_response(resp): assert resp.status_code == 400 assert response.json() == { "error_code": "INVALID_PARAMETER_VALUE", "message": f"Invalid path: {invalid_path}", }
Variant
0
def test_path_validation(mlflow_client): experiment_id = mlflow_client.create_experiment("tags validation") created_run = mlflow_client.create_run(experiment_id) run_id = created_run.info.run_id invalid_path = "../path" def assert_response(resp): assert resp.status_code == 400 asser...
Base
1
def test_path_validation(mlflow_client): experiment_id = mlflow_client.create_experiment("tags validation") created_run = mlflow_client.create_run(experiment_id) run_id = created_run.info.run_id invalid_path = "../path" def assert_response(resp): assert resp.status_code == 400 asser...
Variant
0
def test_validate_path_is_safe_windows_bad(path): with pytest.raises(MlflowException, match="Invalid path"): validate_path_is_safe(path)
Base
1
def test_validate_path_is_safe_windows_bad(path): with pytest.raises(MlflowException, match="Invalid path"): validate_path_is_safe(path)
Variant
0
def test_validate_path_is_safe_good(path): validate_path_is_safe(path)
Base
1
def test_validate_path_is_safe_good(path): validate_path_is_safe(path)
Variant
0
def test_validate_path_is_safe_bad(path): with pytest.raises(MlflowException, match="Invalid path"): validate_path_is_safe(path)
Base
1
def test_validate_path_is_safe_bad(path): with pytest.raises(MlflowException, match="Invalid path"): validate_path_is_safe(path)
Variant
0
def load(self, dst_path=None) -> str: """ Downloads the dataset source to the local filesystem. :param dst_path: Path of the local filesystem destination directory to which to download the dataset source. If the directory does not exist, it is created. If ...
Base
1
def list_artifacts(self, path=None): with self.get_ftp_client() as ftp: artifact_dir = self.path list_dir = posixpath.join(artifact_dir, path) if path else artifact_dir if not self._is_dir(ftp, list_dir): return [] artifact_files = ftp.nlst(lis...
Variant
0
def _create_multipart_upload_artifact(artifact_path): """ A request handler for `POST /mlflow-artifacts/mpu/create` to create a multipart upload to `artifact_path` (a relative path from the root artifact directory). """ validate_path_is_safe(artifact_path) request_message = _get_request_message...
Base
1
def get_artifact_handler(): from querystring_parser import parser query_string = request.query_string.decode("utf-8") request_dict = parser.parse(query_string, normalized=True) run_id = request_dict.get("run_id") or request_dict.get("run_uuid") path = request_dict["path"] validate_path_is_safe(...
Base
1
def _delete_artifact_mlflow_artifacts(artifact_path): """ A request handler for `DELETE /mlflow-artifacts/artifacts?path=<value>` to delete artifacts in `path` (a relative path from the root artifact directory). """ validate_path_is_safe(artifact_path) _get_request_message(DeleteArtifact()) ...
Base
1
def _list_artifacts(): request_message = _get_request_message( ListArtifacts(), schema={ "run_id": [_assert_string, _assert_required], "path": [_assert_string], "page_token": [_assert_string], }, ) response_message = ListArtifacts.Response() if...
Base
1
def _abort_multipart_upload_artifact(artifact_path): """ A request handler for `POST /mlflow-artifacts/mpu/abort` to abort a multipart upload to `artifact_path` (a relative path from the root artifact directory). """ validate_path_is_safe(artifact_path) request_message = _get_request_message( ...
Base
1
def get_model_version_artifact_handler(): from querystring_parser import parser query_string = request.query_string.decode("utf-8") request_dict = parser.parse(query_string, normalized=True) name = request_dict.get("name") version = request_dict.get("version") path = request_dict["path"] va...
Base
1
def _download_artifact(artifact_path): """ A request handler for `GET /mlflow-artifacts/artifacts/<artifact_path>` to download an artifact from `artifact_path` (a relative path from the root artifact directory). """ validate_path_is_safe(artifact_path) tmp_dir = tempfile.TemporaryDirectory() ...
Base
1
def _complete_multipart_upload_artifact(artifact_path): """ A request handler for `POST /mlflow-artifacts/mpu/complete` to complete a multipart upload to `artifact_path` (a relative path from the root artifact directory). """ validate_path_is_safe(artifact_path) request_message = _get_request_m...
Base
1
def _list_artifacts_mlflow_artifacts(): """ A request handler for `GET /mlflow-artifacts/artifacts?path=<value>` to list artifacts in `path` (a relative path from the root artifact directory). """ request_message = _get_request_message(ListArtifactsMlflowArtifacts()) if request_message.HasField(...
Base
1
def _upload_artifact(artifact_path): """ A request handler for `PUT /mlflow-artifacts/artifacts/<artifact_path>` to upload an artifact to `artifact_path` (a relative path from the root artifact directory). """ validate_path_is_safe(artifact_path) head, tail = posixpath.split(artifact_path) w...
Base
1
def list_artifacts(self, path=None): endpoint = "/mlflow-artifacts/artifacts" url, tail = self.artifact_uri.split(endpoint, maxsplit=1) root = tail.lstrip("/") params = {"path": posixpath.join(root, path) if path else root} host_creds = _get_default_host_creds(url) re...
Base
1
def _get_http_response_with_retries( method, url, max_retries, backoff_factor, backoff_jitter, retry_codes, raise_on_status=True, **kwargs, ): """ Performs an HTTP request using Python's `requests` module with an automatic retry policy. :param method: a string indicating the...
Base
1
def test_log_artifact_gcp_with_headers( databricks_artifact_repo, test_file, artifact_path, expected_location ): expected_headers = {header.name: header.value for header in MOCK_HEADERS} mock_response = Response() mock_response.status_code = 200 mock_response.close = lambda: None mock_credential...
Base
1
def test_log_artifact_aws_with_headers( databricks_artifact_repo, test_file, artifact_path, expected_location ): expected_headers = {header.name: header.value for header in MOCK_HEADERS} mock_response = Response() mock_response.status_code = 200 mock_response.close = lambda: None mock_credential...
Base
1
def test_log_artifact_aws(databricks_artifact_repo, test_file, artifact_path, expected_location): mock_response = Response() mock_response.status_code = 200 mock_response.close = lambda: None mock_credential_info = ArtifactCredentialInfo( signed_uri=MOCK_AWS_SIGNED_URI, type=ArtifactCredentialTy...
Base
1
def test_log_artifact_gcp(databricks_artifact_repo, test_file, artifact_path, expected_location): mock_response = Response() mock_response.status_code = 200 mock_response.close = lambda: None mock_credential_info = ArtifactCredentialInfo( signed_uri=MOCK_GCP_SIGNED_URL, type=ArtifactCredentialTy...
Base
1
def run_as_real_user(args: list[str]) -> None: """Call subprocess.run as real user if called via sudo/pkexec. If we are called through pkexec/sudo, determine the real user ID and run the command with it to get the user's web browser settings. """ uid = _get_env_int("SUDO_UID", _get_env_int("PKEXEC_...
Class
2
def open_url(self, url): """Open the given URL in a new browser window. Display an error dialog if everything fails. """ (r, w) = os.pipe() if os.fork() > 0: os.close(w) status = os.wait()[1] if status: title = _("Unable to...
Class
2
def test_run_as_real_user_no_gvfsd( self, getpwuid_mock: unittest.mock.MagicMock ) -> None: """Test run_as_real_user() without no gvfsd process.""" getpwuid_mock.return_value = pwd.struct_passwd( ( "testuser", "x", 1337, ...
Class
2
def test_run_as_real_user(self) -> None: """Test run_as_real_user() with SUDO_UID set.""" pwuid = pwd.getpwuid(int(os.environ["SUDO_UID"])) with tempfile.TemporaryDirectory() as tmpdir: # rename test program to fake gvfsd gvfsd_mock = os.path.join(tmpdir, "gvfsd") ...
Class
2
def _get_data(self): LOG.debug("Machine is a Vultr instance") # Fetch metadata self.metadata = self.get_metadata() self.userdata_raw = self.metadata["user-data"] # Generate config and process data self.get_datasource_data(self.metadata) # Dump some data so...
Base
1
def redact_sensitive_keys(metadata, redact_value=REDACT_SENSITIVE_VALUE): """Redact any sensitive keys from to provided metadata dictionary. Replace any keys values listed in 'sensitive_keys' with redact_value. """ if not metadata.get("sensitive_keys", []): return metadata md_copy = copy.de...
Base
1
def process_instance_metadata(metadata, key_path="", sensitive_keys=()): """Process all instance metadata cleaning it up for persisting as json. Strip ci-b64 prefix and catalog any 'base64_encoded_keys' as a list @return Dict copy of processed metadata. """ md_copy = copy.deepcopy(metadata) ba...
Base
1
def _initialize_filesystem(self): util.ensure_dirs(self._initial_subdirs()) log_file = util.get_cfg_option_str(self.cfg, "def_log_file") if log_file: util.ensure_file(log_file, mode=0o640, preserve_mode=True) perms = self.cfg.get("syslog_fix_perms") if not...
Base
1
def test_existing_file_permissions_are_not_modified(self, init, tmpdir): """If the log file already exists, we should not modify its permissions See https://bugs.launchpad.net/cloud-init/+bug/1900837. """ # Use a mode that will never be made the default so this test will # a...
Base
1
def test_regular_user_cant_add_users(self): response = self.client.get("/admin/auth/user/add/") self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code) response = self.client.post( "/admin/auth/user/add/", { "username": "added-by-regular-user", ...
Base
1
def test_moderator_can_add_users(self): user_should_have_perm(self.moderator, "auth.add_user") user_should_have_perm(self.moderator, "auth.change_user") # test for https://github.com/kiwitcms/Kiwi/issues/642 self.client.login( # nosec:B106:hardcoded_password_funcarg use...
Base
1
def test_superuser_can_add_users(self): # test for https://github.com/kiwitcms/Kiwi/issues/642 self.client.login( # nosec:B106:hardcoded_password_funcarg username=self.admin.username, password="admin-password" ) response = self.client.get("/admin/auth/user/add/") ...
Base
1
def setUp(self): self.data = { "username": "test_user", "password1": "password", "password2": "password", "email": "new-tester@example.com", }
Base
1
def test_invalid_form(self): response = self.client.post( self.register_url, { "username": "kiwi-tester", "password1": "password-1", "password2": "password-2", "email": "new-tester@example.com", }, ...
Base
1
def assert_user_registration(self, username, follow=False): with patch("tcms.kiwi_auth.models.secrets") as _secrets: _secrets.token_hex.return_value = self.fake_activate_key try: # https://github.com/mbi/django-simple-captcha/issues/84 # pylint: disab...
Base
1
def test_register_user_already_registered(self): User.objects.create_user("kiwi-tester", "new-tester@example.com", "password") response = self.client.post( self.register_url, { "username": "test_user", "password1": "password", ...
Base
1
def test_send_mail_for_password_reset(self, mail_sent): user = User.objects.create_user("kiwi-tester", "tester@example.com", "password") user.is_active = True user.save() data = {"email": "tester@example.com"} response = self.client.post(self.password_reset_url, data, follow=...
Base
1
def render_GET(self, request): template = env.get_template('generate_new.html') sites_len = len(get_all_canary_sites()) now = datetime.datetime.now() return template.render(settings=settings, sites_len=sites_len, now=now).encode('utf8')
Base
1
def get_signed_upload_url(path: str, download: bool = False) -> str: client = boto3.client( "s3", aws_access_key_id=settings.S3_KEY, aws_secret_access_key=settings.S3_SECRET_KEY, region_name=settings.S3_REGION, endpoint_url=settings.S3_ENDPOINT_URL, ) params = { ...
Class
2
def check_xsend_links( name: str, name_str_for_test: str, content_disposition: str = "", download: bool = False, ) -> None: self.login("hamlet") fp = StringIO("zulip!") fp.name = name result = self.client_pos...
Class
2
def test_avatar_url_local(self) -> None: self.login("hamlet") with get_test_image_file("img.png") as image_file: result = self.client_post("/json/users/me/avatar", {"file": image_file}) response_dict = self.assert_json_success(result) self.assertIn("avatar_url", response...
Class
2
def serve_local( request: HttpRequest, path_id: str, url_only: bool, download: bool = False ) -> HttpResponseBase: assert settings.LOCAL_FILES_DIR is not None local_path = os.path.join(settings.LOCAL_FILES_DIR, path_id) assert_is_local_storage_path("files", local_path) if not os.path.isfile(local_pa...
Class
2
def get_local_file_path_id_from_token(token: str) -> Optional[str]: signer = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT) try: signed_data = base64.b16decode(token).decode() path_id = signer.unsign(signed_data, max_age=timedelta(seconds=60)) except (BadSignature, binascii.Error): ...
Class
2
def serve_local_avatar_unauthed(request: HttpRequest, path: str) -> HttpResponseBase: """Serves avatar images off disk, via nginx (or directly in dev), with no auth. This is done unauthed because these need to be accessed from HTML emails, where the client does not have any auth. We rely on the URL be...
Class
2
def serve_s3( request: HttpRequest, url_path: str, url_only: bool, download: bool = False ) -> HttpResponse: url = get_signed_upload_url(url_path, download=download) if url_only: return json_success(request, data=dict(url=url)) return redirect(url)
Class
2
def serve_file( request: HttpRequest, maybe_user_profile: Union[UserProfile, AnonymousUser], realm_id_str: str, filename: str, url_only: bool = False, download: bool = False, ) -> HttpResponseBase: path_id = f"{realm_id_str}/{filename}" realm = get_valid_realm_from_request(request) i...
Class
2
def generate_unauthed_file_access_url(path_id: str) -> str: signed_data = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT).sign(path_id) token = base64.b16encode(signed_data.encode()).decode() filename = path_id.split("/")[-1] return reverse("local_file_unauthed", args=[token, filename])
Class
2