From 582507e7008daf6133cd74dd6e32e06483422560 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Sun, 14 Jul 2024 21:45:49 +0800 Subject: [PATCH 01/19] Eval-V2-Modal: init eval tabby serve v2. --- .../20240714212858-TabbyML-StarCoder-1B.jsonl | 2 + python/tabby-eval/v2-modal/README.md | 74 ++++++++ python/tabby-eval/v2-modal/app.py | 104 +++++++++++ python/tabby-eval/v2-modal/data.jsonl | 2 + .../v2-modal/eval_code_completion.py | 164 ++++++++++++++++++ .../v2-modal/eval_code_completion_jsonl.py | 44 +++++ 6 files changed, 390 insertions(+) create mode 100644 python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl create mode 100644 python/tabby-eval/v2-modal/README.md create mode 100644 python/tabby-eval/v2-modal/app.py create mode 100644 python/tabby-eval/v2-modal/data.jsonl create mode 100755 python/tabby-eval/v2-modal/eval_code_completion.py create mode 100644 python/tabby-eval/v2-modal/eval_code_completion_jsonl.py diff --git a/python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl b/python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl new file mode 100644 index 000000000000..4a7caa595b70 --- /dev/null +++ b/python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl @@ -0,0 +1,2 @@ +{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else fib(n - 1) + fib(n - 2)"} +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {"} diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md new file mode 100644 index 000000000000..f4200923550d --- /dev/null +++ b/python/tabby-eval/v2-modal/README.md @@ -0,0 +1,74 @@ +# Evaluating Code Completion Quality + +## Introduction + +This directory contains three Python scripts for evaluating code completion quality: + +* `eval_code_completion.py`: Evaluates code completion quality using parameters. +* `eval_code_completion_jsonl.py`: Evaluates code completion quality using a results file. +* `app.py`: A standalone Modal Tabby Serve service. + +## Usage + +Run the `eval_code_completion.py` script directly. Here’s an example: + +```bash +python eval_code_completion.py \ + --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ + --token auth_a51a5e20bcd9478d83e4f26fb87055d1 \ + --model TabbyML/StarCoder-1B \ + --jsonl_file data.jsonl +``` + +This script will call the Tabby service and evaluate the quality of code completion. The script’s parameters are as follows: + +```bash +python eval_code_completion.py -h +usage: eval_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL + [--jsonl_file JSONL_FILE] [--need_manager_modal NEED_MANAGER_MODAL] + +eval tabby code completion. + +options: + -h, --help show this help message and exit + --endpoint ENDPOINT Tabby server endpoint. + --token TOKEN Tabby server token. + --model MODEL Evaluation model. + --jsonl_file JSONL_FILE + Evaluation JSONL file. + --need_manager_modal NEED_MANAGER_MODAL + Whether a manager modal is needed. Accepts 1 or another. +``` + +If you already have a Tabby service running, you can set the `need_manager_modal` parameter to 0 to avoid starting a standalone Tabby service. Example: + +```bash +python eval_code_completion.py \ + --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ + --token auth_a51a5e20bcd9478d83e4f26fb87055d1 \ + --model TabbyML/StarCoder-1B \ + --jsonl_file data.jsonl \ + --need_manager_modal 0 +``` + +If you have a JSONL file with code completion results, you can use the `eval_code_completion_jsonl.py` script. Example: + +```bash +python eval_code_completion_jsonl.py --prediction_jsonl_file 20240714204945-TabbyML-StarCoder-1B.jsonl +``` + +The script’s parameters are as follows: + +```bash +python eval_code_completion_jsonl.py -h +usage: eval_code_completion_jsonl.py [-h] [--prediction_jsonl_file PREDICTION_JSONL_FILE] + +eval tabby code completion JSONL. + +options: + -h, --help show this help message and exit + --prediction_jsonl_file PREDICTION_JSONL_FILE + Prediction JSONL file. +``` + +Feel free to reach out if you have any questions or need further assistance! diff --git a/python/tabby-eval/v2-modal/app.py b/python/tabby-eval/v2-modal/app.py new file mode 100644 index 000000000000..3c6d36b225ba --- /dev/null +++ b/python/tabby-eval/v2-modal/app.py @@ -0,0 +1,104 @@ +"""Usage: +modal serve app.py + +To force a rebuild by pulling the latest image tag, use: +MODAL_FORCE_BUILD=1 modal serve app.py +""" + +import os + +from modal import Image, App, asgi_app, gpu, Volume + +IMAGE_NAME = "tabbyml/tabby" +EMBEDDING_MODEL_ID = os.getenv("EMBEDDING_MODEL_ID") +MODEL_ID = os.getenv("MODEL_ID") + +# TODO: If you're testing large datasets, consider using a better GPU and higher parallelism +GPU_CONFIG = gpu.T4() + +TABBY_BIN = "/opt/tabby/bin/tabby" +TABBY_ENV = os.environ.copy() +TABBY_ENV["TABBY_MODEL_CACHE_ROOT"] = "/models" +TABBY_ENV["MODEL_ID"] = MODEL_ID +TABBY_ENV["EMBEDDING_MODEL_ID"] = EMBEDDING_MODEL_ID + + +def download_model(model_id: str): + import subprocess + + subprocess.run( + [ + TABBY_BIN, + "download", + "--model", + model_id, + ] + ) + + +image = ( + Image.from_registry( + IMAGE_NAME, + add_python="3.11", + ) + .env(TABBY_ENV) + .dockerfile_commands("ENTRYPOINT []") + .run_function(download_model, kwargs={"model_id": EMBEDDING_MODEL_ID}) + .run_function(download_model, kwargs={"model_id": MODEL_ID}) + .pip_install("asgi-proxy-lib") +) + +app = App("tabby-server", image=image) + +data_volume = Volume.from_name("tabby-data", create_if_missing=True) +data_dir = "/data" + +@app.function( + gpu=GPU_CONFIG, + allow_concurrent_inputs=10, + container_idle_timeout=120, + timeout=360, + volumes={data_dir: data_volume}, + _allow_background_volume_commits=True, + concurrency_limit=1, +) +@asgi_app() +def app_serve(): + import socket + import subprocess + import time + from asgi_proxy import asgi_proxy + + launcher = subprocess.Popen( + [ + TABBY_BIN, + "serve", + "--model", + os.getenv("MODEL_ID"), + "--port", + "8000", + "--device", + "cuda", + "--parallelism", + "1", + ] + ) + + # Poll until webserver at 127.0.0.1:8000 accepts connections before running inputs. + def tabby_ready(): + try: + socket.create_connection(("127.0.0.1", 8000), timeout=1).close() + return True + except (socket.timeout, ConnectionRefusedError): + # Check if launcher webserving process has exited. + # If so, a connection can never be made. + retcode = launcher.poll() + if retcode is not None: + raise RuntimeError(f"launcher exited unexpectedly with code {retcode}") + return False + + while not tabby_ready(): + time.sleep(1.0) + + print("Tabby server ready!") + return asgi_proxy("http://localhost:8000") diff --git a/python/tabby-eval/v2-modal/data.jsonl b/python/tabby-eval/v2-modal/data.jsonl new file mode 100644 index 000000000000..cb2f741ce519 --- /dev/null +++ b/python/tabby-eval/v2-modal/data.jsonl @@ -0,0 +1,2 @@ +{"language": "python", "segments": {"prefix": "def fib(n):\n ", "suffix": "\n return fib(n - 1) + fib(n - 2)"}, "groundtruth": "\n if n <= 1:\n return n\n else:"} +{"language": "csharp", "segments": {"prefix": "using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n // Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n"}, "groundtruth": "LassoProfile> GetLassoProfiles()\n {"} \ No newline at end of file diff --git a/python/tabby-eval/v2-modal/eval_code_completion.py b/python/tabby-eval/v2-modal/eval_code_completion.py new file mode 100755 index 000000000000..98f0c135a732 --- /dev/null +++ b/python/tabby-eval/v2-modal/eval_code_completion.py @@ -0,0 +1,164 @@ +import argparse +import json +import logging +import os +import signal +import subprocess +import threading +import time + +import httpx +import pandas as pd +from pandas import json_normalize + +from eval_code_completion_jsonl import evaluation + +EMBEDDING_MODEL_ID = "TabbyML/Nomic-Embed-Text" + +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' +) + + +def check_service_health(endpoint, token): + def modal_tabby_ready(): + url = "{}/v1/health".format(endpoint) + headers = { + "Content-Type": "application/json", + "Accept": "application/json", + "Authorization": f'Bearer {token}' + } + + try: + response = httpx.get(url=url, headers=headers, timeout=5) + if response.status_code == 200: + logging.info("Server details: {}".format(response.json())) + return True + else: + return False + except Exception as e: + logging.error(f"Failed to check service health: {e}") + return False + + while not modal_tabby_ready(): + time.sleep(5) + + logging.info("Modal tabby server ready!") + + +def monitor_serve_output(process): + while True: + line = process.stdout.readline() + if not line: + break + logging.info(line.strip()) + + +def start_tabby_server(model): + logging.info("Starting tabby server for model {model}".format(model=model)) + + modal_env = os.environ.copy() + modal_env["MODEL_ID"] = model + modal_env["EMBEDDING_MODEL_ID"] = EMBEDDING_MODEL_ID + + process = subprocess.Popen(args=["modal", "serve", "app.py"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + env=modal_env) + + threading.Thread(target=monitor_serve_output, args=(process,)).start() + + return process + + +def send_sigint_to_process(process): + try: + os.kill(process.pid, signal.SIGINT) + logging.info("SIGINT signal sent successfully.") + except Exception as e: + logging.error(f"Failed to send SIGINT signal: {e}") + + +def generate_predictions(endpoint, token, model, jsonl_file): + df = pd.read_json(jsonl_file, lines=True) + df_flat = json_normalize(df.to_dict(orient="records")) + + headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'Authorization': f'Bearer {token}' + } + + predictions = [] + for index, row in df_flat.iterrows(): + payload = { + "language": row['language'], + "segments": { + "prefix": row['segments.prefix'], + "suffix": row['segments.suffix'] + } + } + + # TODO: Add retry logic, parallelism. + url = f"{endpoint}/v1/completions" + response = httpx.post(url=url, headers=headers, content=json.dumps(payload), timeout=10) + + if response.status_code == 200: + predictions.append(response.json()['choices'][0]['text']) + else: + predictions.append("Request failed after retry.") + + df_flat['prediction'] = predictions + formatted_timestamp = time.strftime("%Y%m%d%H%M%S") + prediction_jsonl_file = f"{formatted_timestamp}-{model.replace('/', '-')}.jsonl" + df_flat.to_json(prediction_jsonl_file, orient='records', lines=True) + + return prediction_jsonl_file + + +def eval_code_completion(endpoint: str, + token: str, + model: str, + jsonl_file: str, + need_manager_modal: bool): + # Start modal tabby server + process = None + if need_manager_modal: + process = start_tabby_server(model) + + # Check the service health + logging.info("Checking service health...") + check_service_health(endpoint, token) + + # Generate predictions + logging.info("Generating predictions...") + prediction_jsonl_file = generate_predictions(endpoint, token, model, jsonl_file) + logging.info("Predictions generated!") + + # Run the evaluation + logging.info("Running evaluation...") + evaluation(prediction_jsonl_file) + logging.info("Evaluation completed") + + # Stop the server + if need_manager_modal and process: + logging.info("Stopping server...") + send_sigint_to_process(process) + logging.info("Server stopped!") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="eval tabby code completion.") + parser.add_argument("--endpoint", type=str, required=True, help="tabby server endpoint.") + parser.add_argument("--token", type=str, required=True, default="", help="tabby server token.") + parser.add_argument("--model", type=str, required=True, help="evaluation model.") + parser.add_argument("--jsonl_file", type=str, default="data.jsonl", help="evaluation jsonl file.") + parser.add_argument("--need_manager_modal", type=str, default="1", + help="Whether a manager modal is needed. Accepts 1 or another.") + + args = parser.parse_args() + bool_need_manager_modal = True if args.need_manager_modal == "1" else False + eval_code_completion(args.endpoint, args.token, args.model, args.jsonl_file, bool_need_manager_modal) diff --git a/python/tabby-eval/v2-modal/eval_code_completion_jsonl.py b/python/tabby-eval/v2-modal/eval_code_completion_jsonl.py new file mode 100644 index 000000000000..3944609e6b5e --- /dev/null +++ b/python/tabby-eval/v2-modal/eval_code_completion_jsonl.py @@ -0,0 +1,44 @@ +import argparse +import logging + +import pandas as pd +from Levenshtein import ratio + +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' +) + + +def evaluation(prediction_jsonl_file): + df = pd.read_json(prediction_jsonl_file, lines=True) + total_score = 0 + + for index, row in df.iterrows(): + groundtruth = row['groundtruth'].split('\n') + prediction = row['prediction'].split('\n') + + # Get the first non-empty line + groundtruth_first_non_empty = next((s for s in groundtruth if s.strip()), "") + prediction_first_non_empty = next((s for s in prediction if s.strip()), "") + + # Calculate the ratio between the two + score = ratio(groundtruth_first_non_empty, prediction_first_non_empty) + + # Add the score to the total score + total_score += score + + # Calculate the average score + average_score = total_score / len(df) if len(df) > 0 else 0 + logging.info(f"Evaluation result: file {prediction_jsonl_file}, score: {average_score}") + + return average_score + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="eval tabby code completion jsonl.") + parser.add_argument("--prediction_jsonl_file", type=str, help="prediction jsonl file.") + + args = parser.parse_args() + evaluation(args.prediction_jsonl_file) From 9e0529b6f3f70033e8ce05c3c8b291fae04d4c01 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Tue, 16 Jul 2024 16:16:45 +0800 Subject: [PATCH 02/19] Update eval v2: Centralize env var setup in image config. --- python/tabby-eval/v2-modal/app.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/python/tabby-eval/v2-modal/app.py b/python/tabby-eval/v2-modal/app.py index 3c6d36b225ba..98568d77c55a 100644 --- a/python/tabby-eval/v2-modal/app.py +++ b/python/tabby-eval/v2-modal/app.py @@ -17,10 +17,6 @@ GPU_CONFIG = gpu.T4() TABBY_BIN = "/opt/tabby/bin/tabby" -TABBY_ENV = os.environ.copy() -TABBY_ENV["TABBY_MODEL_CACHE_ROOT"] = "/models" -TABBY_ENV["MODEL_ID"] = MODEL_ID -TABBY_ENV["EMBEDDING_MODEL_ID"] = EMBEDDING_MODEL_ID def download_model(model_id: str): @@ -41,7 +37,11 @@ def download_model(model_id: str): IMAGE_NAME, add_python="3.11", ) - .env(TABBY_ENV) + .env({ + "TABBY_MODEL_CACHE_ROOT": "/models", + "MODEL_ID": MODEL_ID, + "EMBEDDING_MODEL_ID": EMBEDDING_MODEL_ID + }) .dockerfile_commands("ENTRYPOINT []") .run_function(download_model, kwargs={"model_id": EMBEDDING_MODEL_ID}) .run_function(download_model, kwargs={"model_id": MODEL_ID}) @@ -53,6 +53,7 @@ def download_model(model_id: str): data_volume = Volume.from_name("tabby-data", create_if_missing=True) data_dir = "/data" + @app.function( gpu=GPU_CONFIG, allow_concurrent_inputs=10, From b707007f6d427cae58a54e5dc0ba99256b02d2b5 Mon Sep 17 00:00:00 2001 From: moqimoqidea <39821951+moqimoqidea@users.noreply.github.com> Date: Tue, 16 Jul 2024 22:37:35 +0800 Subject: [PATCH 03/19] rename code completion name. Co-authored-by: Meng Zhang --- python/tabby-eval/v2-modal/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index f4200923550d..a209b9f48076 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -4,7 +4,7 @@ This directory contains three Python scripts for evaluating code completion quality: -* `eval_code_completion.py`: Evaluates code completion quality using parameters. +* `compute_code_completion.py`: Evaluates code completion quality using parameters. * `eval_code_completion_jsonl.py`: Evaluates code completion quality using a results file. * `app.py`: A standalone Modal Tabby Serve service. From ae35f1a52975cea721652d41797faf496136ddb2 Mon Sep 17 00:00:00 2001 From: moqimoqidea <39821951+moqimoqidea@users.noreply.github.com> Date: Tue, 16 Jul 2024 22:38:01 +0800 Subject: [PATCH 04/19] rename compte metrics Co-authored-by: Meng Zhang --- python/tabby-eval/v2-modal/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index a209b9f48076..9fba80ea8d5a 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -5,7 +5,7 @@ This directory contains three Python scripts for evaluating code completion quality: * `compute_code_completion.py`: Evaluates code completion quality using parameters. -* `eval_code_completion_jsonl.py`: Evaluates code completion quality using a results file. +* `compute_metrics.py`: Evaluates code completion quality given prediction / groundtruth * `app.py`: A standalone Modal Tabby Serve service. ## Usage From e61d9e3293ce574f4bcac1db47fcb7a4a03cdca1 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Tue, 16 Jul 2024 22:41:26 +0800 Subject: [PATCH 05/19] Eval-V2-Modal: rename compute py file names. --- python/tabby-eval/v2-modal/README.md | 18 +++++++++--------- ...ompletion.py => compute_code_completion.py} | 2 +- ..._completion_jsonl.py => compute_metrics.py} | 0 3 files changed, 10 insertions(+), 10 deletions(-) rename python/tabby-eval/v2-modal/{eval_code_completion.py => compute_code_completion.py} (99%) rename python/tabby-eval/v2-modal/{eval_code_completion_jsonl.py => compute_metrics.py} (100%) diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index 9fba80ea8d5a..e41fed4b8721 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -10,10 +10,10 @@ This directory contains three Python scripts for evaluating code completion qual ## Usage -Run the `eval_code_completion.py` script directly. Here’s an example: +Run the `compute_code_completion.py` script directly. Here’s an example: ```bash -python eval_code_completion.py \ +python compute_code_completion.py \ --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ --token auth_a51a5e20bcd9478d83e4f26fb87055d1 \ --model TabbyML/StarCoder-1B \ @@ -23,8 +23,8 @@ python eval_code_completion.py \ This script will call the Tabby service and evaluate the quality of code completion. The script’s parameters are as follows: ```bash -python eval_code_completion.py -h -usage: eval_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL +python compute_code_completion.py -h +usage: compute_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL [--jsonl_file JSONL_FILE] [--need_manager_modal NEED_MANAGER_MODAL] eval tabby code completion. @@ -43,7 +43,7 @@ options: If you already have a Tabby service running, you can set the `need_manager_modal` parameter to 0 to avoid starting a standalone Tabby service. Example: ```bash -python eval_code_completion.py \ +python compute_code_completion.py \ --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ --token auth_a51a5e20bcd9478d83e4f26fb87055d1 \ --model TabbyML/StarCoder-1B \ @@ -51,17 +51,17 @@ python eval_code_completion.py \ --need_manager_modal 0 ``` -If you have a JSONL file with code completion results, you can use the `eval_code_completion_jsonl.py` script. Example: +If you have a JSONL file with code completion results, you can use the `compute_metrics.py` script. Example: ```bash -python eval_code_completion_jsonl.py --prediction_jsonl_file 20240714204945-TabbyML-StarCoder-1B.jsonl +python compute_metrics.py --prediction_jsonl_file 20240714204945-TabbyML-StarCoder-1B.jsonl ``` The script’s parameters are as follows: ```bash -python eval_code_completion_jsonl.py -h -usage: eval_code_completion_jsonl.py [-h] [--prediction_jsonl_file PREDICTION_JSONL_FILE] +python compute_metrics.py -h +usage: compute_metrics.py [-h] [--prediction_jsonl_file PREDICTION_JSONL_FILE] eval tabby code completion JSONL. diff --git a/python/tabby-eval/v2-modal/eval_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py similarity index 99% rename from python/tabby-eval/v2-modal/eval_code_completion.py rename to python/tabby-eval/v2-modal/compute_code_completion.py index 98f0c135a732..7a72aab87050 100755 --- a/python/tabby-eval/v2-modal/eval_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -11,7 +11,7 @@ import pandas as pd from pandas import json_normalize -from eval_code_completion_jsonl import evaluation +from compute_metrics import evaluation EMBEDDING_MODEL_ID = "TabbyML/Nomic-Embed-Text" diff --git a/python/tabby-eval/v2-modal/eval_code_completion_jsonl.py b/python/tabby-eval/v2-modal/compute_metrics.py similarity index 100% rename from python/tabby-eval/v2-modal/eval_code_completion_jsonl.py rename to python/tabby-eval/v2-modal/compute_metrics.py From b891e52117ab0df5273fe26e3829b6d147d4f9f3 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Tue, 16 Jul 2024 23:42:08 +0800 Subject: [PATCH 06/19] Eval-V2-Modal: add cpu/memory limit; use output_prediction_jsonl_file flag pass prediction file; add retry support for code completion; only save code completion success data to prediction file --- ...r-1B.jsonl => 20240716-StarCoder-1B.jsonl} | 4 +- python/tabby-eval/v2-modal/README.md | 26 +++++---- python/tabby-eval/v2-modal/app.py | 2 + .../v2-modal/compute_code_completion.py | 54 +++++++++++++++---- 4 files changed, 64 insertions(+), 22 deletions(-) rename python/tabby-eval/v2-modal/{20240714212858-TabbyML-StarCoder-1B.jsonl => 20240716-StarCoder-1B.jsonl} (93%) diff --git a/python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl b/python/tabby-eval/v2-modal/20240716-StarCoder-1B.jsonl similarity index 93% rename from python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl rename to python/tabby-eval/v2-modal/20240716-StarCoder-1B.jsonl index 4a7caa595b70..68a9717be62c 100644 --- a/python/tabby-eval/v2-modal/20240714212858-TabbyML-StarCoder-1B.jsonl +++ b/python/tabby-eval/v2-modal/20240716-StarCoder-1B.jsonl @@ -1,2 +1,2 @@ -{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else fib(n - 1) + fib(n - 2)"} -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {"} +{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else 1 + fib(n - 1)","prediction_status":"success"} +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index e41fed4b8721..64a25b556fee 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -15,9 +15,10 @@ Run the `compute_code_completion.py` script directly. Here’s an example: ```bash python compute_code_completion.py \ --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ - --token auth_a51a5e20bcd9478d83e4f26fb87055d1 \ + --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ - --jsonl_file data.jsonl + --jsonl_file data.jsonl \ + --output_prediction_jsonl_file 20240716-StarCoder-1B.jsonl ``` This script will call the Tabby service and evaluate the quality of code completion. The script’s parameters are as follows: @@ -25,17 +26,21 @@ This script will call the Tabby service and evaluate the quality of code complet ```bash python compute_code_completion.py -h usage: compute_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL - [--jsonl_file JSONL_FILE] [--need_manager_modal NEED_MANAGER_MODAL] + [--jsonl_file JSONL_FILE] + [--output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE] + [--need_manager_modal NEED_MANAGER_MODAL] eval tabby code completion. options: -h, --help show this help message and exit - --endpoint ENDPOINT Tabby server endpoint. - --token TOKEN Tabby server token. - --model MODEL Evaluation model. + --endpoint ENDPOINT tabby server endpoint. + --token TOKEN tabby server token. + --model MODEL evaluation model. --jsonl_file JSONL_FILE - Evaluation JSONL file. + evaluation jsonl file. + --output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE + output prediction jsonl file. --need_manager_modal NEED_MANAGER_MODAL Whether a manager modal is needed. Accepts 1 or another. ``` @@ -45,9 +50,10 @@ If you already have a Tabby service running, you can set the `need_manager_modal ```bash python compute_code_completion.py \ --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ - --token auth_a51a5e20bcd9478d83e4f26fb87055d1 \ + --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ --jsonl_file data.jsonl \ + --output_prediction_jsonl_file 20240716-StarCoder-1B.jsonl \ --need_manager_modal 0 ``` @@ -63,12 +69,12 @@ The script’s parameters are as follows: python compute_metrics.py -h usage: compute_metrics.py [-h] [--prediction_jsonl_file PREDICTION_JSONL_FILE] -eval tabby code completion JSONL. +eval tabby code completion jsonl. options: -h, --help show this help message and exit --prediction_jsonl_file PREDICTION_JSONL_FILE - Prediction JSONL file. + prediction jsonl file. ``` Feel free to reach out if you have any questions or need further assistance! diff --git a/python/tabby-eval/v2-modal/app.py b/python/tabby-eval/v2-modal/app.py index 98568d77c55a..4ac566c7dc20 100644 --- a/python/tabby-eval/v2-modal/app.py +++ b/python/tabby-eval/v2-modal/app.py @@ -62,6 +62,8 @@ def download_model(model_id: str): volumes={data_dir: data_volume}, _allow_background_volume_commits=True, concurrency_limit=1, + cpu=20.0, + memory=16 * 1024, ) @asgi_app() def app_serve(): diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index 7a72aab87050..45254f7ab5cc 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -82,7 +82,27 @@ def send_sigint_to_process(process): logging.error(f"Failed to send SIGINT signal: {e}") -def generate_predictions(endpoint, token, model, jsonl_file): +def send_request_with_retry(url, headers, payload, timeout=10, max_retries=10): + retries = 0 + response = None + + while retries < max_retries: + try: + response = httpx.post(url=url, headers=headers, content=json.dumps(payload), timeout=timeout) + if response.status_code == 200: + return response + else: + retries += 1 + time.sleep(1) + except httpx.RequestError as e: + logging.error(f"Get code completion failed: {e}") + retries += 1 + time.sleep(1) + + return response + + +def generate_predictions(endpoint: str, token: str, jsonl_file: str, output_prediction_jsonl_file: str): df = pd.read_json(jsonl_file, lines=True) df_flat = json_normalize(df.to_dict(orient="records")) @@ -93,6 +113,7 @@ def generate_predictions(endpoint, token, model, jsonl_file): } predictions = [] + prediction_status = [] for index, row in df_flat.iterrows(): payload = { "language": row['language'], @@ -102,27 +123,34 @@ def generate_predictions(endpoint, token, model, jsonl_file): } } - # TODO: Add retry logic, parallelism. + # TODO: Add parallelism support url = f"{endpoint}/v1/completions" - response = httpx.post(url=url, headers=headers, content=json.dumps(payload), timeout=10) + response = send_request_with_retry(url, headers, payload, timeout=10, max_retries=10) if response.status_code == 200: predictions.append(response.json()['choices'][0]['text']) + prediction_status.append("success") else: predictions.append("Request failed after retry.") + prediction_status.append("failed") df_flat['prediction'] = predictions - formatted_timestamp = time.strftime("%Y%m%d%H%M%S") - prediction_jsonl_file = f"{formatted_timestamp}-{model.replace('/', '-')}.jsonl" - df_flat.to_json(prediction_jsonl_file, orient='records', lines=True) + df_flat['prediction_status'] = prediction_status + df_success = df_flat[df_flat['prediction_status'] == "success"] + + total_records = len(df_flat) + success_count = len(df_success) + failed_count = total_records - success_count + logging.info(f"Total predictions: {total_records}, Success: {success_count}, Failed: {failed_count}") - return prediction_jsonl_file + df_success.to_json(output_prediction_jsonl_file, orient='records', lines=True) def eval_code_completion(endpoint: str, token: str, model: str, jsonl_file: str, + output_prediction_jsonl_file: str, need_manager_modal: bool): # Start modal tabby server process = None @@ -135,12 +163,12 @@ def eval_code_completion(endpoint: str, # Generate predictions logging.info("Generating predictions...") - prediction_jsonl_file = generate_predictions(endpoint, token, model, jsonl_file) + generate_predictions(endpoint, token, jsonl_file, output_prediction_jsonl_file) logging.info("Predictions generated!") # Run the evaluation logging.info("Running evaluation...") - evaluation(prediction_jsonl_file) + evaluation(output_prediction_jsonl_file) logging.info("Evaluation completed") # Stop the server @@ -156,9 +184,15 @@ def eval_code_completion(endpoint: str, parser.add_argument("--token", type=str, required=True, default="", help="tabby server token.") parser.add_argument("--model", type=str, required=True, help="evaluation model.") parser.add_argument("--jsonl_file", type=str, default="data.jsonl", help="evaluation jsonl file.") + parser.add_argument("--output_prediction_jsonl_file", type=str, help="output prediction jsonl file.") parser.add_argument("--need_manager_modal", type=str, default="1", help="Whether a manager modal is needed. Accepts 1 or another.") args = parser.parse_args() bool_need_manager_modal = True if args.need_manager_modal == "1" else False - eval_code_completion(args.endpoint, args.token, args.model, args.jsonl_file, bool_need_manager_modal) + eval_code_completion(args.endpoint, + args.token, + args.model, + args.jsonl_file, + args.output_prediction_jsonl_file, + bool_need_manager_modal) From 5e2e39d52ebc818bab95651000bf6dfd2441cbf1 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 00:09:31 +0800 Subject: [PATCH 07/19] Eval-V2-Modal: set compute_metrics.py output evaluation jsonl file; add avg_metrics.py calc avg metrics; --- python/tabby-eval/v2-modal/README.md | 30 +++++++++++++- python/tabby-eval/v2-modal/avg_metrics.py | 31 +++++++++++++++ python/tabby-eval/v2-modal/compute_metrics.py | 39 ++++++++++++------- 3 files changed, 84 insertions(+), 16 deletions(-) create mode 100644 python/tabby-eval/v2-modal/avg_metrics.py diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index 64a25b556fee..f4d54537ed3f 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -2,10 +2,11 @@ ## Introduction -This directory contains three Python scripts for evaluating code completion quality: +This directory contains four Python scripts for evaluating code completion quality: * `compute_code_completion.py`: Evaluates code completion quality using parameters. * `compute_metrics.py`: Evaluates code completion quality given prediction / groundtruth +* `avg_metrics.py`: Averages the evaluation results of multiple JSONL files. * `app.py`: A standalone Modal Tabby Serve service. ## Usage @@ -60,7 +61,9 @@ python compute_code_completion.py \ If you have a JSONL file with code completion results, you can use the `compute_metrics.py` script. Example: ```bash -python compute_metrics.py --prediction_jsonl_file 20240714204945-TabbyML-StarCoder-1B.jsonl +python compute_metrics.py \ + --prediction_jsonl_file 20240716-StarCoder-1B.jsonl \ + --output_evaluation_jsonl_file 20240716-StarCoder-1B-evaluation.jsonl ``` The script’s parameters are as follows: @@ -68,6 +71,7 @@ The script’s parameters are as follows: ```bash python compute_metrics.py -h usage: compute_metrics.py [-h] [--prediction_jsonl_file PREDICTION_JSONL_FILE] + [--output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE] eval tabby code completion jsonl. @@ -75,6 +79,28 @@ options: -h, --help show this help message and exit --prediction_jsonl_file PREDICTION_JSONL_FILE prediction jsonl file. + --output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE + output evaluation jsonl file. +``` + +If you have a JSONL file with evaluation results, you can use the `avg_metrics.py` script. Example: + +```bash +python avg_metrics.py --evaluation_jsonl_file 20240716-StarCoder-1B-evaluation.jsonl +``` + +The script’s parameters are as follows: + +```bash +python avg_metrics.py -h +usage: avg_metrics.py [-h] [--evaluation_jsonl_file EVALUATION_JSONL_FILE] + +avg tabby code completion metrics. + +options: + -h, --help show this help message and exit + --evaluation_jsonl_file EVALUATION_JSONL_FILE + evaluation jsonl file. ``` Feel free to reach out if you have any questions or need further assistance! diff --git a/python/tabby-eval/v2-modal/avg_metrics.py b/python/tabby-eval/v2-modal/avg_metrics.py new file mode 100644 index 000000000000..b99f25673a6f --- /dev/null +++ b/python/tabby-eval/v2-modal/avg_metrics.py @@ -0,0 +1,31 @@ +import argparse +import logging + +import pandas as pd + +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' +) + + +def avg_compute(evaluation_jsonl_file): + df = pd.read_json(evaluation_jsonl_file, lines=True) + + avg_results = { + "line_accuracy": df["line_accuracy"].mean(), + "block_accuracy": df["block_accuracy"].mean(), + "avg_line_edit_distance": df["avg_line_edit_distance"].mean(), + "block_edit_distance": df["block_edit_distance"].mean() + } + + logging.info(f"Average results: {avg_results}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="avg tabby code completion metrics.") + parser.add_argument("--evaluation_jsonl_file", type=str, help="evaluation jsonl file.") + + args = parser.parse_args() + avg_compute(args.evaluation_jsonl_file) diff --git a/python/tabby-eval/v2-modal/compute_metrics.py b/python/tabby-eval/v2-modal/compute_metrics.py index 3944609e6b5e..e2b56ea66771 100644 --- a/python/tabby-eval/v2-modal/compute_metrics.py +++ b/python/tabby-eval/v2-modal/compute_metrics.py @@ -4,6 +4,8 @@ import pandas as pd from Levenshtein import ratio +from avg_metrics import avg_compute + logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(message)s', @@ -11,34 +13,43 @@ ) -def evaluation(prediction_jsonl_file): +def evaluation(prediction_jsonl_file, output_evaluation_jsonl_file): df = pd.read_json(prediction_jsonl_file, lines=True) - total_score = 0 + results = [] for index, row in df.iterrows(): groundtruth = row['groundtruth'].split('\n') prediction = row['prediction'].split('\n') - # Get the first non-empty line - groundtruth_first_non_empty = next((s for s in groundtruth if s.strip()), "") - prediction_first_non_empty = next((s for s in prediction if s.strip()), "") + line_accuracy = sum(1 for gt, pred in zip(groundtruth, prediction) if gt == pred) / len( + groundtruth) if groundtruth else 0 + + block_accuracy = 1 if '\n'.join(groundtruth) == '\n'.join(prediction) else 0 + + line_edit_distances = [ratio(gt, pred) for gt, pred in zip(groundtruth, prediction)] + avg_line_edit_distance = sum(line_edit_distances) / len(line_edit_distances) if line_edit_distances else 0 + + block_edit_distance = ratio('\n'.join(groundtruth), '\n'.join(prediction)) - # Calculate the ratio between the two - score = ratio(groundtruth_first_non_empty, prediction_first_non_empty) + results.append({ + "line_accuracy": line_accuracy, + "block_accuracy": block_accuracy, + "avg_line_edit_distance": avg_line_edit_distance, + "block_edit_distance": block_edit_distance + }) - # Add the score to the total score - total_score += score + df = pd.concat([df, pd.DataFrame(results)], axis=1) - # Calculate the average score - average_score = total_score / len(df) if len(df) > 0 else 0 - logging.info(f"Evaluation result: file {prediction_jsonl_file}, score: {average_score}") + df.to_json(output_evaluation_jsonl_file, orient='records', lines=True, force_ascii=False) + logging.info(f"Evaluation result written to {output_evaluation_jsonl_file}") - return average_score + avg_compute(output_evaluation_jsonl_file) if __name__ == "__main__": parser = argparse.ArgumentParser(description="eval tabby code completion jsonl.") parser.add_argument("--prediction_jsonl_file", type=str, help="prediction jsonl file.") + parser.add_argument("--output_evaluation_jsonl_file", type=str, help="output evaluation jsonl file.") args = parser.parse_args() - evaluation(args.prediction_jsonl_file) + evaluation(args.prediction_jsonl_file, args.output_evaluation_jsonl_file) From 0a3a83548ff1c88c44753c26b60b14e6d0a15250 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 00:10:04 +0800 Subject: [PATCH 08/19] Eval-V2-Modal: add 20240716-StarCoder-1B-evaluation.jsonl --- .../tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl diff --git a/python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl b/python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl new file mode 100644 index 000000000000..e9a02e31eeef --- /dev/null +++ b/python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl @@ -0,0 +1,2 @@ +{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else 1 + fib(n - 1)","prediction_status":"success","line_accuracy":0.0,"block_accuracy":0,"avg_line_edit_distance":0.0,"block_edit_distance":0.4} +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","line_accuracy":1.0,"block_accuracy":1,"avg_line_edit_distance":1.0,"block_edit_distance":1.0} From 18531f7b1926654f19342d2ceb6cca3b8b2e59e8 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 00:29:27 +0800 Subject: [PATCH 09/19] Eval-V2-Modal: code optimization --- python/tabby-eval/v2-modal/avg_metrics.py | 4 ++-- python/tabby-eval/v2-modal/compute_metrics.py | 22 ++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/python/tabby-eval/v2-modal/avg_metrics.py b/python/tabby-eval/v2-modal/avg_metrics.py index b99f25673a6f..13ceb56f17b2 100644 --- a/python/tabby-eval/v2-modal/avg_metrics.py +++ b/python/tabby-eval/v2-modal/avg_metrics.py @@ -14,10 +14,10 @@ def avg_compute(evaluation_jsonl_file): df = pd.read_json(evaluation_jsonl_file, lines=True) avg_results = { - "line_accuracy": df["line_accuracy"].mean(), "block_accuracy": df["block_accuracy"].mean(), + "block_edit_distance": df["block_edit_distance"].mean(), + "line_accuracy": df["line_accuracy"].mean(), "avg_line_edit_distance": df["avg_line_edit_distance"].mean(), - "block_edit_distance": df["block_edit_distance"].mean() } logging.info(f"Average results: {avg_results}") diff --git a/python/tabby-eval/v2-modal/compute_metrics.py b/python/tabby-eval/v2-modal/compute_metrics.py index e2b56ea66771..f9f5aa2f5cb4 100644 --- a/python/tabby-eval/v2-modal/compute_metrics.py +++ b/python/tabby-eval/v2-modal/compute_metrics.py @@ -18,24 +18,26 @@ def evaluation(prediction_jsonl_file, output_evaluation_jsonl_file): results = [] for index, row in df.iterrows(): - groundtruth = row['groundtruth'].split('\n') - prediction = row['prediction'].split('\n') + groundtruth = row['groundtruth'] + prediction = row['prediction'] - line_accuracy = sum(1 for gt, pred in zip(groundtruth, prediction) if gt == pred) / len( - groundtruth) if groundtruth else 0 + block_accuracy = 1 if groundtruth == prediction else 0 + block_edit_distance = ratio(groundtruth, prediction) - block_accuracy = 1 if '\n'.join(groundtruth) == '\n'.join(prediction) else 0 + groundtruth_lines = groundtruth.split('\n') + prediction_lines = prediction.split('\n') - line_edit_distances = [ratio(gt, pred) for gt, pred in zip(groundtruth, prediction)] - avg_line_edit_distance = sum(line_edit_distances) / len(line_edit_distances) if line_edit_distances else 0 + line_accuracy = sum(1 for gt, pred in zip(groundtruth_lines, prediction_lines) if gt == pred) / len( + groundtruth_lines) if groundtruth_lines else 0 - block_edit_distance = ratio('\n'.join(groundtruth), '\n'.join(prediction)) + line_edit_distances = [ratio(gt, pred) for gt, pred in zip(groundtruth_lines, prediction_lines)] + avg_line_edit_distance = sum(line_edit_distances) / len(line_edit_distances) if line_edit_distances else 0 results.append({ - "line_accuracy": line_accuracy, "block_accuracy": block_accuracy, + "block_edit_distance": block_edit_distance, + "line_accuracy": line_accuracy, "avg_line_edit_distance": avg_line_edit_distance, - "block_edit_distance": block_edit_distance }) df = pd.concat([df, pd.DataFrame(results)], axis=1) From 0302d781bc1b26252d95d75033818b761be960dc Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 09:04:14 +0800 Subject: [PATCH 10/19] Eval-V2-Modal: fix calling evaluation function parameter error --- ...onl => 20240717-StarCoder-1B-evaluation.jsonl} | 4 ++-- ...Coder-1B.jsonl => 20240717-StarCoder-1B.jsonl} | 0 python/tabby-eval/v2-modal/README.md | 15 ++++++++++----- .../v2-modal/compute_code_completion.py | 5 ++++- 4 files changed, 16 insertions(+), 8 deletions(-) rename python/tabby-eval/v2-modal/{20240716-StarCoder-1B-evaluation.jsonl => 20240717-StarCoder-1B-evaluation.jsonl} (91%) rename python/tabby-eval/v2-modal/{20240716-StarCoder-1B.jsonl => 20240717-StarCoder-1B.jsonl} (100%) diff --git a/python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl b/python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl similarity index 91% rename from python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl rename to python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl index e9a02e31eeef..647ca56cf686 100644 --- a/python/tabby-eval/v2-modal/20240716-StarCoder-1B-evaluation.jsonl +++ b/python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl @@ -1,2 +1,2 @@ -{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else 1 + fib(n - 1)","prediction_status":"success","line_accuracy":0.0,"block_accuracy":0,"avg_line_edit_distance":0.0,"block_edit_distance":0.4} -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","line_accuracy":1.0,"block_accuracy":1,"avg_line_edit_distance":1.0,"block_edit_distance":1.0} +{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else 1 + fib(n - 1)","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.4,"line_accuracy":0.0,"avg_line_edit_distance":0.0} +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/20240716-StarCoder-1B.jsonl b/python/tabby-eval/v2-modal/20240717-StarCoder-1B.jsonl similarity index 100% rename from python/tabby-eval/v2-modal/20240716-StarCoder-1B.jsonl rename to python/tabby-eval/v2-modal/20240717-StarCoder-1B.jsonl diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index f4d54537ed3f..50686b9d1468 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -19,7 +19,8 @@ python compute_code_completion.py \ --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ --jsonl_file data.jsonl \ - --output_prediction_jsonl_file 20240716-StarCoder-1B.jsonl + --output_prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ + --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl ``` This script will call the Tabby service and evaluate the quality of code completion. The script’s parameters are as follows: @@ -29,6 +30,7 @@ python compute_code_completion.py -h usage: compute_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL [--jsonl_file JSONL_FILE] [--output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE] + [--output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE] [--need_manager_modal NEED_MANAGER_MODAL] eval tabby code completion. @@ -42,6 +44,8 @@ options: evaluation jsonl file. --output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE output prediction jsonl file. + --output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE + output evaluation jsonl file. --need_manager_modal NEED_MANAGER_MODAL Whether a manager modal is needed. Accepts 1 or another. ``` @@ -54,7 +58,8 @@ python compute_code_completion.py \ --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ --jsonl_file data.jsonl \ - --output_prediction_jsonl_file 20240716-StarCoder-1B.jsonl \ + --output_prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ + --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl \ --need_manager_modal 0 ``` @@ -62,8 +67,8 @@ If you have a JSONL file with code completion results, you can use the `compute_ ```bash python compute_metrics.py \ - --prediction_jsonl_file 20240716-StarCoder-1B.jsonl \ - --output_evaluation_jsonl_file 20240716-StarCoder-1B-evaluation.jsonl + --prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ + --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl ``` The script’s parameters are as follows: @@ -86,7 +91,7 @@ options: If you have a JSONL file with evaluation results, you can use the `avg_metrics.py` script. Example: ```bash -python avg_metrics.py --evaluation_jsonl_file 20240716-StarCoder-1B-evaluation.jsonl +python avg_metrics.py --evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl ``` The script’s parameters are as follows: diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index 45254f7ab5cc..108f68126c39 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -151,6 +151,7 @@ def eval_code_completion(endpoint: str, model: str, jsonl_file: str, output_prediction_jsonl_file: str, + output_evaluation_jsonl_file: str, need_manager_modal: bool): # Start modal tabby server process = None @@ -168,7 +169,7 @@ def eval_code_completion(endpoint: str, # Run the evaluation logging.info("Running evaluation...") - evaluation(output_prediction_jsonl_file) + evaluation(output_prediction_jsonl_file, output_evaluation_jsonl_file) logging.info("Evaluation completed") # Stop the server @@ -185,6 +186,7 @@ def eval_code_completion(endpoint: str, parser.add_argument("--model", type=str, required=True, help="evaluation model.") parser.add_argument("--jsonl_file", type=str, default="data.jsonl", help="evaluation jsonl file.") parser.add_argument("--output_prediction_jsonl_file", type=str, help="output prediction jsonl file.") + parser.add_argument("--output_evaluation_jsonl_file", type=str, help="output evaluation jsonl file.") parser.add_argument("--need_manager_modal", type=str, default="1", help="Whether a manager modal is needed. Accepts 1 or another.") @@ -195,4 +197,5 @@ def eval_code_completion(endpoint: str, args.model, args.jsonl_file, args.output_prediction_jsonl_file, + args.output_evaluation_jsonl_file, bool_need_manager_modal) From c12632af6182dd9820dc87527f22096e07789a6f Mon Sep 17 00:00:00 2001 From: moqimoqidea <39821951+moqimoqidea@users.noreply.github.com> Date: Wed, 17 Jul 2024 10:35:31 +0800 Subject: [PATCH 11/19] rename need_manager_modal to start_tabby_server_on_modal Co-authored-by: Meng Zhang --- python/tabby-eval/v2-modal/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index 50686b9d1468..986eb33bbf28 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -46,7 +46,7 @@ options: output prediction jsonl file. --output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE output evaluation jsonl file. - --need_manager_modal NEED_MANAGER_MODAL + --start_tabby_server_on_modal NEED_MANAGER_MODAL Whether a manager modal is needed. Accepts 1 or another. ``` From b8bdcde391ead3912ef1fd3c80c328df9e38004e Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 10:45:07 +0800 Subject: [PATCH 12/19] Eval-V2-Modal: rename need_manager_modal to start_tabby_server_on_modal --- python/tabby-eval/v2-modal/README.md | 13 ++++++------- .../tabby-eval/v2-modal/compute_code_completion.py | 14 +++++++------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index 986eb33bbf28..a04b6c181146 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -27,11 +27,10 @@ This script will call the Tabby service and evaluate the quality of code complet ```bash python compute_code_completion.py -h -usage: compute_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL - [--jsonl_file JSONL_FILE] +usage: compute_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL [--jsonl_file JSONL_FILE] [--output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE] [--output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE] - [--need_manager_modal NEED_MANAGER_MODAL] + [--start_tabby_server_on_modal START_TABBY_SERVER_ON_MODAL] eval tabby code completion. @@ -46,11 +45,11 @@ options: output prediction jsonl file. --output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE output evaluation jsonl file. - --start_tabby_server_on_modal NEED_MANAGER_MODAL - Whether a manager modal is needed. Accepts 1 or another. + --start_tabby_server_on_modal START_TABBY_SERVER_ON_MODAL + start tabby server on modal manager, accepts 1 or another. ``` -If you already have a Tabby service running, you can set the `need_manager_modal` parameter to 0 to avoid starting a standalone Tabby service. Example: +If you already have a Tabby service running, you can set the `start_tabby_server_on_modal` parameter to 0 to avoid starting a standalone Tabby service. Example: ```bash python compute_code_completion.py \ @@ -60,7 +59,7 @@ python compute_code_completion.py \ --jsonl_file data.jsonl \ --output_prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl \ - --need_manager_modal 0 + --start_tabby_server_on_modal 0 ``` If you have a JSONL file with code completion results, you can use the `compute_metrics.py` script. Example: diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index 108f68126c39..742d7bc2849c 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -152,10 +152,10 @@ def eval_code_completion(endpoint: str, jsonl_file: str, output_prediction_jsonl_file: str, output_evaluation_jsonl_file: str, - need_manager_modal: bool): + start_tabby_server_on_modal: bool): # Start modal tabby server process = None - if need_manager_modal: + if start_tabby_server_on_modal: process = start_tabby_server(model) # Check the service health @@ -173,7 +173,7 @@ def eval_code_completion(endpoint: str, logging.info("Evaluation completed") # Stop the server - if need_manager_modal and process: + if start_tabby_server_on_modal and process: logging.info("Stopping server...") send_sigint_to_process(process) logging.info("Server stopped!") @@ -187,15 +187,15 @@ def eval_code_completion(endpoint: str, parser.add_argument("--jsonl_file", type=str, default="data.jsonl", help="evaluation jsonl file.") parser.add_argument("--output_prediction_jsonl_file", type=str, help="output prediction jsonl file.") parser.add_argument("--output_evaluation_jsonl_file", type=str, help="output evaluation jsonl file.") - parser.add_argument("--need_manager_modal", type=str, default="1", - help="Whether a manager modal is needed. Accepts 1 or another.") + parser.add_argument("--start_tabby_server_on_modal", type=str, default="1", + help="start tabby server on modal manager, accepts 1 or another.") args = parser.parse_args() - bool_need_manager_modal = True if args.need_manager_modal == "1" else False + bool_start_tabby_server_on_modal = True if args.start_tabby_server_on_modal == "1" else False eval_code_completion(args.endpoint, args.token, args.model, args.jsonl_file, args.output_prediction_jsonl_file, args.output_evaluation_jsonl_file, - bool_need_manager_modal) + bool_start_tabby_server_on_modal) From 737fd91ad0e522a71b24b0de7be8c40699adc9ea Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 10:47:26 +0800 Subject: [PATCH 13/19] Eval-V2-Modal: set python file 755 permissions --- python/tabby-eval/v2-modal/app.py | 0 python/tabby-eval/v2-modal/avg_metrics.py | 0 python/tabby-eval/v2-modal/compute_metrics.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 python/tabby-eval/v2-modal/app.py mode change 100644 => 100755 python/tabby-eval/v2-modal/avg_metrics.py mode change 100644 => 100755 python/tabby-eval/v2-modal/compute_metrics.py diff --git a/python/tabby-eval/v2-modal/app.py b/python/tabby-eval/v2-modal/app.py old mode 100644 new mode 100755 diff --git a/python/tabby-eval/v2-modal/avg_metrics.py b/python/tabby-eval/v2-modal/avg_metrics.py old mode 100644 new mode 100755 diff --git a/python/tabby-eval/v2-modal/compute_metrics.py b/python/tabby-eval/v2-modal/compute_metrics.py old mode 100644 new mode 100755 From b9bb4b72a3352b6e556ab2f104ac4d8a38de5e0a Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 12:33:25 +0800 Subject: [PATCH 14/19] Eval-V2-Modal: add transform_legacy_data.py --- python/tabby-eval/v2-modal/legacy/README.md | 32 ++++++++++++++ .../legacy/data-with-crossfile-context.jsonl | 10 +++++ .../head10_line_completion_rg1_bm25.jsonl | 10 +++++ .../v2-modal/legacy/transform_legacy_data.py | 44 +++++++++++++++++++ 4 files changed, 96 insertions(+) create mode 100644 python/tabby-eval/v2-modal/legacy/README.md create mode 100644 python/tabby-eval/v2-modal/legacy/data-with-crossfile-context.jsonl create mode 100644 python/tabby-eval/v2-modal/legacy/head10_line_completion_rg1_bm25.jsonl create mode 100755 python/tabby-eval/v2-modal/legacy/transform_legacy_data.py diff --git a/python/tabby-eval/v2-modal/legacy/README.md b/python/tabby-eval/v2-modal/legacy/README.md new file mode 100644 index 000000000000..cdb780c53106 --- /dev/null +++ b/python/tabby-eval/v2-modal/legacy/README.md @@ -0,0 +1,32 @@ +# Transform legacy data to new format + +## Usage + +Run the `transform_legacy_data.py` script directly. Here’s an example: + +```bash +python transform_legacy_data.py \ + --language csharp \ + --legacy_jsonl_file head10_line_completion_rg1_bm25.jsonl \ + --output_data_jsonl_file data-with-crossfile-context.jsonl +``` + +This script will transform the legacy data to new format. The script’s parameters are as follows: + +```bash +python transform_legacy_data.py -h +usage: transform_legacy_data.py [-h] [--language LANGUAGE] [--legacy_jsonl_file LEGACY_JSONL_FILE] + [--output_data_jsonl_file OUTPUT_DATA_JSONL_FILE] + +transform legacy jsonl file to new format. + +options: + -h, --help show this help message and exit + --language LANGUAGE programming language. + --legacy_jsonl_file LEGACY_JSONL_FILE + legacy jsonl file. + --output_data_jsonl_file OUTPUT_DATA_JSONL_FILE + output data jsonl file. +``` + +Feel free to reach out if you have any questions or need further assistance! diff --git a/python/tabby-eval/v2-modal/legacy/data-with-crossfile-context.jsonl b/python/tabby-eval/v2-modal/legacy/data-with-crossfile-context.jsonl new file mode 100644 index 000000000000..dc3a3ba2f878 --- /dev/null +++ b/python/tabby-eval/v2-modal/legacy/data-with-crossfile-context.jsonl @@ -0,0 +1,10 @@ +{"language": "csharp", "segments": {"prefix": "using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n // Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ProcessManager/Providers/IConfigProvider.cs\n// ManagerConfig GetManagerConfig();\n// /// \n// /// Geth the list of lasso rules.\n// /// \n// /// \n// List GetRules();\n// Dictionary GetLassoProfiles();\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Models/Configs/ManagerConfig.cs\n// public ProcessRule[] ProcessRules { get; set; }\n// /// \n// /// List of folders rules.\n// /// \n// public FolderRule[] FolderRules { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// public void Dispose()\n// {\n// if (processStartEvent != null) \n// {\n// processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n// processStartEvent.Dispose();\n// processStartEvent = null;\n// }\n// }\n// public bool Setup()\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// {\n// int failCount = 0;\n// Dictionary successCount = new Dictionary();\n// foreach (var process in Process.GetProcesses())\n// {\n// LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n// bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n// if (success)\n// {\n// if (!successCount.ContainsKey(profileName))\n\n", "list": [{"retrieved_chunk": " ManagerConfig GetManagerConfig();\n /// \n /// Geth the list of lasso rules.\n /// \n /// \n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}", "filename": "ProcessManager/Providers/IConfigProvider.cs", "score": 22.799994275269317}, {"retrieved_chunk": " public ProcessRule[] ProcessRules { get; set; }\n /// \n /// List of folders rules.\n /// \n public FolderRule[] FolderRules { get; set; }\n }\n}", "filename": "ProcessManager/Models/Configs/ManagerConfig.cs", "score": 20.728193497923062}, {"retrieved_chunk": " public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 14.506247294243275}, {"retrieved_chunk": " {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 11.789149115850975}]}}, "groundtruth": "LassoProfile> GetLassoProfiles()\n {", "metadata": {"task_id": "project_cc_csharp/27", "repository": "kenshinakh1-LassoProcessManager-bcc481f", "file": "ProcessManager/Providers/ConfigProvider.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 45, "right_context_start_lineno": 47}} +{"language": "csharp", "segments": {"prefix": "//#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(", "suffix": "\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\t\tBuildProjectsList();\n// \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n// \t\t\t\t\t{\n// \t\t\t\t\t\tLaunchInstaller(entry);\n// \t\t\t\t\t\treturn;\n// \t\t\t\t\t}\n// \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n// \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n// \t\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n// \t\t\t\t\treturn;\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/FileHelper.cs\n// \t{\n// \t\tGD.Print(\"*********** Delete file!\");\n// \t}\n// \tprivate static void CreateDirectoryForUser(string directory)\n// \t{\n// \t\tvar path = Path.Combine(BasePath, directory);\n// \t\tif (!DirAccess.DirExistsAbsolute(path))\n// \t\t{\n// \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n// \t\t}\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n// \t\t\t};\n// \t\t\tprojectEntries.Add(project);\n// \t\t\tLaunchProject(directoryPath, false);\n// \t\t}\n// \t\tvoid _onFilesDropped(string[] files)\n// \t\t{\n// \t\t\tfor (int i = 0; i < files.Length; i++)\n// \t\t\t{\n// \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/FileHelper.cs\n// \t}\n// \tpublic static void WriteUserText(string path, string json)\n// \t{\n// \t\tWriteAllText(PathCombine(BasePath, path), json);\n// \t}\n// \tpublic static bool UserFileExists(string path)\n// \t{\n// \t\treturn FileExists(PathCombine(BasePath, path));\n// \t}\n// \tpublic static void Delete(string path)\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\tInstallVersion(versionKey);\n// \t\t\t}\n// \t\t\tSaveProjectsList();\n// \t\t\tBuildProjectsList();\n// \t\t}\n// \t\tvoid SaveConfig()\n// \t\t{\n// \t\t\tvar json = DataBuilder.GetConfigJson(config);\n// \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n// \t\t}\n\n", "list": [{"retrieved_chunk": "\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 29.431886867394642}, {"retrieved_chunk": "\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}", "filename": "godot-project/Scripts/DataManagement/FileHelper.cs", "score": 16.13486385582849}, {"retrieved_chunk": "\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 14.892200276853623}, {"retrieved_chunk": "\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)", "filename": "godot-project/Scripts/DataManagement/FileHelper.cs", "score": 13.921454071982678}, {"retrieved_chunk": "\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 13.535088476589515}]}}, "groundtruth": "InstallerEntryData installerEntryData)\n\t\t{", "metadata": {"task_id": "project_cc_csharp/55", "repository": "NathanWarden-ready-to-launch-58eba6d", "file": "godot-project/Scripts/DataManagement/DataPaths.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 94, "right_context_start_lineno": 96}} +{"language": "csharp", "segments": {"prefix": "using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [", "suffix": " get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs\n// private const string BADGE_URL = \"https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true\";\n// private const string SUMMARY_URL = \"https://forum.dotnetdev.kr/u/{0}/summary.json\";\n// private readonly IHttpClientFactory _httpClientFactory;\n// public ForumDataProvider(IHttpClientFactory httpClientFactory)\n// {\n// _httpClientFactory = httpClientFactory;\n// }\n// private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n// {\n// using HttpClient client = _httpClientFactory.CreateClient();\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs\n// public string Username { get; set; }\n// [JsonProperty(\"name\")]\n// public string Name { get; set; }\n// [JsonProperty(\"avatar_template\")]\n// public string AvatarTemplate { get; set; }\n// [JsonProperty(\"flair_name\")]\n// public object FlairName { get; set; }\n// [JsonProperty(\"trust_level\")]\n// public int TrustLevel { get; set; }\n// [JsonProperty(\"admin\")]\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs\n// \ufeffusing DotNetDevBadgeWeb.Model;\n// namespace DotNetDevBadgeWeb.Interfaces\n// {\n// public interface IProvider\n// {\n// Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n// Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n// Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n// }\n// }\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs\n// private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n// private readonly IProvider _forumProvider;\n// private readonly IMeasureTextV1 _measureTextV1;\n// public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n// {\n// _forumProvider = forumProvider;\n// _measureTextV1 = measureTextV1;\n// }\n// public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n// {\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs\n// {\n// app.UseMiddleware();\n// app.MapBadgeEndpointsV1();\n// return app;\n// }\n// internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n// {\n// app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n// {\n// string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n", "list": [{"retrieved_chunk": " private const string BADGE_URL = \"https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https://forum.dotnetdev.kr/u/{0}/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs", "score": 20.998481641894454}, {"retrieved_chunk": " public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "score": 20.73346729938653}, {"retrieved_chunk": "\ufeffusing DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs", "score": 12.088199207115517}, {"retrieved_chunk": " private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs", "score": 10.738553623860039}, {"retrieved_chunk": " {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs", "score": 7.998097817927588}]}}, "groundtruth": "JsonProperty(\"likes_given\")]\n public int LikesGiven {", "metadata": {"task_id": "project_cc_csharp/48", "repository": "chanos-dev-dotnetdev-badge-5740a40", "file": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 8}} +{"language": "csharp", "segments": {"prefix": "using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<", "suffix": " get; set; } = new List();\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs\n// {\n// public List Workbooks { get; set; } = new List();\n// public int SearchLimitRow { get; set; }\n// public int SearchLimitColumn { get; set; }\n// public List WorksheetIndexes { get; set; } = new List();\n// public List Worksheets { get; set; } = new List();\n// public bool ReadAllWorksheets { get; set; }\n// public List HeadersToSearch { get; set; } = new List();\n// public DataTable GetDataTable()\n// {\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs\n// public class DataTableExtractor :\n// IDataTableExtractorConfiguration,\n// IDataTableExtractorWorkbookConfiguration,\n// IDataTableExtractorSearchConfiguration,\n// IDataTableExtractorWorksheetConfiguration\n// {\n// private bool _readAllWorksheets;\n// private int _searchLimitRow;\n// private int _searchLimitColumn;\n// private readonly List _workbooks = new List();\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorksheetData.cs\n// \ufeffusing System.Collections.Generic;\n// namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n// {\n// public class JXLWorksheetData\n// {\n// public string WorksheetName { get; set; } = string.Empty;\n// public List Rows { get; set; } = new List();\n// }\n// }\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLExtractedRow.cs\n// \ufeffusing System.Collections.Generic;\n// namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n// {\n// public class JXLExtractedRow\n// {\n// public Dictionary Columns { get; set; } = new Dictionary();\n// }\n// }\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/Configuration/IDataExtraction.cs\n// /// \n// /// \n// List GetWorkbooksData();\n// /// \n// /// Only retrieves the extracted rows from all the workbooks and worksheets.\n// /// \n// /// \n// /// \n// List GetExtractedRows();\n// /// \n\n", "list": [{"retrieved_chunk": " {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {", "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "score": 21.880390238660006}, {"retrieved_chunk": " public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();", "filename": "JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs", "score": 20.597128248615988}, {"retrieved_chunk": "\ufeffusing System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}", "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorksheetData.cs", "score": 20.44056373724002}, {"retrieved_chunk": "\ufeffusing System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}", "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLExtractedRow.cs", "score": 20.174278440276893}, {"retrieved_chunk": " /// \n /// \n List GetWorkbooksData();\n /// \n /// Only retrieves the extracted rows from all the workbooks and worksheets.\n /// \n /// \n /// \n List GetExtractedRows();\n /// ", "filename": "JdeJabali.JXLDataTableExtractor/Configuration/IDataExtraction.cs", "score": 19.028401583774812}]}}, "groundtruth": "JXLWorkbookData> WorkbooksData {", "metadata": {"task_id": "project_cc_csharp/50", "repository": "JdeJabali-JXLDataTableExtractor-90a12f4", "file": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLDataExtracted.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 7}} +{"language": "csharp", "segments": {"prefix": "using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ", "suffix": "\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/ExampleWebApplication/Controllers/WebSocket2Controller.cs\n// public WebSocket2Controller(WebSocketHub webSocketHub)\n// {\n// _webSocketHub = webSocketHub;\n// }\n// [HttpGet(\"GetSocketListWithSelector\")]\n// public IActionResult GetSocketListWithSelector(int id)\n// {\n// var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n// return Ok(socketListOfUser);\n// }\n\n// the below code fragment can be found in:\n// src/ExampleWebApplication/Controllers/WebSocket1Controller.cs\n// {\n// _webSocketHub = webSocketHub;\n// }\n// [HttpGet(\"GetSocketList\")]\n// public IActionResult GetSocketList(int id)\n// {\n// var socketListOfUser = _webSocketHub.GetSocketList(id);\n// return Ok(socketListOfUser);\n// }\n// [HttpGet(\"GetSocketListWithSelector\")]\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketRequestHandlerProvider.cs\n// /// Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n// /// \n// /// The type of WebSocket request handler to add.\n// /// The message type associated with the WebSocket request handler.\n// /// true if the WebSocket request handler was added to the handler type map; otherwise, false.\n// /// Thrown when is not assignable from IWebSocketRequestHandler.\n// /// \n// /// This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n// /// \n// public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketHub.cs\n// public WebSocketHub(IOptions options)\n// {\n// if (options == null) throw new ArgumentNullException(nameof(options));\n// Options = options.Value;\n// _webSocketDictionary = new();\n// }\n// /// \n// /// Encodes the specified Message object into a UTF-8 encoded byte array.\n// /// \n// /// The Message object to encode.\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketHub.cs\n// private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n// public WebSocketHubOptions Options { get; private set; }\n// /// \n// /// Initializes a new instance of the WebSocketHub class with the specified options.\n// /// \n// /// The options to configure the WebSocketHub.\n// /// Thrown when is null.\n// /// \n// /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n// /// \n\n", "list": [{"retrieved_chunk": " public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }", "filename": "src/ExampleWebApplication/Controllers/WebSocket2Controller.cs", "score": 45.19935267420081}, {"retrieved_chunk": " {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]", "filename": "src/ExampleWebApplication/Controllers/WebSocket1Controller.cs", "score": 45.02333198140999}, {"retrieved_chunk": " /// Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n /// \n /// The type of WebSocket request handler to add.\n /// The message type associated with the WebSocket request handler.\n /// true if the WebSocket request handler was added to the handler type map; otherwise, false.\n /// Thrown when is not assignable from IWebSocketRequestHandler.\n /// \n /// This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n /// \n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)", "filename": "src/WebSocketHub/Core/src/WebSocketRequestHandlerProvider.cs", "score": 38.98487610590298}, {"retrieved_chunk": " public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n /// \n /// Encodes the specified Message object into a UTF-8 encoded byte array.\n /// \n /// The Message object to encode.", "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "score": 37.98681211524358}, {"retrieved_chunk": " private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n /// \n /// Initializes a new instance of the WebSocketHub class with the specified options.\n /// \n /// The options to configure the WebSocketHub.\n /// Thrown when is null.\n /// \n /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n /// ", "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "score": 31.71651588733243}]}}, "groundtruth": "WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {", "metadata": {"task_id": "project_cc_csharp/68", "repository": "TRA-Tech-dotnet-websocket-9049854", "file": "src/WebSocketHub/Core/src/WebSocketHubMiddleware.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 17, "right_context_start_lineno": 19}} +{"language": "csharp", "segments": {"prefix": "using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; // in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n /// \n /// Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n /// \n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n /// \n /// The Xbox memory stream.\n /// \n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<", "suffix": "\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n // init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n // enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n // custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length / 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n // argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n // argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], // initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n // optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n // peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n // call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n // cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n /// \n /// Calls an Xbox function.\n /// \n /// The function address.\n /// The function arguments.\n /// Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.\n public uint Call(long address, params object[] args)\n {\n // TODO: call context (~4039+ which requires qwordparam)\n\n // injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n /// \n /// Original Xbox Debug Monitor runtime patches.\n /// Prevents crashdumps from being written to the HDD and enables remote code execution.\n /// \n /// \n private void PatchXbdm(Xbox target)\n {\n // the spin routine to be patched in after the signature patterns\n // spin:\n // jmp spin\n // int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n // prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n // this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n // labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); // pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); // size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n //asm.push(__dword_ptr[ebx + 8]);\n //asm.call((uint)target.Signatures[\"DmFreePool\"]);\n //asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); // buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); // address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n // 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n // labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n // prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); // carve out arbitrary space for local temp variables\n asm.pushad();\n\n // disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n // arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n // local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n // check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); // 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n // call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n // thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n // determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); // 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n // get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); // 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n // push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n // get argument name\n asm.push(edi); // argument index\n asm.push(argFormatStringAddress); // format string address\n asm.lea(eax, __dword_ptr[argName]); // argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n // check if it's included in the command\n asm.lea(eax, __[temp]); // argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); // argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); // command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n // push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n // move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n // perform the call\n asm.call(__dword_ptr[callAddress]);\n\n // print response message\n asm.push(eax); // integer return value\n asm.push(returnFormatAddress); // format string address\n asm.push(__dword_ptr[responseAddress]); // response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n // TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n // get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); // address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n //asm.mov(eax, 0x2000); // TODO: increase pool size?\n //asm.push(eax);\n //asm.call((uint)target.Signatures[\"DmAllocatePool\"]); // TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); // buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); // buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n // if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n // generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n // successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n // generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n // original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n // inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n // read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n // disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n // formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n // convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n // skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n // optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n // output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n // optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n // output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n // NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n // universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n // mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n // mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n // mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n // universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n // mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n // mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n // universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n // jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n // push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n // mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n // universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n // mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n // jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n // retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n // universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n // test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n // push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n // early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n // mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n // mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n // later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n // mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n // mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n // xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha/dvt3/dvt4/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n // mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n // mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n // early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n // push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n // mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n // push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n // later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n // push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n // retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n // universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n // cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n // read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n // scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n // cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // TODO: dispose managed state (managed objects)\n }\n\n // TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n // TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/ConnectionInfo.cs\n// var connections = new List();\n// byte[] datagramBuffer = new byte[1024];\n// // iterate through each network interface\n// Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n// {\n// // only worry about active IPv4 interfaces\n// if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n// return;\n// // iterate through each ip address assigned to the interface\n// Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Connection.cs\n// /// \n// /// Initializes the session.\n// /// \n// public Connection()\n// {\n// // initialize defaults\n// Reader = new BinaryReader(this);\n// Writer = new BinaryWriter(this);\n// ResetTcp();\n// }\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Connection.cs\n// /// \n// /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n// /// \n// public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n// /// \n// /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n// /// \n// public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n// #endregion\n// #region Construction\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Kernel.cs\n// throw new ArgumentNullException(nameof(xbox));\n// Module = xbox.Modules.Find(m => m.Name == Name) ??\n// throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n// // TODO: remove 3rd-party dependency with proper PE parsing logic\n// // grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n// var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n// int size = (int)(initSection.Base - Address);\n// var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n// // resolve exports\n// Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Kernel.cs\n// /// The kernel exports.\n// /// \n// public KernelExports Exports { get; private set; }\n// /// \n// /// Initializes communication with the Xbox kernel.\n// /// \n// /// \n// public Kernel(Xbox xbox)\n// {\n// _xbox = xbox ??\n\n", "list": [{"retrieved_chunk": " var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n // iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n // only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n // iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>", "filename": "src/OGXbdmDumper/ConnectionInfo.cs", "score": 66.55166457984245}, {"retrieved_chunk": " /// \n /// Initializes the session.\n /// \n public Connection()\n {\n // initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }", "filename": "src/OGXbdmDumper/Connection.cs", "score": 65.61480573217976}, {"retrieved_chunk": " /// \n /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n /// \n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n /// \n /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n /// \n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction", "filename": "src/OGXbdmDumper/Connection.cs", "score": 63.14871472847682}, {"retrieved_chunk": " throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n // TODO: remove 3rd-party dependency with proper PE parsing logic\n // grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n // resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);", "filename": "src/OGXbdmDumper/Kernel.cs", "score": 62.61533660943069}, {"retrieved_chunk": " /// The kernel exports.\n /// \n public KernelExports Exports { get; private set; }\n /// \n /// Initializes communication with the Xbox kernel.\n /// \n /// \n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??", "filename": "src/OGXbdmDumper/Kernel.cs", "score": 60.88570669473385}]}}, "groundtruth": "Thread> Threads => GetThreads();", "metadata": {"task_id": "project_cc_csharp/20", "repository": "Ernegien-OGXbdmDumper-07a1e82", "file": "src/OGXbdmDumper/Xbox.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 75, "right_context_start_lineno": 76}} +{"language": "csharp", "segments": {"prefix": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [", "suffix": " get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/JWDal.cs\n// {\n// connectionString = $\"Data Source={dbPath}\";\n// }\n// public IEnumerable TableList()\n// {\n// using (IDbConnection cnn = new SQLiteConnection(connectionString))\n// {\n// return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/InputField.cs\n// \ufeffusing JWLSLMerge.Data.Attributes;\n// namespace JWLSLMerge.Data.Models\n// {\n// public class InputField\n// {\n// public int LocationId { get; set; }\n// public string TextTag { get; set; } = null!;\n// public string Value { get; set; } = null!;\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Tag.cs\n// public int NewTagId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge/MergeService.cs\n// private readonly string targetPath = null!;\n// private readonly string targetDbFile = null!;\n// private string lastModified = null!;\n// public MergeService()\n// {\n// targetPath = Environment.GetTargetDirectory();\n// targetDbFile = Environment.GetDbFile();\n// }\n// public void Run(string[] jwlibraryFiles)\n// {\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/UserMark.cs\n// public string UserMarkGuid { get; set; } = null!;\n// public int Version { get; set; }\n// [Ignore]\n// public int NewUserMarkId { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": " {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }", "filename": "JWLSLMerge.Data/JWDal.cs", "score": 13.78401506779753}, {"retrieved_chunk": "\ufeffusing JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}", "filename": "JWLSLMerge.Data/Models/InputField.cs", "score": 13.000811547599904}, {"retrieved_chunk": " public int NewTagId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Tag.cs", "score": 12.828308464376727}, {"retrieved_chunk": " private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {", "filename": "JWLSLMerge/MergeService.cs", "score": 12.77934094725121}, {"retrieved_chunk": " public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/UserMark.cs", "score": 12.358601363000677}]}}, "groundtruth": "Ignore]\n public int NoteId {", "metadata": {"task_id": "project_cc_csharp/51", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/Note.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 8}} +{"language": "csharp", "segments": {"prefix": "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n /// \n /// \u5e94\u7528\u5de5\u4f5c\u76ee\u5f55\n /// \n /// \u542f\u52a8\u53c2\u6570\n /// \n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"\u7cfb\u7edf\u5df2\u5b58\u5728\u540c\u540d\u4f46\u4e0d\u540c\u8def\u5f84\u7684\u670d\u52a1\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ", "suffix": "\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n /// \n /// \u505c\u6b62\u5e76\u5220\u9664\u670d\u52a1\n /// \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n // \u8fd9\u91cc\u4e0d\u9700\u8981\u6062\u590dSERVICE_CONFIG_FAILURE_ACTIONS\uff0c\u56e0\u4e3a\u4e0b\u9762\u6211\u4eec\u8981\u5220\u9664\u670d\u52a1\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"\u7b49\u5f85\u670d\u52a1\u505c\u6b62\u8d85\u8fc7\u4e86{maxWaitTime.TotalSeconds}\u79d2\");\n }\n\n /// \n /// \u5c1d\u8bd5\u83b7\u53d6\u670d\u52a1\u7684\u8fdb\u7a0bid\n /// \n /// \n /// \n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// }\n// var linuxOptions = CreateLinuxOptions(filePath, options);\n// using (var fileStream = File.OpenWrite(unitFilePath))\n// {\n// using var wirter = new StreamWriter(fileStream);\n// linuxOptions.WriteTo(wirter);\n// }\n// // SELinux\n// Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n// SystemControl(\"daemon-reload\", showError: true);\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// break;\n// }\n// }\n// if (filePath.IsEmpty || wantedBy.IsEmpty)\n// {\n// return ReadOnlySpan.Empty;\n// }\n// var wants = $\"{wantedBy.ToString()}.wants\";\n// var unitFileName = Path.GetFileName(unitFilePath);\n// var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// if (geteuid() != 0)\n// {\n// throw new UnauthorizedAccessException(\"\u65e0\u6cd5\u64cd\u4f5c\u670d\u52a1\uff1a\u6ca1\u6709root\u6743\u9650\");\n// }\n// }\n// }\n// }\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// line = line[execStartPrefix.Length..];\n// var index = line.IndexOf(' ');\n// filePath = index < 0 ? line : line[..index];\n// }\n// else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n// {\n// wantedBy = line[wantedByPrefix.Length..].Trim();\n// }\n// if (filePath.Length > 0 && wantedBy.Length > 0)\n// {\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// {\n// execStart = $\"{filePath} {string.Join(' ', args)}\";\n// }\n// }\n// var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n// ? Path.GetDirectoryName(filePath)\n// : Path.GetFullPath(options.WorkingDirectory);\n// var linuxOptions = options.Linux.Clone();\n// linuxOptions.Unit[\"Description\"] = options.Description;\n// linuxOptions.Service[\"ExecStart\"] = execStart;\n\n", "list": [{"retrieved_chunk": " }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n // SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);", "filename": "ServiceSelf/LinuxService.cs", "score": 53.22018771652771}, {"retrieved_chunk": " break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);", "filename": "ServiceSelf/LinuxService.cs", "score": 21.470485420837036}, {"retrieved_chunk": " if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"\u65e0\u6cd5\u64cd\u4f5c\u670d\u52a1\uff1a\u6ca1\u6709root\u6743\u9650\");\n }\n }\n }\n}", "filename": "ServiceSelf/LinuxService.cs", "score": 12.934142972279112}, {"retrieved_chunk": " line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {", "filename": "ServiceSelf/LinuxService.cs", "score": 12.544725417438247}, {"retrieved_chunk": " {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;", "filename": "ServiceSelf/LinuxService.cs", "score": 12.519455560002188}]}}, "groundtruth": "SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {", "metadata": {"task_id": "project_cc_csharp/14", "repository": "xljiulang-ServiceSelf-7f8604b", "file": "ServiceSelf/WindowsService.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 66, "right_context_start_lineno": 68}} +{"language": "csharp", "segments": {"prefix": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [", "suffix": " get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemMarker.cs\n// public long DurationTicks { get; set; }\n// public long EndTransitionDurationTicks { get; set; }\n// [Ignore]\n// public int NewPlaylistItemMarkerId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Note.cs\n// public string? Title { get; set; }\n// public string? Content { get; set; }\n// public string LastModified { get; set; } = null!;\n// public string Created { get; set; } = null!;\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// [Ignore]\n// public int NewNoteId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/UserMark.cs\n// public string UserMarkGuid { get; set; } = null!;\n// public int Version { get; set; }\n// [Ignore]\n// public int NewUserMarkId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Location.cs\n// public int? Track { get; set; }\n// public int IssueTagNumber { get; set; }\n// public string? KeySymbol { get; set; }\n// public int? MepsLanguage { get; set; }\n// public int Type { get; set; }\n// public string? Title { get; set; }\n// [Ignore]\n// public int NewLocationId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Bookmark.cs\n// public string Title { get; set; } = null!;\n// public string? Snippet { get; set; }\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": " public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs", "score": 35.26889876052275}, {"retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Note.cs", "score": 33.518184487704545}, {"retrieved_chunk": " public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/UserMark.cs", "score": 32.64848873570582}, {"retrieved_chunk": " public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Location.cs", "score": 31.624913532715233}, {"retrieved_chunk": " public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Bookmark.cs", "score": 31.183025189281004}]}}, "groundtruth": "Ignore]\n public int NewPlaylistItemId {", "metadata": {"task_id": "project_cc_csharp/37", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/PlayListItem.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 15, "right_context_start_lineno": 17}} +{"language": "csharp", "segments": {"prefix": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [", "suffix": " get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemIndependentMediaMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemIndependentMediaMap\n// {\n// public int PlaylistItemId { get; set; }\n// public int IndependentMediaId { get; set; }\n// public long DurationTicks { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemLocationMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemLocationMap\n// {\n// public int PlaylistItemId { get; set; }\n// public int LocationId { get; set; }\n// public int MajorMultimediaType { get; set; }\n// public long? BaseDurationTicks { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlayListItem.cs\n// public int Accuracy { get; set; }\n// public int EndAction { get; set; }\n// public string ThumbnailFilePath { get; set; } = null!;\n// [Ignore]\n// public int NewPlaylistItemId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Note.cs\n// public string? Title { get; set; }\n// public string? Content { get; set; }\n// public string LastModified { get; set; } = null!;\n// public string Created { get; set; } = null!;\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// [Ignore]\n// public int NewNoteId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemMarkerParagraphMap\n// {\n// public int PlaylistItemMarkerId { get; set; }\n// public int MepsDocumentId { get; set; }\n// public int ParagraphIndex { get; set; }\n// public int MarkerIndexWithinParagraph { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemIndependentMediaMap.cs", "score": 40.139620221589794}, {"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemLocationMap.cs", "score": 35.276235533017854}, {"retrieved_chunk": " public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlayListItem.cs", "score": 29.760486252006046}, {"retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Note.cs", "score": 25.37908122532722}, {"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs", "score": 25.258196191223316}]}}, "groundtruth": "Ignore]\n public int NewPlaylistItemMarkerId {", "metadata": {"task_id": "project_cc_csharp/29", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 14, "right_context_start_lineno": 16}} diff --git a/python/tabby-eval/v2-modal/legacy/head10_line_completion_rg1_bm25.jsonl b/python/tabby-eval/v2-modal/legacy/head10_line_completion_rg1_bm25.jsonl new file mode 100644 index 000000000000..6ff3cb42bfda --- /dev/null +++ b/python/tabby-eval/v2-modal/legacy/head10_line_completion_rg1_bm25.jsonl @@ -0,0 +1,10 @@ +{"prompt": "using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary GetLassoProfiles()\n {", "right_context": "\n Dictionary lassoProfiles = new Dictionary();\n\n // Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/27", "repository": "kenshinakh1-LassoProcessManager-bcc481f", "file": "ProcessManager/Providers/ConfigProvider.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 45, "right_context_start_lineno": 47}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ProcessManager/Providers/IConfigProvider.cs\n// ManagerConfig GetManagerConfig();\n// /// \n// /// Geth the list of lasso rules.\n// /// \n// /// \n// List GetRules();\n// Dictionary GetLassoProfiles();\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Models/Configs/ManagerConfig.cs\n// public ProcessRule[] ProcessRules { get; set; }\n// /// \n// /// List of folders rules.\n// /// \n// public FolderRule[] FolderRules { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// public void Dispose()\n// {\n// if (processStartEvent != null) \n// {\n// processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n// processStartEvent.Dispose();\n// processStartEvent = null;\n// }\n// }\n// public bool Setup()\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// {\n// int failCount = 0;\n// Dictionary successCount = new Dictionary();\n// foreach (var process in Process.GetProcesses())\n// {\n// LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n// bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n// if (success)\n// {\n// if (!successCount.ContainsKey(profileName))\n\n", "list": [{"retrieved_chunk": " ManagerConfig GetManagerConfig();\n /// \n /// Geth the list of lasso rules.\n /// \n /// \n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}", "filename": "ProcessManager/Providers/IConfigProvider.cs", "score": 22.799994275269317}, {"retrieved_chunk": " public ProcessRule[] ProcessRules { get; set; }\n /// \n /// List of folders rules.\n /// \n public FolderRule[] FolderRules { get; set; }\n }\n}", "filename": "ProcessManager/Models/Configs/ManagerConfig.cs", "score": 20.728193497923062}, {"retrieved_chunk": " public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 14.506247294243275}, {"retrieved_chunk": " {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 11.789149115850975}]}, "prediction": " LassoProfile> GetLassoProfiles()\n {\n Dictionary lassoProfiles = new Dictionary();\n foreach (var rule in GetRules())\n {\n if (rule is LassoRule lassoRule)\n {\n lassoProfiles.Add(lassoRule.ProfileName, lassoRule.Profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n {\n string configPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName"} +{"prompt": "//#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(", "groundtruth": "InstallerEntryData installerEntryData)\n\t\t{", "right_context": "\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n", "metadata": {"task_id": "project_cc_csharp/55", "repository": "NathanWarden-ready-to-launch-58eba6d", "file": "godot-project/Scripts/DataManagement/DataPaths.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 94, "right_context_start_lineno": 96}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\t\tBuildProjectsList();\n// \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n// \t\t\t\t\t{\n// \t\t\t\t\t\tLaunchInstaller(entry);\n// \t\t\t\t\t\treturn;\n// \t\t\t\t\t}\n// \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n// \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n// \t\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n// \t\t\t\t\treturn;\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/FileHelper.cs\n// \t{\n// \t\tGD.Print(\"*********** Delete file!\");\n// \t}\n// \tprivate static void CreateDirectoryForUser(string directory)\n// \t{\n// \t\tvar path = Path.Combine(BasePath, directory);\n// \t\tif (!DirAccess.DirExistsAbsolute(path))\n// \t\t{\n// \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n// \t\t}\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n// \t\t\t};\n// \t\t\tprojectEntries.Add(project);\n// \t\t\tLaunchProject(directoryPath, false);\n// \t\t}\n// \t\tvoid _onFilesDropped(string[] files)\n// \t\t{\n// \t\t\tfor (int i = 0; i < files.Length; i++)\n// \t\t\t{\n// \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/FileHelper.cs\n// \t}\n// \tpublic static void WriteUserText(string path, string json)\n// \t{\n// \t\tWriteAllText(PathCombine(BasePath, path), json);\n// \t}\n// \tpublic static bool UserFileExists(string path)\n// \t{\n// \t\treturn FileExists(PathCombine(BasePath, path));\n// \t}\n// \tpublic static void Delete(string path)\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\tInstallVersion(versionKey);\n// \t\t\t}\n// \t\t\tSaveProjectsList();\n// \t\t\tBuildProjectsList();\n// \t\t}\n// \t\tvoid SaveConfig()\n// \t\t{\n// \t\t\tvar json = DataBuilder.GetConfigJson(config);\n// \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n// \t\t}\n\n", "list": [{"retrieved_chunk": "\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 29.431886867394642}, {"retrieved_chunk": "\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}", "filename": "godot-project/Scripts/DataManagement/FileHelper.cs", "score": 16.13486385582849}, {"retrieved_chunk": "\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 14.892200276853623}, {"retrieved_chunk": "\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)", "filename": "godot-project/Scripts/DataManagement/FileHelper.cs", "score": 13.921454071982678}, {"retrieved_chunk": "\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 13.535088476589515}]}, "prediction": "string path)\n\t\t{\n\t\t\treturn File.Exists(path);\n\t\t}"} +{"prompt": "using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [", "groundtruth": "JsonProperty(\"likes_given\")]\n public int LikesGiven {", "right_context": " get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/48", "repository": "chanos-dev-dotnetdev-badge-5740a40", "file": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 8}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs\n// private const string BADGE_URL = \"https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true\";\n// private const string SUMMARY_URL = \"https://forum.dotnetdev.kr/u/{0}/summary.json\";\n// private readonly IHttpClientFactory _httpClientFactory;\n// public ForumDataProvider(IHttpClientFactory httpClientFactory)\n// {\n// _httpClientFactory = httpClientFactory;\n// }\n// private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n// {\n// using HttpClient client = _httpClientFactory.CreateClient();\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs\n// public string Username { get; set; }\n// [JsonProperty(\"name\")]\n// public string Name { get; set; }\n// [JsonProperty(\"avatar_template\")]\n// public string AvatarTemplate { get; set; }\n// [JsonProperty(\"flair_name\")]\n// public object FlairName { get; set; }\n// [JsonProperty(\"trust_level\")]\n// public int TrustLevel { get; set; }\n// [JsonProperty(\"admin\")]\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs\n// \ufeffusing DotNetDevBadgeWeb.Model;\n// namespace DotNetDevBadgeWeb.Interfaces\n// {\n// public interface IProvider\n// {\n// Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n// Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n// Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n// }\n// }\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs\n// private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n// private readonly IProvider _forumProvider;\n// private readonly IMeasureTextV1 _measureTextV1;\n// public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n// {\n// _forumProvider = forumProvider;\n// _measureTextV1 = measureTextV1;\n// }\n// public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n// {\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs\n// {\n// app.UseMiddleware();\n// app.MapBadgeEndpointsV1();\n// return app;\n// }\n// internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n// {\n// app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n// {\n// string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n", "list": [{"retrieved_chunk": " private const string BADGE_URL = \"https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https://forum.dotnetdev.kr/u/{0}/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs", "score": 20.998481641894454}, {"retrieved_chunk": " public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "score": 20.73346729938653}, {"retrieved_chunk": "\ufeffusing DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs", "score": 12.088199207115517}, {"retrieved_chunk": " private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs", "score": 10.738553623860039}, {"retrieved_chunk": " {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs", "score": 7.998097817927588}]}, "prediction": "JsonProperty(\"badge_counts\")]\n public BadgeCounts BadgeCounts { get; set; }\n\n [JsonProperty(\"badge_summary\")]\n public BadgeSummary BadgeSummary { get; set; }\n\n [JsonProperty(\"badges\")]\n public Badge[] Badges { get; set; }\n\n [JsonProperty(\"user\")]\n public User User { get; set; }\n }\n\n public class BadgeCounts\n {\n [JsonProperty(\"bronze\")]\n public int Bronze { get; set; }\n\n [JsonProperty(\"silver\")]\n public int Silver { get; set; }\n\n [JsonProperty(\"gold\")]\n public int Gold {"} +{"prompt": "using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<", "groundtruth": "JXLWorkbookData> WorkbooksData {", "right_context": " get; set; } = new List();\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/50", "repository": "JdeJabali-JXLDataTableExtractor-90a12f4", "file": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLDataExtracted.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 7}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs\n// {\n// public List Workbooks { get; set; } = new List();\n// public int SearchLimitRow { get; set; }\n// public int SearchLimitColumn { get; set; }\n// public List WorksheetIndexes { get; set; } = new List();\n// public List Worksheets { get; set; } = new List();\n// public bool ReadAllWorksheets { get; set; }\n// public List HeadersToSearch { get; set; } = new List();\n// public DataTable GetDataTable()\n// {\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs\n// public class DataTableExtractor :\n// IDataTableExtractorConfiguration,\n// IDataTableExtractorWorkbookConfiguration,\n// IDataTableExtractorSearchConfiguration,\n// IDataTableExtractorWorksheetConfiguration\n// {\n// private bool _readAllWorksheets;\n// private int _searchLimitRow;\n// private int _searchLimitColumn;\n// private readonly List _workbooks = new List();\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorksheetData.cs\n// \ufeffusing System.Collections.Generic;\n// namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n// {\n// public class JXLWorksheetData\n// {\n// public string WorksheetName { get; set; } = string.Empty;\n// public List Rows { get; set; } = new List();\n// }\n// }\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLExtractedRow.cs\n// \ufeffusing System.Collections.Generic;\n// namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n// {\n// public class JXLExtractedRow\n// {\n// public Dictionary Columns { get; set; } = new Dictionary();\n// }\n// }\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/Configuration/IDataExtraction.cs\n// /// \n// /// \n// List GetWorkbooksData();\n// /// \n// /// Only retrieves the extracted rows from all the workbooks and worksheets.\n// /// \n// /// \n// /// \n// List GetExtractedRows();\n// /// \n\n", "list": [{"retrieved_chunk": " {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {", "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "score": 21.880390238660006}, {"retrieved_chunk": " public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();", "filename": "JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs", "score": 20.597128248615988}, {"retrieved_chunk": "\ufeffusing System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}", "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorksheetData.cs", "score": 20.44056373724002}, {"retrieved_chunk": "\ufeffusing System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}", "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLExtractedRow.cs", "score": 20.174278440276893}, {"retrieved_chunk": " /// \n /// \n List GetWorkbooksData();\n /// \n /// Only retrieves the extracted rows from all the workbooks and worksheets.\n /// \n /// \n /// \n List GetExtractedRows();\n /// ", "filename": "JdeJabali.JXLDataTableExtractor/Configuration/IDataExtraction.cs", "score": 19.028401583774812}]}, "prediction": "JXLWorksheetData> Worksheets { get; set; } = new List();\n }"} +{"prompt": "using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ", "groundtruth": "WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {", "right_context": "\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/68", "repository": "TRA-Tech-dotnet-websocket-9049854", "file": "src/WebSocketHub/Core/src/WebSocketHubMiddleware.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 17, "right_context_start_lineno": 19}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/ExampleWebApplication/Controllers/WebSocket2Controller.cs\n// public WebSocket2Controller(WebSocketHub webSocketHub)\n// {\n// _webSocketHub = webSocketHub;\n// }\n// [HttpGet(\"GetSocketListWithSelector\")]\n// public IActionResult GetSocketListWithSelector(int id)\n// {\n// var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n// return Ok(socketListOfUser);\n// }\n\n// the below code fragment can be found in:\n// src/ExampleWebApplication/Controllers/WebSocket1Controller.cs\n// {\n// _webSocketHub = webSocketHub;\n// }\n// [HttpGet(\"GetSocketList\")]\n// public IActionResult GetSocketList(int id)\n// {\n// var socketListOfUser = _webSocketHub.GetSocketList(id);\n// return Ok(socketListOfUser);\n// }\n// [HttpGet(\"GetSocketListWithSelector\")]\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketRequestHandlerProvider.cs\n// /// Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n// /// \n// /// The type of WebSocket request handler to add.\n// /// The message type associated with the WebSocket request handler.\n// /// true if the WebSocket request handler was added to the handler type map; otherwise, false.\n// /// Thrown when is not assignable from IWebSocketRequestHandler.\n// /// \n// /// This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n// /// \n// public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketHub.cs\n// public WebSocketHub(IOptions options)\n// {\n// if (options == null) throw new ArgumentNullException(nameof(options));\n// Options = options.Value;\n// _webSocketDictionary = new();\n// }\n// /// \n// /// Encodes the specified Message object into a UTF-8 encoded byte array.\n// /// \n// /// The Message object to encode.\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketHub.cs\n// private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n// public WebSocketHubOptions Options { get; private set; }\n// /// \n// /// Initializes a new instance of the WebSocketHub class with the specified options.\n// /// \n// /// The options to configure the WebSocketHub.\n// /// Thrown when is null.\n// /// \n// /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n// /// \n\n", "list": [{"retrieved_chunk": " public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }", "filename": "src/ExampleWebApplication/Controllers/WebSocket2Controller.cs", "score": 45.19935267420081}, {"retrieved_chunk": " {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]", "filename": "src/ExampleWebApplication/Controllers/WebSocket1Controller.cs", "score": 45.02333198140999}, {"retrieved_chunk": " /// Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n /// \n /// The type of WebSocket request handler to add.\n /// The message type associated with the WebSocket request handler.\n /// true if the WebSocket request handler was added to the handler type map; otherwise, false.\n /// Thrown when is not assignable from IWebSocketRequestHandler.\n /// \n /// This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n /// \n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)", "filename": "src/WebSocketHub/Core/src/WebSocketRequestHandlerProvider.cs", "score": 38.98487610590298}, {"retrieved_chunk": " public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n /// \n /// Encodes the specified Message object into a UTF-8 encoded byte array.\n /// \n /// The Message object to encode.", "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "score": 37.98681211524358}, {"retrieved_chunk": " private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n /// \n /// Initializes a new instance of the WebSocketHub class with the specified options.\n /// \n /// The options to configure the WebSocketHub.\n /// Thrown when is null.\n /// \n /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n /// ", "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "score": 31.71651588733243}]}, "prediction": " Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {\n _serviceProvider = serviceProvider;\n _next = next;\n _acceptIf = acceptIf;\n _webSocketHub = webSocketHub;\n _keyGenerator = keyGenerator;\n _receiveBuffer = new byte[1024 * 4];\n }\n\n public async Task Invoke(HttpContext context)\n {\n if (!_acceptIf(context))\n {\n await _next(context);\n return;\n }\n\n var webSocket = await context."} +{"prompt": "using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; // in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n /// \n /// Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n /// \n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n /// \n /// The Xbox memory stream.\n /// \n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<", "groundtruth": "Thread> Threads => GetThreads();", "right_context": "\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n // init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n // enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n // custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length / 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n // argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n // argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], // initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n // optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n // peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n // call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n // cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n /// \n /// Calls an Xbox function.\n /// \n /// The function address.\n /// The function arguments.\n /// Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.\n public uint Call(long address, params object[] args)\n {\n // TODO: call context (~4039+ which requires qwordparam)\n\n // injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n /// \n /// Original Xbox Debug Monitor runtime patches.\n /// Prevents crashdumps from being written to the HDD and enables remote code execution.\n /// \n /// \n private void PatchXbdm(Xbox target)\n {\n // the spin routine to be patched in after the signature patterns\n // spin:\n // jmp spin\n // int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n // prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n // this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n // labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); // pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); // size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n //asm.push(__dword_ptr[ebx + 8]);\n //asm.call((uint)target.Signatures[\"DmFreePool\"]);\n //asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); // buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); // address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n // 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n // labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n // prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); // carve out arbitrary space for local temp variables\n asm.pushad();\n\n // disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n // arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n // local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n // check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); // 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n // call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n // thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n // determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); // 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n // get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); // 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n // push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n // get argument name\n asm.push(edi); // argument index\n asm.push(argFormatStringAddress); // format string address\n asm.lea(eax, __dword_ptr[argName]); // argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n // check if it's included in the command\n asm.lea(eax, __[temp]); // argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); // argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); // command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n // push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n // move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n // perform the call\n asm.call(__dword_ptr[callAddress]);\n\n // print response message\n asm.push(eax); // integer return value\n asm.push(returnFormatAddress); // format string address\n asm.push(__dword_ptr[responseAddress]); // response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n // TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n // get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); // address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n //asm.mov(eax, 0x2000); // TODO: increase pool size?\n //asm.push(eax);\n //asm.call((uint)target.Signatures[\"DmAllocatePool\"]); // TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); // buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); // buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n // if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n // generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n // successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n // generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n // original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n // inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n // read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n // disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n // formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n // convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n // skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n // optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n // output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n // optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n // output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n // NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n // universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n // mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n // mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n // mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n // universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n // mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n // mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n // universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n // jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n // push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n // mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n // universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n // mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n // jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n // retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n // universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n // test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n // push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n // early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n // mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n // mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n // later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n // mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n // mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n // xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha/dvt3/dvt4/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n // mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n // mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n // early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n // push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n // mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n // push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n // later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n // push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n // retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n // universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n // cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n // read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n // scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n // cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // TODO: dispose managed state (managed objects)\n }\n\n // TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n // TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/20", "repository": "Ernegien-OGXbdmDumper-07a1e82", "file": "src/OGXbdmDumper/Xbox.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 75, "right_context_start_lineno": 76}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/ConnectionInfo.cs\n// var connections = new List();\n// byte[] datagramBuffer = new byte[1024];\n// // iterate through each network interface\n// Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n// {\n// // only worry about active IPv4 interfaces\n// if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n// return;\n// // iterate through each ip address assigned to the interface\n// Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Connection.cs\n// /// \n// /// Initializes the session.\n// /// \n// public Connection()\n// {\n// // initialize defaults\n// Reader = new BinaryReader(this);\n// Writer = new BinaryWriter(this);\n// ResetTcp();\n// }\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Connection.cs\n// /// \n// /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n// /// \n// public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n// /// \n// /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n// /// \n// public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n// #endregion\n// #region Construction\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Kernel.cs\n// throw new ArgumentNullException(nameof(xbox));\n// Module = xbox.Modules.Find(m => m.Name == Name) ??\n// throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n// // TODO: remove 3rd-party dependency with proper PE parsing logic\n// // grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n// var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n// int size = (int)(initSection.Base - Address);\n// var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n// // resolve exports\n// Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Kernel.cs\n// /// The kernel exports.\n// /// \n// public KernelExports Exports { get; private set; }\n// /// \n// /// Initializes communication with the Xbox kernel.\n// /// \n// /// \n// public Kernel(Xbox xbox)\n// {\n// _xbox = xbox ??\n\n", "list": [{"retrieved_chunk": " var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n // iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n // only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n // iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>", "filename": "src/OGXbdmDumper/ConnectionInfo.cs", "score": 66.55166457984245}, {"retrieved_chunk": " /// \n /// Initializes the session.\n /// \n public Connection()\n {\n // initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }", "filename": "src/OGXbdmDumper/Connection.cs", "score": 65.61480573217976}, {"retrieved_chunk": " /// \n /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n /// \n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n /// \n /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n /// \n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction", "filename": "src/OGXbdmDumper/Connection.cs", "score": 63.14871472847682}, {"retrieved_chunk": " throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n // TODO: remove 3rd-party dependency with proper PE parsing logic\n // grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n // resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);", "filename": "src/OGXbdmDumper/Kernel.cs", "score": 62.61533660943069}, {"retrieved_chunk": " /// The kernel exports.\n /// \n public KernelExports Exports { get; private set; }\n /// \n /// Initializes communication with the Xbox kernel.\n /// \n /// \n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??", "filename": "src/OGXbdmDumper/Kernel.cs", "score": 60.88570669473385}]}, "prediction": "Module> GetModules()\n {\n var modules = new List();\n foreach (var module in Session.SendCommand(\"listmodules\"))\n {\n var moduleInfo = new Module(module);\n modules.Add(moduleInfo);\n }\n return modules;\n }\n\n public Module? GetModule(string name)\n {\n foreach (var module in Modules)\n {\n if (module.Name == name) return module;\n }\n return null;\n }\n\n public Module? GetModule(int index)\n {\n if (index < 0 || index >= Modules.Count) return null"} +{"prompt": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [", "groundtruth": "Ignore]\n public int NoteId {", "right_context": " get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/51", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/Note.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 8}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/JWDal.cs\n// {\n// connectionString = $\"Data Source={dbPath}\";\n// }\n// public IEnumerable TableList()\n// {\n// using (IDbConnection cnn = new SQLiteConnection(connectionString))\n// {\n// return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/InputField.cs\n// \ufeffusing JWLSLMerge.Data.Attributes;\n// namespace JWLSLMerge.Data.Models\n// {\n// public class InputField\n// {\n// public int LocationId { get; set; }\n// public string TextTag { get; set; } = null!;\n// public string Value { get; set; } = null!;\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Tag.cs\n// public int NewTagId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge/MergeService.cs\n// private readonly string targetPath = null!;\n// private readonly string targetDbFile = null!;\n// private string lastModified = null!;\n// public MergeService()\n// {\n// targetPath = Environment.GetTargetDirectory();\n// targetDbFile = Environment.GetDbFile();\n// }\n// public void Run(string[] jwlibraryFiles)\n// {\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/UserMark.cs\n// public string UserMarkGuid { get; set; } = null!;\n// public int Version { get; set; }\n// [Ignore]\n// public int NewUserMarkId { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": " {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }", "filename": "JWLSLMerge.Data/JWDal.cs", "score": 13.78401506779753}, {"retrieved_chunk": "\ufeffusing JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}", "filename": "JWLSLMerge.Data/Models/InputField.cs", "score": 13.000811547599904}, {"retrieved_chunk": " public int NewTagId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Tag.cs", "score": 12.828308464376727}, {"retrieved_chunk": " private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {", "filename": "JWLSLMerge/MergeService.cs", "score": 12.77934094725121}, {"retrieved_chunk": " public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/UserMark.cs", "score": 12.358601363000677}]}, "prediction": "PrimaryKey]\n public int NoteId { get; set; }\n public string Text { get; set; } = null!;\n public int NewNoteId { get; set; }\n }"} +{"prompt": "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n /// \n /// \u5e94\u7528\u5de5\u4f5c\u76ee\u5f55\n /// \n /// \u542f\u52a8\u53c2\u6570\n /// \n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"\u7cfb\u7edf\u5df2\u5b58\u5728\u540c\u540d\u4f46\u4e0d\u540c\u8def\u5f84\u7684\u670d\u52a1\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ", "groundtruth": "SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {", "right_context": "\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n /// \n /// \u505c\u6b62\u5e76\u5220\u9664\u670d\u52a1\n /// \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n // \u8fd9\u91cc\u4e0d\u9700\u8981\u6062\u590dSERVICE_CONFIG_FAILURE_ACTIONS\uff0c\u56e0\u4e3a\u4e0b\u9762\u6211\u4eec\u8981\u5220\u9664\u670d\u52a1\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"\u7b49\u5f85\u670d\u52a1\u505c\u6b62\u8d85\u8fc7\u4e86{maxWaitTime.TotalSeconds}\u79d2\");\n }\n\n /// \n /// \u5c1d\u8bd5\u83b7\u53d6\u670d\u52a1\u7684\u8fdb\u7a0bid\n /// \n /// \n /// \n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/14", "repository": "xljiulang-ServiceSelf-7f8604b", "file": "ServiceSelf/WindowsService.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 66, "right_context_start_lineno": 68}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// }\n// var linuxOptions = CreateLinuxOptions(filePath, options);\n// using (var fileStream = File.OpenWrite(unitFilePath))\n// {\n// using var wirter = new StreamWriter(fileStream);\n// linuxOptions.WriteTo(wirter);\n// }\n// // SELinux\n// Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n// SystemControl(\"daemon-reload\", showError: true);\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// break;\n// }\n// }\n// if (filePath.IsEmpty || wantedBy.IsEmpty)\n// {\n// return ReadOnlySpan.Empty;\n// }\n// var wants = $\"{wantedBy.ToString()}.wants\";\n// var unitFileName = Path.GetFileName(unitFilePath);\n// var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// if (geteuid() != 0)\n// {\n// throw new UnauthorizedAccessException(\"\u65e0\u6cd5\u64cd\u4f5c\u670d\u52a1\uff1a\u6ca1\u6709root\u6743\u9650\");\n// }\n// }\n// }\n// }\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// line = line[execStartPrefix.Length..];\n// var index = line.IndexOf(' ');\n// filePath = index < 0 ? line : line[..index];\n// }\n// else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n// {\n// wantedBy = line[wantedByPrefix.Length..].Trim();\n// }\n// if (filePath.Length > 0 && wantedBy.Length > 0)\n// {\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// {\n// execStart = $\"{filePath} {string.Join(' ', args)}\";\n// }\n// }\n// var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n// ? Path.GetDirectoryName(filePath)\n// : Path.GetFullPath(options.WorkingDirectory);\n// var linuxOptions = options.Linux.Clone();\n// linuxOptions.Unit[\"Description\"] = options.Description;\n// linuxOptions.Service[\"ExecStart\"] = execStart;\n\n", "list": [{"retrieved_chunk": " }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n // SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);", "filename": "ServiceSelf/LinuxService.cs", "score": 53.22018771652771}, {"retrieved_chunk": " break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);", "filename": "ServiceSelf/LinuxService.cs", "score": 21.470485420837036}, {"retrieved_chunk": " if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"\u65e0\u6cd5\u64cd\u4f5c\u670d\u52a1\uff1a\u6ca1\u6709root\u6743\u9650\");\n }\n }\n }\n}", "filename": "ServiceSelf/LinuxService.cs", "score": 12.934142972279112}, {"retrieved_chunk": " line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {", "filename": "ServiceSelf/LinuxService.cs", "score": 12.544725417438247}, {"retrieved_chunk": " {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;", "filename": "ServiceSelf/LinuxService.cs", "score": 12.519455560002188}]}, "prediction": " string QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n var serviceFilePath = new StringBuilder(256);\n var serviceFilePathLength = serviceFilePath.Capacity;\n if (QueryServiceConfig(serviceHandle, serviceFilePath, serviceFilePathLength, out var bytesNeeded) == false)\n {\n throw new Win32Exception();\n }\n serviceFilePath.Capacity = bytesNeeded;\n return serviceFilePath.ToString();\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStop(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null"} +{"prompt": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [", "groundtruth": "Ignore]\n public int NewPlaylistItemId {", "right_context": " get; set; }\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/37", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/PlayListItem.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 15, "right_context_start_lineno": 17}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemMarker.cs\n// public long DurationTicks { get; set; }\n// public long EndTransitionDurationTicks { get; set; }\n// [Ignore]\n// public int NewPlaylistItemMarkerId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Note.cs\n// public string? Title { get; set; }\n// public string? Content { get; set; }\n// public string LastModified { get; set; } = null!;\n// public string Created { get; set; } = null!;\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// [Ignore]\n// public int NewNoteId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/UserMark.cs\n// public string UserMarkGuid { get; set; } = null!;\n// public int Version { get; set; }\n// [Ignore]\n// public int NewUserMarkId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Location.cs\n// public int? Track { get; set; }\n// public int IssueTagNumber { get; set; }\n// public string? KeySymbol { get; set; }\n// public int? MepsLanguage { get; set; }\n// public int Type { get; set; }\n// public string? Title { get; set; }\n// [Ignore]\n// public int NewLocationId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Bookmark.cs\n// public string Title { get; set; } = null!;\n// public string? Snippet { get; set; }\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": " public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs", "score": 35.26889876052275}, {"retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Note.cs", "score": 33.518184487704545}, {"retrieved_chunk": " public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/UserMark.cs", "score": 32.64848873570582}, {"retrieved_chunk": " public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Location.cs", "score": 31.624913532715233}, {"retrieved_chunk": " public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Bookmark.cs", "score": 31.183025189281004}]}, "prediction": "Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n\n public class Note\n {\n [Ignore]\n public int NoteId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }"} +{"prompt": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [", "groundtruth": "Ignore]\n public int NewPlaylistItemMarkerId {", "right_context": " get; set; }\n }\n}\n", "metadata": {"task_id": "project_cc_csharp/29", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 14, "right_context_start_lineno": 16}, "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemIndependentMediaMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemIndependentMediaMap\n// {\n// public int PlaylistItemId { get; set; }\n// public int IndependentMediaId { get; set; }\n// public long DurationTicks { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemLocationMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemLocationMap\n// {\n// public int PlaylistItemId { get; set; }\n// public int LocationId { get; set; }\n// public int MajorMultimediaType { get; set; }\n// public long? BaseDurationTicks { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlayListItem.cs\n// public int Accuracy { get; set; }\n// public int EndAction { get; set; }\n// public string ThumbnailFilePath { get; set; } = null!;\n// [Ignore]\n// public int NewPlaylistItemId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Note.cs\n// public string? Title { get; set; }\n// public string? Content { get; set; }\n// public string LastModified { get; set; } = null!;\n// public string Created { get; set; } = null!;\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// [Ignore]\n// public int NewNoteId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemMarkerParagraphMap\n// {\n// public int PlaylistItemMarkerId { get; set; }\n// public int MepsDocumentId { get; set; }\n// public int ParagraphIndex { get; set; }\n// public int MarkerIndexWithinParagraph { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemIndependentMediaMap.cs", "score": 40.139620221589794}, {"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemLocationMap.cs", "score": 35.276235533017854}, {"retrieved_chunk": " public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlayListItem.cs", "score": 29.760486252006046}, {"retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Note.cs", "score": 25.37908122532722}, {"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs", "score": 25.258196191223316}]}, "prediction": "Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }"} diff --git a/python/tabby-eval/v2-modal/legacy/transform_legacy_data.py b/python/tabby-eval/v2-modal/legacy/transform_legacy_data.py new file mode 100755 index 000000000000..81b804156d46 --- /dev/null +++ b/python/tabby-eval/v2-modal/legacy/transform_legacy_data.py @@ -0,0 +1,44 @@ +import argparse +import json +import logging + +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' +) + + +def transform(language: str, + legacy_jsonl_file: str, + output_data_jsonl_file: str): + logging.info(f"Start transforming legacy data from {legacy_jsonl_file} to new format.") + + with open(legacy_jsonl_file, 'r') as source_file, open(output_data_jsonl_file, 'w') as destination_file: + for line in source_file: + source_data = json.loads(line) + + transformed_data = { + "language": language, + "segments": { + "prefix": source_data["prompt"], + "suffix": source_data["right_context"], + "crossfile_context": source_data["crossfile_context"] + }, + "groundtruth": source_data["groundtruth"], + "metadata": source_data["metadata"] + } + + destination_file.write(json.dumps(transformed_data) + '\n') + + logging.info(f"End transforming legacy data to {output_data_jsonl_file}.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="transform legacy jsonl file to new format.") + parser.add_argument("--language", type=str, help="programming language.") + parser.add_argument("--legacy_jsonl_file", type=str, help="legacy jsonl file.") + parser.add_argument("--output_data_jsonl_file", type=str, help="output data jsonl file.") + + args = parser.parse_args() + transform(args.language, args.legacy_jsonl_file, args.output_data_jsonl_file) From 350f9d908d8dbecdbf8c42f8f8316ca152060fe9 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 15:32:47 +0800 Subject: [PATCH 15/19] Eval-V2-Modal: add two types requests to eval code completion. --- .../20240717-StarCoder-1B-evaluation.jsonl | 2 - .../v2-modal/20240717-StarCoder-1B.jsonl | 2 - python/tabby-eval/v2-modal/README.md | 24 ++--- python/tabby-eval/v2-modal/app.py | 5 +- .../v2-modal/compute_code_completion.py | 100 ++++++++++++++---- python/tabby-eval/v2-modal/compute_metrics.py | 8 +- python/tabby-eval/v2-modal/data.jsonl | 2 - ...der-1B-cross-file-content-evaluation.jsonl | 1 + ...der-1B-cross-file-content-prediction.jsonl | 1 + .../20240717-StarCoder-1B-evaluation.jsonl | 1 + .../20240717-StarCoder-1B-prediction.jsonl | 1 + .../tabby-eval/v2-modal/data/one-record.jsonl | 1 + .../v2-modal/data/ten-records.jsonl | 10 ++ 13 files changed, 114 insertions(+), 44 deletions(-) delete mode 100644 python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl delete mode 100644 python/tabby-eval/v2-modal/20240717-StarCoder-1B.jsonl delete mode 100644 python/tabby-eval/v2-modal/data.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl create mode 100644 python/tabby-eval/v2-modal/data/one-record.jsonl create mode 100644 python/tabby-eval/v2-modal/data/ten-records.jsonl diff --git a/python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl b/python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl deleted file mode 100644 index 647ca56cf686..000000000000 --- a/python/tabby-eval/v2-modal/20240717-StarCoder-1B-evaluation.jsonl +++ /dev/null @@ -1,2 +0,0 @@ -{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else 1 + fib(n - 1)","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.4,"line_accuracy":0.0,"avg_line_edit_distance":0.0} -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/20240717-StarCoder-1B.jsonl b/python/tabby-eval/v2-modal/20240717-StarCoder-1B.jsonl deleted file mode 100644 index 68a9717be62c..000000000000 --- a/python/tabby-eval/v2-modal/20240717-StarCoder-1B.jsonl +++ /dev/null @@ -1,2 +0,0 @@ -{"language":"python","groundtruth":"\n if n <= 1:\n return n\n else:","segments.prefix":"def fib(n):\n ","segments.suffix":"\n return fib(n - 1) + fib(n - 2)","prediction":"return 1 if n == 0 else 1 + fib(n - 1)","prediction_status":"success"} -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index a04b6c181146..4e672d3b802a 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -18,9 +18,8 @@ python compute_code_completion.py \ --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ - --jsonl_file data.jsonl \ - --output_prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ - --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl + --jsonl_file data/one-record.jsonl \ + --output_jsonl_file_prefix data/20240717-StarCoder-1B ``` This script will call the Tabby service and evaluate the quality of code completion. The script’s parameters are as follows: @@ -28,8 +27,7 @@ This script will call the Tabby service and evaluate the quality of code complet ```bash python compute_code_completion.py -h usage: compute_code_completion.py [-h] --endpoint ENDPOINT --token TOKEN --model MODEL [--jsonl_file JSONL_FILE] - [--output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE] - [--output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE] + [--output_jsonl_file_prefix OUTPUT_JSONL_FILE_PREFIX] [--start_tabby_server_on_modal START_TABBY_SERVER_ON_MODAL] eval tabby code completion. @@ -41,10 +39,9 @@ options: --model MODEL evaluation model. --jsonl_file JSONL_FILE evaluation jsonl file. - --output_prediction_jsonl_file OUTPUT_PREDICTION_JSONL_FILE - output prediction jsonl file. - --output_evaluation_jsonl_file OUTPUT_EVALUATION_JSONL_FILE - output evaluation jsonl file. + --output_jsonl_file_prefix OUTPUT_JSONL_FILE_PREFIX + output jsonl file prefix, it will generate four files: prediction, evaluation, cross_file_content_prediction, + cross_file_content_evaluation. --start_tabby_server_on_modal START_TABBY_SERVER_ON_MODAL start tabby server on modal manager, accepts 1 or another. ``` @@ -57,8 +54,7 @@ python compute_code_completion.py \ --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ --jsonl_file data.jsonl \ - --output_prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ - --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl \ + --output_jsonl_file_prefix data/20240717-StarCoder-1B \ --start_tabby_server_on_modal 0 ``` @@ -66,8 +62,8 @@ If you have a JSONL file with code completion results, you can use the `compute_ ```bash python compute_metrics.py \ - --prediction_jsonl_file 20240717-StarCoder-1B.jsonl \ - --output_evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl + --prediction_jsonl_file data/20240717-StarCoder-1B-prediction.jsonl \ + --output_evaluation_jsonl_file data/20240717-StarCoder-1B-evaluation.jsonl ``` The script’s parameters are as follows: @@ -90,7 +86,7 @@ options: If you have a JSONL file with evaluation results, you can use the `avg_metrics.py` script. Example: ```bash -python avg_metrics.py --evaluation_jsonl_file 20240717-StarCoder-1B-evaluation.jsonl +python avg_metrics.py --evaluation_jsonl_file data/20240717-StarCoder-1B-evaluation.jsonl ``` The script’s parameters are as follows: diff --git a/python/tabby-eval/v2-modal/app.py b/python/tabby-eval/v2-modal/app.py index 4ac566c7dc20..9750b18fe69c 100755 --- a/python/tabby-eval/v2-modal/app.py +++ b/python/tabby-eval/v2-modal/app.py @@ -14,7 +14,7 @@ MODEL_ID = os.getenv("MODEL_ID") # TODO: If you're testing large datasets, consider using a better GPU and higher parallelism -GPU_CONFIG = gpu.T4() +GPU_CONFIG = gpu.A10G() TABBY_BIN = "/opt/tabby/bin/tabby" @@ -63,7 +63,8 @@ def download_model(model_id: str): _allow_background_volume_commits=True, concurrency_limit=1, cpu=20.0, - memory=16 * 1024, + memory=24 * 1024, + keep_warm=1, ) @asgi_app() def app_serve(): diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index 742d7bc2849c..71ac9929f2b5 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -102,7 +102,37 @@ def send_request_with_retry(url, headers, payload, timeout=10, max_retries=10): return response -def generate_predictions(endpoint: str, token: str, jsonl_file: str, output_prediction_jsonl_file: str): +def parse_model_id(model_id: str): + parts = model_id.split('/') + if len(parts) == 1: + return "TabbyML", parts[0] + elif len(parts) == 2: + return parts[0], parts[1] + else: + raise ValueError(f"Invalid model id {model_id}") + + +def get_model_prompt_template(model_id: str): + registry, model_name = parse_model_id(model_id) + url = f"https://raw.githubusercontent.com/{registry}/registry-tabby/main/models.json" + + response = httpx.get(url=url) + response.raise_for_status() + + for model in response.json(): + if model["name"] == model_name: + return model.get("prompt_template", None) + + return None + + +def generate_predictions(endpoint: str, + token: str, + jsonl_file: str, + prediction_jsonl_file: str, + data_function, + prompt_template: str = None): + logging.info(f"Generating predictions to {prediction_jsonl_file}...") df = pd.read_json(jsonl_file, lines=True) df_flat = json_normalize(df.to_dict(orient="records")) @@ -115,17 +145,11 @@ def generate_predictions(endpoint: str, token: str, jsonl_file: str, output_pred predictions = [] prediction_status = [] for index, row in df_flat.iterrows(): - payload = { - "language": row['language'], - "segments": { - "prefix": row['segments.prefix'], - "suffix": row['segments.suffix'] - } - } + data = data_function(row, prompt_template) if prompt_template else data_function(row) # TODO: Add parallelism support url = f"{endpoint}/v1/completions" - response = send_request_with_retry(url, headers, payload, timeout=10, max_retries=10) + response = send_request_with_retry(url, headers, data, timeout=10, max_retries=10) if response.status_code == 200: predictions.append(response.json()['choices'][0]['text']) @@ -143,15 +167,44 @@ def generate_predictions(endpoint: str, token: str, jsonl_file: str, output_pred failed_count = total_records - success_count logging.info(f"Total predictions: {total_records}, Success: {success_count}, Failed: {failed_count}") - df_success.to_json(output_prediction_jsonl_file, orient='records', lines=True) + df_success.to_json(prediction_jsonl_file, orient='records', lines=True) + + +def default_data_function(row): + return { + "language": row['language'], + "segments": { + "prefix": row['segments.prefix'], + "suffix": row['segments.suffix'] + } + } + + +def cross_file_data_function(row, prompt_template): + crossfile_context_list = row['segments.crossfile_context.list'] + sorted_list = sorted(crossfile_context_list, key=lambda x: x['score']) + + combined_context = "\n".join( + f"// {item['filename']}\n// {item['retrieved_chunk']}" for item in sorted_list + ) + "\n" + + return { + "debug_options": { + "raw_prompt": combined_context + prompt_template.format( + prefix=row['segments.prefix'], + suffix=row['segments.suffix']) + } + } def eval_code_completion(endpoint: str, token: str, model: str, jsonl_file: str, - output_prediction_jsonl_file: str, - output_evaluation_jsonl_file: str, + prediction_jsonl_file: str, + evaluation_jsonl_file: str, + cross_file_content_prediction_jsonl_file: str, + cross_file_content_evaluation_jsonl_file: str, start_tabby_server_on_modal: bool): # Start modal tabby server process = None @@ -164,12 +217,17 @@ def eval_code_completion(endpoint: str, # Generate predictions logging.info("Generating predictions...") - generate_predictions(endpoint, token, jsonl_file, output_prediction_jsonl_file) + generate_predictions(endpoint, token, jsonl_file, prediction_jsonl_file, default_data_function) + generate_predictions(endpoint, token, jsonl_file, + cross_file_content_prediction_jsonl_file, + cross_file_data_function, + get_model_prompt_template(model)) logging.info("Predictions generated!") # Run the evaluation logging.info("Running evaluation...") - evaluation(output_prediction_jsonl_file, output_evaluation_jsonl_file) + evaluation(prediction_jsonl_file, evaluation_jsonl_file) + evaluation(cross_file_content_prediction_jsonl_file, cross_file_content_evaluation_jsonl_file) logging.info("Evaluation completed") # Stop the server @@ -185,17 +243,23 @@ def eval_code_completion(endpoint: str, parser.add_argument("--token", type=str, required=True, default="", help="tabby server token.") parser.add_argument("--model", type=str, required=True, help="evaluation model.") parser.add_argument("--jsonl_file", type=str, default="data.jsonl", help="evaluation jsonl file.") - parser.add_argument("--output_prediction_jsonl_file", type=str, help="output prediction jsonl file.") - parser.add_argument("--output_evaluation_jsonl_file", type=str, help="output evaluation jsonl file.") + parser.add_argument("--output_jsonl_file_prefix", type=str, help=""" + output jsonl file prefix, it will generate four files: + prediction, evaluation, cross_file_content_prediction, cross_file_content_evaluation. + """) parser.add_argument("--start_tabby_server_on_modal", type=str, default="1", help="start tabby server on modal manager, accepts 1 or another.") args = parser.parse_args() + output_jsonl_file_prefix = args.output_jsonl_file_prefix bool_start_tabby_server_on_modal = True if args.start_tabby_server_on_modal == "1" else False + eval_code_completion(args.endpoint, args.token, args.model, args.jsonl_file, - args.output_prediction_jsonl_file, - args.output_evaluation_jsonl_file, + f"{output_jsonl_file_prefix}-prediction.jsonl", + f"{output_jsonl_file_prefix}-evaluation.jsonl", + f"{output_jsonl_file_prefix}-cross-file-content-prediction.jsonl", + f"{output_jsonl_file_prefix}-cross-file-content-evaluation.jsonl", bool_start_tabby_server_on_modal) diff --git a/python/tabby-eval/v2-modal/compute_metrics.py b/python/tabby-eval/v2-modal/compute_metrics.py index f9f5aa2f5cb4..9d54011226ba 100755 --- a/python/tabby-eval/v2-modal/compute_metrics.py +++ b/python/tabby-eval/v2-modal/compute_metrics.py @@ -13,7 +13,7 @@ ) -def evaluation(prediction_jsonl_file, output_evaluation_jsonl_file): +def evaluation(prediction_jsonl_file, evaluation_jsonl_file): df = pd.read_json(prediction_jsonl_file, lines=True) results = [] @@ -42,10 +42,10 @@ def evaluation(prediction_jsonl_file, output_evaluation_jsonl_file): df = pd.concat([df, pd.DataFrame(results)], axis=1) - df.to_json(output_evaluation_jsonl_file, orient='records', lines=True, force_ascii=False) - logging.info(f"Evaluation result written to {output_evaluation_jsonl_file}") + df.to_json(evaluation_jsonl_file, orient='records', lines=True, force_ascii=False) + logging.info(f"Evaluation result written to {evaluation_jsonl_file}") - avg_compute(output_evaluation_jsonl_file) + avg_compute(evaluation_jsonl_file) if __name__ == "__main__": diff --git a/python/tabby-eval/v2-modal/data.jsonl b/python/tabby-eval/v2-modal/data.jsonl deleted file mode 100644 index cb2f741ce519..000000000000 --- a/python/tabby-eval/v2-modal/data.jsonl +++ /dev/null @@ -1,2 +0,0 @@ -{"language": "python", "segments": {"prefix": "def fib(n):\n ", "suffix": "\n return fib(n - 1) + fib(n - 2)"}, "groundtruth": "\n if n <= 1:\n return n\n else:"} -{"language": "csharp", "segments": {"prefix": "using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n // Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n"}, "groundtruth": "LassoProfile> GetLassoProfiles()\n {"} \ No newline at end of file diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl new file mode 100644 index 000000000000..dd9a51070031 --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl @@ -0,0 +1 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl new file mode 100644 index 000000000000..0b67833a20cf --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl @@ -0,0 +1 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl new file mode 100644 index 000000000000..dd9a51070031 --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl @@ -0,0 +1 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl new file mode 100644 index 000000000000..0b67833a20cf --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl @@ -0,0 +1 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/one-record.jsonl b/python/tabby-eval/v2-modal/data/one-record.jsonl new file mode 100644 index 000000000000..dadd94cd84da --- /dev/null +++ b/python/tabby-eval/v2-modal/data/one-record.jsonl @@ -0,0 +1 @@ +{"language": "csharp", "segments": {"prefix": "using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n // Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ProcessManager/Providers/IConfigProvider.cs\n// ManagerConfig GetManagerConfig();\n// /// \n// /// Geth the list of lasso rules.\n// /// \n// /// \n// List GetRules();\n// Dictionary GetLassoProfiles();\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Models/Configs/ManagerConfig.cs\n// public ProcessRule[] ProcessRules { get; set; }\n// /// \n// /// List of folders rules.\n// /// \n// public FolderRule[] FolderRules { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// public void Dispose()\n// {\n// if (processStartEvent != null) \n// {\n// processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n// processStartEvent.Dispose();\n// processStartEvent = null;\n// }\n// }\n// public bool Setup()\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// {\n// int failCount = 0;\n// Dictionary successCount = new Dictionary();\n// foreach (var process in Process.GetProcesses())\n// {\n// LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n// bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n// if (success)\n// {\n// if (!successCount.ContainsKey(profileName))\n\n", "list": [{"retrieved_chunk": " ManagerConfig GetManagerConfig();\n /// \n /// Geth the list of lasso rules.\n /// \n /// \n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}", "filename": "ProcessManager/Providers/IConfigProvider.cs", "score": 22.799994275269317}, {"retrieved_chunk": " public ProcessRule[] ProcessRules { get; set; }\n /// \n /// List of folders rules.\n /// \n public FolderRule[] FolderRules { get; set; }\n }\n}", "filename": "ProcessManager/Models/Configs/ManagerConfig.cs", "score": 20.728193497923062}, {"retrieved_chunk": " public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 14.506247294243275}, {"retrieved_chunk": " {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 11.789149115850975}]}}, "groundtruth": "LassoProfile> GetLassoProfiles()\n {", "metadata": {"task_id": "project_cc_csharp/27", "repository": "kenshinakh1-LassoProcessManager-bcc481f", "file": "ProcessManager/Providers/ConfigProvider.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 45, "right_context_start_lineno": 47}} diff --git a/python/tabby-eval/v2-modal/data/ten-records.jsonl b/python/tabby-eval/v2-modal/data/ten-records.jsonl new file mode 100644 index 000000000000..dc3a3ba2f878 --- /dev/null +++ b/python/tabby-eval/v2-modal/data/ten-records.jsonl @@ -0,0 +1,10 @@ +{"language": "csharp", "segments": {"prefix": "using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n // Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ProcessManager/Providers/IConfigProvider.cs\n// ManagerConfig GetManagerConfig();\n// /// \n// /// Geth the list of lasso rules.\n// /// \n// /// \n// List GetRules();\n// Dictionary GetLassoProfiles();\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Models/Configs/ManagerConfig.cs\n// public ProcessRule[] ProcessRules { get; set; }\n// /// \n// /// List of folders rules.\n// /// \n// public FolderRule[] FolderRules { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// public void Dispose()\n// {\n// if (processStartEvent != null) \n// {\n// processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n// processStartEvent.Dispose();\n// processStartEvent = null;\n// }\n// }\n// public bool Setup()\n\n// the below code fragment can be found in:\n// ProcessManager/Managers/LassoManager.cs\n// {\n// int failCount = 0;\n// Dictionary successCount = new Dictionary();\n// foreach (var process in Process.GetProcesses())\n// {\n// LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n// bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n// if (success)\n// {\n// if (!successCount.ContainsKey(profileName))\n\n", "list": [{"retrieved_chunk": " ManagerConfig GetManagerConfig();\n /// \n /// Geth the list of lasso rules.\n /// \n /// \n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}", "filename": "ProcessManager/Providers/IConfigProvider.cs", "score": 22.799994275269317}, {"retrieved_chunk": " public ProcessRule[] ProcessRules { get; set; }\n /// \n /// List of folders rules.\n /// \n public FolderRule[] FolderRules { get; set; }\n }\n}", "filename": "ProcessManager/Models/Configs/ManagerConfig.cs", "score": 20.728193497923062}, {"retrieved_chunk": " public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 14.506247294243275}, {"retrieved_chunk": " {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))", "filename": "ProcessManager/Managers/LassoManager.cs", "score": 11.789149115850975}]}}, "groundtruth": "LassoProfile> GetLassoProfiles()\n {", "metadata": {"task_id": "project_cc_csharp/27", "repository": "kenshinakh1-LassoProcessManager-bcc481f", "file": "ProcessManager/Providers/ConfigProvider.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 45, "right_context_start_lineno": 47}} +{"language": "csharp", "segments": {"prefix": "//#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(", "suffix": "\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\t\tBuildProjectsList();\n// \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n// \t\t\t\t\t{\n// \t\t\t\t\t\tLaunchInstaller(entry);\n// \t\t\t\t\t\treturn;\n// \t\t\t\t\t}\n// \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n// \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n// \t\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n// \t\t\t\t\treturn;\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/FileHelper.cs\n// \t{\n// \t\tGD.Print(\"*********** Delete file!\");\n// \t}\n// \tprivate static void CreateDirectoryForUser(string directory)\n// \t{\n// \t\tvar path = Path.Combine(BasePath, directory);\n// \t\tif (!DirAccess.DirExistsAbsolute(path))\n// \t\t{\n// \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n// \t\t}\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n// \t\t\t};\n// \t\t\tprojectEntries.Add(project);\n// \t\t\tLaunchProject(directoryPath, false);\n// \t\t}\n// \t\tvoid _onFilesDropped(string[] files)\n// \t\t{\n// \t\t\tfor (int i = 0; i < files.Length; i++)\n// \t\t\t{\n// \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/FileHelper.cs\n// \t}\n// \tpublic static void WriteUserText(string path, string json)\n// \t{\n// \t\tWriteAllText(PathCombine(BasePath, path), json);\n// \t}\n// \tpublic static bool UserFileExists(string path)\n// \t{\n// \t\treturn FileExists(PathCombine(BasePath, path));\n// \t}\n// \tpublic static void Delete(string path)\n\n// the below code fragment can be found in:\n// godot-project/Scripts/DataManagement/LauncherManager.cs\n// \t\t\t\tInstallVersion(versionKey);\n// \t\t\t}\n// \t\t\tSaveProjectsList();\n// \t\t\tBuildProjectsList();\n// \t\t}\n// \t\tvoid SaveConfig()\n// \t\t{\n// \t\t\tvar json = DataBuilder.GetConfigJson(config);\n// \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n// \t\t}\n\n", "list": [{"retrieved_chunk": "\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t//OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 29.431886867394642}, {"retrieved_chunk": "\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}", "filename": "godot-project/Scripts/DataManagement/FileHelper.cs", "score": 16.13486385582849}, {"retrieved_chunk": "\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 14.892200276853623}, {"retrieved_chunk": "\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)", "filename": "godot-project/Scripts/DataManagement/FileHelper.cs", "score": 13.921454071982678}, {"retrieved_chunk": "\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}", "filename": "godot-project/Scripts/DataManagement/LauncherManager.cs", "score": 13.535088476589515}]}}, "groundtruth": "InstallerEntryData installerEntryData)\n\t\t{", "metadata": {"task_id": "project_cc_csharp/55", "repository": "NathanWarden-ready-to-launch-58eba6d", "file": "godot-project/Scripts/DataManagement/DataPaths.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 94, "right_context_start_lineno": 96}} +{"language": "csharp", "segments": {"prefix": "using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [", "suffix": " get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs\n// private const string BADGE_URL = \"https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true\";\n// private const string SUMMARY_URL = \"https://forum.dotnetdev.kr/u/{0}/summary.json\";\n// private readonly IHttpClientFactory _httpClientFactory;\n// public ForumDataProvider(IHttpClientFactory httpClientFactory)\n// {\n// _httpClientFactory = httpClientFactory;\n// }\n// private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n// {\n// using HttpClient client = _httpClientFactory.CreateClient();\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs\n// public string Username { get; set; }\n// [JsonProperty(\"name\")]\n// public string Name { get; set; }\n// [JsonProperty(\"avatar_template\")]\n// public string AvatarTemplate { get; set; }\n// [JsonProperty(\"flair_name\")]\n// public object FlairName { get; set; }\n// [JsonProperty(\"trust_level\")]\n// public int TrustLevel { get; set; }\n// [JsonProperty(\"admin\")]\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs\n// \ufeffusing DotNetDevBadgeWeb.Model;\n// namespace DotNetDevBadgeWeb.Interfaces\n// {\n// public interface IProvider\n// {\n// Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n// Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n// Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n// }\n// }\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs\n// private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n// private readonly IProvider _forumProvider;\n// private readonly IMeasureTextV1 _measureTextV1;\n// public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n// {\n// _forumProvider = forumProvider;\n// _measureTextV1 = measureTextV1;\n// }\n// public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n// {\n\n// the below code fragment can be found in:\n// src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs\n// {\n// app.UseMiddleware();\n// app.MapBadgeEndpointsV1();\n// return app;\n// }\n// internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n// {\n// app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n// {\n// string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n", "list": [{"retrieved_chunk": " private const string BADGE_URL = \"https://forum.dotnetdev.kr/user-badges/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https://forum.dotnetdev.kr/u/{0}/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Provider/ForumDataProvider.cs", "score": 20.998481641894454}, {"retrieved_chunk": " public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Model/User.cs", "score": 20.73346729938653}, {"retrieved_chunk": "\ufeffusing DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Interfaces/IProvider.cs", "score": 12.088199207115517}, {"retrieved_chunk": " private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Core/Badge/BadgeCreatorV1.cs", "score": 10.738553623860039}, {"retrieved_chunk": " {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"/api/v1/badge/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);", "filename": "src/dotnetdev-badge/dotnetdev-badge.web/Endpoints/Badge/BadgeEndpoints.cs", "score": 7.998097817927588}]}}, "groundtruth": "JsonProperty(\"likes_given\")]\n public int LikesGiven {", "metadata": {"task_id": "project_cc_csharp/48", "repository": "chanos-dev-dotnetdev-badge-5740a40", "file": "src/dotnetdev-badge/dotnetdev-badge.web/Model/UserSummary.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 8}} +{"language": "csharp", "segments": {"prefix": "using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<", "suffix": " get; set; } = new List();\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs\n// {\n// public List Workbooks { get; set; } = new List();\n// public int SearchLimitRow { get; set; }\n// public int SearchLimitColumn { get; set; }\n// public List WorksheetIndexes { get; set; } = new List();\n// public List Worksheets { get; set; } = new List();\n// public bool ReadAllWorksheets { get; set; }\n// public List HeadersToSearch { get; set; } = new List();\n// public DataTable GetDataTable()\n// {\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs\n// public class DataTableExtractor :\n// IDataTableExtractorConfiguration,\n// IDataTableExtractorWorkbookConfiguration,\n// IDataTableExtractorSearchConfiguration,\n// IDataTableExtractorWorksheetConfiguration\n// {\n// private bool _readAllWorksheets;\n// private int _searchLimitRow;\n// private int _searchLimitColumn;\n// private readonly List _workbooks = new List();\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorksheetData.cs\n// \ufeffusing System.Collections.Generic;\n// namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n// {\n// public class JXLWorksheetData\n// {\n// public string WorksheetName { get; set; } = string.Empty;\n// public List Rows { get; set; } = new List();\n// }\n// }\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLExtractedRow.cs\n// \ufeffusing System.Collections.Generic;\n// namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n// {\n// public class JXLExtractedRow\n// {\n// public Dictionary Columns { get; set; } = new Dictionary();\n// }\n// }\n\n// the below code fragment can be found in:\n// JdeJabali.JXLDataTableExtractor/Configuration/IDataExtraction.cs\n// /// \n// /// \n// List GetWorkbooksData();\n// /// \n// /// Only retrieves the extracted rows from all the workbooks and worksheets.\n// /// \n// /// \n// /// \n// List GetExtractedRows();\n// /// \n\n", "list": [{"retrieved_chunk": " {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {", "filename": "JdeJabali.JXLDataTableExtractor/DataExtraction/DataReader.cs", "score": 21.880390238660006}, {"retrieved_chunk": " public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();", "filename": "JdeJabali.JXLDataTableExtractor/DataTableExtractor.cs", "score": 20.597128248615988}, {"retrieved_chunk": "\ufeffusing System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}", "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLWorksheetData.cs", "score": 20.44056373724002}, {"retrieved_chunk": "\ufeffusing System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}", "filename": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLExtractedRow.cs", "score": 20.174278440276893}, {"retrieved_chunk": " /// \n /// \n List GetWorkbooksData();\n /// \n /// Only retrieves the extracted rows from all the workbooks and worksheets.\n /// \n /// \n /// \n List GetExtractedRows();\n /// ", "filename": "JdeJabali.JXLDataTableExtractor/Configuration/IDataExtraction.cs", "score": 19.028401583774812}]}}, "groundtruth": "JXLWorkbookData> WorkbooksData {", "metadata": {"task_id": "project_cc_csharp/50", "repository": "JdeJabali-JXLDataTableExtractor-90a12f4", "file": "JdeJabali.JXLDataTableExtractor/JXLExtractedData/JXLDataExtracted.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 7}} +{"language": "csharp", "segments": {"prefix": "using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ", "suffix": "\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/ExampleWebApplication/Controllers/WebSocket2Controller.cs\n// public WebSocket2Controller(WebSocketHub webSocketHub)\n// {\n// _webSocketHub = webSocketHub;\n// }\n// [HttpGet(\"GetSocketListWithSelector\")]\n// public IActionResult GetSocketListWithSelector(int id)\n// {\n// var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n// return Ok(socketListOfUser);\n// }\n\n// the below code fragment can be found in:\n// src/ExampleWebApplication/Controllers/WebSocket1Controller.cs\n// {\n// _webSocketHub = webSocketHub;\n// }\n// [HttpGet(\"GetSocketList\")]\n// public IActionResult GetSocketList(int id)\n// {\n// var socketListOfUser = _webSocketHub.GetSocketList(id);\n// return Ok(socketListOfUser);\n// }\n// [HttpGet(\"GetSocketListWithSelector\")]\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketRequestHandlerProvider.cs\n// /// Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n// /// \n// /// The type of WebSocket request handler to add.\n// /// The message type associated with the WebSocket request handler.\n// /// true if the WebSocket request handler was added to the handler type map; otherwise, false.\n// /// Thrown when is not assignable from IWebSocketRequestHandler.\n// /// \n// /// This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n// /// \n// public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketHub.cs\n// public WebSocketHub(IOptions options)\n// {\n// if (options == null) throw new ArgumentNullException(nameof(options));\n// Options = options.Value;\n// _webSocketDictionary = new();\n// }\n// /// \n// /// Encodes the specified Message object into a UTF-8 encoded byte array.\n// /// \n// /// The Message object to encode.\n\n// the below code fragment can be found in:\n// src/WebSocketHub/Core/src/WebSocketHub.cs\n// private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n// public WebSocketHubOptions Options { get; private set; }\n// /// \n// /// Initializes a new instance of the WebSocketHub class with the specified options.\n// /// \n// /// The options to configure the WebSocketHub.\n// /// Thrown when is null.\n// /// \n// /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n// /// \n\n", "list": [{"retrieved_chunk": " public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }", "filename": "src/ExampleWebApplication/Controllers/WebSocket2Controller.cs", "score": 45.19935267420081}, {"retrieved_chunk": " {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]", "filename": "src/ExampleWebApplication/Controllers/WebSocket1Controller.cs", "score": 45.02333198140999}, {"retrieved_chunk": " /// Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n /// \n /// The type of WebSocket request handler to add.\n /// The message type associated with the WebSocket request handler.\n /// true if the WebSocket request handler was added to the handler type map; otherwise, false.\n /// Thrown when is not assignable from IWebSocketRequestHandler.\n /// \n /// This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n /// \n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)", "filename": "src/WebSocketHub/Core/src/WebSocketRequestHandlerProvider.cs", "score": 38.98487610590298}, {"retrieved_chunk": " public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n /// \n /// Encodes the specified Message object into a UTF-8 encoded byte array.\n /// \n /// The Message object to encode.", "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "score": 37.98681211524358}, {"retrieved_chunk": " private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n /// \n /// Initializes a new instance of the WebSocketHub class with the specified options.\n /// \n /// The options to configure the WebSocketHub.\n /// Thrown when is null.\n /// \n /// This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n /// ", "filename": "src/WebSocketHub/Core/src/WebSocketHub.cs", "score": 31.71651588733243}]}}, "groundtruth": "WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {", "metadata": {"task_id": "project_cc_csharp/68", "repository": "TRA-Tech-dotnet-websocket-9049854", "file": "src/WebSocketHub/Core/src/WebSocketHubMiddleware.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 17, "right_context_start_lineno": 19}} +{"language": "csharp", "segments": {"prefix": "using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; // in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n /// \n /// Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n /// \n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n /// \n /// The Xbox memory stream.\n /// \n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<", "suffix": "\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n // init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n // enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n // custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length / 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n // argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n // argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], // initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n // optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n // peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n // call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n // cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n /// \n /// Calls an Xbox function.\n /// \n /// The function address.\n /// The function arguments.\n /// Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.\n public uint Call(long address, params object[] args)\n {\n // TODO: call context (~4039+ which requires qwordparam)\n\n // injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n /// \n /// Original Xbox Debug Monitor runtime patches.\n /// Prevents crashdumps from being written to the HDD and enables remote code execution.\n /// \n /// \n private void PatchXbdm(Xbox target)\n {\n // the spin routine to be patched in after the signature patterns\n // spin:\n // jmp spin\n // int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n // prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n // this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n // labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); // pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); // size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n //asm.push(__dword_ptr[ebx + 8]);\n //asm.call((uint)target.Signatures[\"DmFreePool\"]);\n //asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); // buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); // address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n // 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n // labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n // prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); // carve out arbitrary space for local temp variables\n asm.pushad();\n\n // disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n // arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n // local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n // check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); // 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n // call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n // thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n // determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); // 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n // get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); // 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n // push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n // get argument name\n asm.push(edi); // argument index\n asm.push(argFormatStringAddress); // format string address\n asm.lea(eax, __dword_ptr[argName]); // argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n // check if it's included in the command\n asm.lea(eax, __[temp]); // argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); // argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); // command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n // push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n // move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n // perform the call\n asm.call(__dword_ptr[callAddress]);\n\n // print response message\n asm.push(eax); // integer return value\n asm.push(returnFormatAddress); // format string address\n asm.push(__dword_ptr[responseAddress]); // response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n // TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n // get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); // address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n //asm.mov(eax, 0x2000); // TODO: increase pool size?\n //asm.push(eax);\n //asm.call((uint)target.Signatures[\"DmAllocatePool\"]); // TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); // buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); // buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n // if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n // generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n // successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n // generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n // original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n // inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n // read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n // disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n // formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n // convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n // skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n // optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n // output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n // optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n // output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n // NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n // universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n // mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n // mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n // mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n // universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n // mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n // mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n // universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n // jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n // push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n // mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n // universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n // mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n // jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n // retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n // universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n // test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n // push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n // early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n // mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n // mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n // later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n // mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n // mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n // xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha/dvt3/dvt4/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n // mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n // mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n // early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n // push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n // mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n // push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n // later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n // push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n // retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n // universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n // cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n // read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n // scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n // cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // TODO: dispose managed state (managed objects)\n }\n\n // TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n // TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/ConnectionInfo.cs\n// var connections = new List();\n// byte[] datagramBuffer = new byte[1024];\n// // iterate through each network interface\n// Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n// {\n// // only worry about active IPv4 interfaces\n// if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n// return;\n// // iterate through each ip address assigned to the interface\n// Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Connection.cs\n// /// \n// /// Initializes the session.\n// /// \n// public Connection()\n// {\n// // initialize defaults\n// Reader = new BinaryReader(this);\n// Writer = new BinaryWriter(this);\n// ResetTcp();\n// }\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Connection.cs\n// /// \n// /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n// /// \n// public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n// /// \n// /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n// /// \n// public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n// #endregion\n// #region Construction\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Kernel.cs\n// throw new ArgumentNullException(nameof(xbox));\n// Module = xbox.Modules.Find(m => m.Name == Name) ??\n// throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n// // TODO: remove 3rd-party dependency with proper PE parsing logic\n// // grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n// var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n// int size = (int)(initSection.Base - Address);\n// var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n// // resolve exports\n// Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n// the below code fragment can be found in:\n// src/OGXbdmDumper/Kernel.cs\n// /// The kernel exports.\n// /// \n// public KernelExports Exports { get; private set; }\n// /// \n// /// Initializes communication with the Xbox kernel.\n// /// \n// /// \n// public Kernel(Xbox xbox)\n// {\n// _xbox = xbox ??\n\n", "list": [{"retrieved_chunk": " var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n // iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n // only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n // iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>", "filename": "src/OGXbdmDumper/ConnectionInfo.cs", "score": 66.55166457984245}, {"retrieved_chunk": " /// \n /// Initializes the session.\n /// \n public Connection()\n {\n // initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }", "filename": "src/OGXbdmDumper/Connection.cs", "score": 65.61480573217976}, {"retrieved_chunk": " /// \n /// The time in milliseconds to wait while sending data before throwing a TimeoutException.\n /// \n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n /// \n /// The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n /// \n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction", "filename": "src/OGXbdmDumper/Connection.cs", "score": 63.14871472847682}, {"retrieved_chunk": " throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n // TODO: remove 3rd-party dependency with proper PE parsing logic\n // grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n // resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);", "filename": "src/OGXbdmDumper/Kernel.cs", "score": 62.61533660943069}, {"retrieved_chunk": " /// The kernel exports.\n /// \n public KernelExports Exports { get; private set; }\n /// \n /// Initializes communication with the Xbox kernel.\n /// \n /// \n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??", "filename": "src/OGXbdmDumper/Kernel.cs", "score": 60.88570669473385}]}}, "groundtruth": "Thread> Threads => GetThreads();", "metadata": {"task_id": "project_cc_csharp/20", "repository": "Ernegien-OGXbdmDumper-07a1e82", "file": "src/OGXbdmDumper/Xbox.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 75, "right_context_start_lineno": 76}} +{"language": "csharp", "segments": {"prefix": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [", "suffix": " get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/JWDal.cs\n// {\n// connectionString = $\"Data Source={dbPath}\";\n// }\n// public IEnumerable TableList()\n// {\n// using (IDbConnection cnn = new SQLiteConnection(connectionString))\n// {\n// return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/InputField.cs\n// \ufeffusing JWLSLMerge.Data.Attributes;\n// namespace JWLSLMerge.Data.Models\n// {\n// public class InputField\n// {\n// public int LocationId { get; set; }\n// public string TextTag { get; set; } = null!;\n// public string Value { get; set; } = null!;\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Tag.cs\n// public int NewTagId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge/MergeService.cs\n// private readonly string targetPath = null!;\n// private readonly string targetDbFile = null!;\n// private string lastModified = null!;\n// public MergeService()\n// {\n// targetPath = Environment.GetTargetDirectory();\n// targetDbFile = Environment.GetDbFile();\n// }\n// public void Run(string[] jwlibraryFiles)\n// {\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/UserMark.cs\n// public string UserMarkGuid { get; set; } = null!;\n// public int Version { get; set; }\n// [Ignore]\n// public int NewUserMarkId { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": " {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }", "filename": "JWLSLMerge.Data/JWDal.cs", "score": 13.78401506779753}, {"retrieved_chunk": "\ufeffusing JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}", "filename": "JWLSLMerge.Data/Models/InputField.cs", "score": 13.000811547599904}, {"retrieved_chunk": " public int NewTagId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Tag.cs", "score": 12.828308464376727}, {"retrieved_chunk": " private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {", "filename": "JWLSLMerge/MergeService.cs", "score": 12.77934094725121}, {"retrieved_chunk": " public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/UserMark.cs", "score": 12.358601363000677}]}}, "groundtruth": "Ignore]\n public int NoteId {", "metadata": {"task_id": "project_cc_csharp/51", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/Note.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 6, "right_context_start_lineno": 8}} +{"language": "csharp", "segments": {"prefix": "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n /// \n /// \u5e94\u7528\u5de5\u4f5c\u76ee\u5f55\n /// \n /// \u542f\u52a8\u53c2\u6570\n /// \n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"\u7cfb\u7edf\u5df2\u5b58\u5728\u540c\u540d\u4f46\u4e0d\u540c\u8def\u5f84\u7684\u670d\u52a1\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ", "suffix": "\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n /// \n /// \u505c\u6b62\u5e76\u5220\u9664\u670d\u52a1\n /// \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n // \u8fd9\u91cc\u4e0d\u9700\u8981\u6062\u590dSERVICE_CONFIG_FAILURE_ACTIONS\uff0c\u56e0\u4e3a\u4e0b\u9762\u6211\u4eec\u8981\u5220\u9664\u670d\u52a1\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"\u7b49\u5f85\u670d\u52a1\u505c\u6b62\u8d85\u8fc7\u4e86{maxWaitTime.TotalSeconds}\u79d2\");\n }\n\n /// \n /// \u5c1d\u8bd5\u83b7\u53d6\u670d\u52a1\u7684\u8fdb\u7a0bid\n /// \n /// \n /// \n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// }\n// var linuxOptions = CreateLinuxOptions(filePath, options);\n// using (var fileStream = File.OpenWrite(unitFilePath))\n// {\n// using var wirter = new StreamWriter(fileStream);\n// linuxOptions.WriteTo(wirter);\n// }\n// // SELinux\n// Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n// SystemControl(\"daemon-reload\", showError: true);\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// break;\n// }\n// }\n// if (filePath.IsEmpty || wantedBy.IsEmpty)\n// {\n// return ReadOnlySpan.Empty;\n// }\n// var wants = $\"{wantedBy.ToString()}.wants\";\n// var unitFileName = Path.GetFileName(unitFilePath);\n// var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// if (geteuid() != 0)\n// {\n// throw new UnauthorizedAccessException(\"\u65e0\u6cd5\u64cd\u4f5c\u670d\u52a1\uff1a\u6ca1\u6709root\u6743\u9650\");\n// }\n// }\n// }\n// }\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// line = line[execStartPrefix.Length..];\n// var index = line.IndexOf(' ');\n// filePath = index < 0 ? line : line[..index];\n// }\n// else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n// {\n// wantedBy = line[wantedByPrefix.Length..].Trim();\n// }\n// if (filePath.Length > 0 && wantedBy.Length > 0)\n// {\n\n// the below code fragment can be found in:\n// ServiceSelf/LinuxService.cs\n// {\n// execStart = $\"{filePath} {string.Join(' ', args)}\";\n// }\n// }\n// var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n// ? Path.GetDirectoryName(filePath)\n// : Path.GetFullPath(options.WorkingDirectory);\n// var linuxOptions = options.Linux.Clone();\n// linuxOptions.Unit[\"Description\"] = options.Description;\n// linuxOptions.Service[\"ExecStart\"] = execStart;\n\n", "list": [{"retrieved_chunk": " }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n // SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);", "filename": "ServiceSelf/LinuxService.cs", "score": 53.22018771652771}, {"retrieved_chunk": " break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);", "filename": "ServiceSelf/LinuxService.cs", "score": 21.470485420837036}, {"retrieved_chunk": " if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"\u65e0\u6cd5\u64cd\u4f5c\u670d\u52a1\uff1a\u6ca1\u6709root\u6743\u9650\");\n }\n }\n }\n}", "filename": "ServiceSelf/LinuxService.cs", "score": 12.934142972279112}, {"retrieved_chunk": " line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {", "filename": "ServiceSelf/LinuxService.cs", "score": 12.544725417438247}, {"retrieved_chunk": " {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;", "filename": "ServiceSelf/LinuxService.cs", "score": 12.519455560002188}]}}, "groundtruth": "SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {", "metadata": {"task_id": "project_cc_csharp/14", "repository": "xljiulang-ServiceSelf-7f8604b", "file": "ServiceSelf/WindowsService.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 66, "right_context_start_lineno": 68}} +{"language": "csharp", "segments": {"prefix": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [", "suffix": " get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemMarker.cs\n// public long DurationTicks { get; set; }\n// public long EndTransitionDurationTicks { get; set; }\n// [Ignore]\n// public int NewPlaylistItemMarkerId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Note.cs\n// public string? Title { get; set; }\n// public string? Content { get; set; }\n// public string LastModified { get; set; } = null!;\n// public string Created { get; set; } = null!;\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// [Ignore]\n// public int NewNoteId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/UserMark.cs\n// public string UserMarkGuid { get; set; } = null!;\n// public int Version { get; set; }\n// [Ignore]\n// public int NewUserMarkId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Location.cs\n// public int? Track { get; set; }\n// public int IssueTagNumber { get; set; }\n// public string? KeySymbol { get; set; }\n// public int? MepsLanguage { get; set; }\n// public int Type { get; set; }\n// public string? Title { get; set; }\n// [Ignore]\n// public int NewLocationId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Bookmark.cs\n// public string Title { get; set; } = null!;\n// public string? Snippet { get; set; }\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": " public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs", "score": 35.26889876052275}, {"retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Note.cs", "score": 33.518184487704545}, {"retrieved_chunk": " public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/UserMark.cs", "score": 32.64848873570582}, {"retrieved_chunk": " public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Location.cs", "score": 31.624913532715233}, {"retrieved_chunk": " public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Bookmark.cs", "score": 31.183025189281004}]}}, "groundtruth": "Ignore]\n public int NewPlaylistItemId {", "metadata": {"task_id": "project_cc_csharp/37", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/PlayListItem.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 15, "right_context_start_lineno": 17}} +{"language": "csharp", "segments": {"prefix": "using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [", "suffix": " get; set; }\n }\n}\n", "crossfile_context": {"text": "// Here are some relevant code fragments from other files of the repo:\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemIndependentMediaMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemIndependentMediaMap\n// {\n// public int PlaylistItemId { get; set; }\n// public int IndependentMediaId { get; set; }\n// public long DurationTicks { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemLocationMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemLocationMap\n// {\n// public int PlaylistItemId { get; set; }\n// public int LocationId { get; set; }\n// public int MajorMultimediaType { get; set; }\n// public long? BaseDurationTicks { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlayListItem.cs\n// public int Accuracy { get; set; }\n// public int EndAction { get; set; }\n// public string ThumbnailFilePath { get; set; } = null!;\n// [Ignore]\n// public int NewPlaylistItemId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/Note.cs\n// public string? Title { get; set; }\n// public string? Content { get; set; }\n// public string LastModified { get; set; } = null!;\n// public string Created { get; set; } = null!;\n// public int BlockType { get; set; }\n// public int? BlockIdentifier { get; set; }\n// [Ignore]\n// public int NewNoteId { get; set; }\n// }\n// }\n\n// the below code fragment can be found in:\n// JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs\n// \ufeffnamespace JWLSLMerge.Data.Models\n// {\n// public class PlaylistItemMarkerParagraphMap\n// {\n// public int PlaylistItemMarkerId { get; set; }\n// public int MepsDocumentId { get; set; }\n// public int ParagraphIndex { get; set; }\n// public int MarkerIndexWithinParagraph { get; set; }\n// }\n// }\n\n", "list": [{"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemIndependentMediaMap.cs", "score": 40.139620221589794}, {"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemLocationMap.cs", "score": 35.276235533017854}, {"retrieved_chunk": " public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlayListItem.cs", "score": 29.760486252006046}, {"retrieved_chunk": " public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/Note.cs", "score": 25.37908122532722}, {"retrieved_chunk": "\ufeffnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}", "filename": "JWLSLMerge.Data/Models/PlaylistItemMarkerParagraphMap.cs", "score": 25.258196191223316}]}}, "groundtruth": "Ignore]\n public int NewPlaylistItemMarkerId {", "metadata": {"task_id": "project_cc_csharp/29", "repository": "pliniobrunelli-JWLSLMerge-7fe66dc", "file": "JWLSLMerge.Data/Models/PlaylistItemMarker.cs", "context_start_lineno": 0, "groundtruth_start_lineno": 14, "right_context_start_lineno": 16}} From 7cbc62fee5d309d957d81da1ae68d0d58bbb16cf Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 15:52:15 +0800 Subject: [PATCH 16/19] Eval-V2-Modal: resolve a combined data error in the cross_file_data_function --- python/tabby-eval/v2-modal/compute_code_completion.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index 71ac9929f2b5..4ee937a7b2e3 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -184,14 +184,17 @@ def cross_file_data_function(row, prompt_template): crossfile_context_list = row['segments.crossfile_context.list'] sorted_list = sorted(crossfile_context_list, key=lambda x: x['score']) + # TODO: The added prefix comments should be consistent with the language, for the time being use "//" for all combined_context = "\n".join( - f"// {item['filename']}\n// {item['retrieved_chunk']}" for item in sorted_list + f"// Path: {item['filename']}\n" + "\n".join(f"// {line}" for line in item['retrieved_chunk'].split("\n")) + for item in sorted_list ) + "\n" + logging.debug(f"Combined context in cross_file_data_function: {combined_context}") return { "debug_options": { - "raw_prompt": combined_context + prompt_template.format( - prefix=row['segments.prefix'], + "raw_prompt": prompt_template.format( + prefix=combined_context + row['segments.prefix'], suffix=row['segments.suffix']) } } From 4733c7f38d9ebaf87fa18447f16194a55dc9d0c8 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 17:07:03 +0800 Subject: [PATCH 17/19] Eval-V2-Modal: add pands-escape-enforce-problem.py --- .../test/pands-escape-enforce-problem.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 python/tabby-eval/v2-modal/test/pands-escape-enforce-problem.py diff --git a/python/tabby-eval/v2-modal/test/pands-escape-enforce-problem.py b/python/tabby-eval/v2-modal/test/pands-escape-enforce-problem.py new file mode 100644 index 000000000000..f66a6298247e --- /dev/null +++ b/python/tabby-eval/v2-modal/test/pands-escape-enforce-problem.py @@ -0,0 +1,17 @@ +import json + +import pandas as pd + +if __name__ == "__main__": + # https://github.com/pandas-dev/pandas/releases + # latest: 2.2.2, released: 2024-04-11 + # today: 20240717 + print(pd.__version__) + + input_json = '{"text": "//"}' + + df = pd.read_json(json.dumps([json.loads(input_json)]), orient='records') + output_json = df.to_json(orient="records", lines=True) + + # {"text":"\/\/"} + print(output_json) From c4a78099f75c170ebfd9af931c82e9284b994b58 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 17:15:56 +0800 Subject: [PATCH 18/19] Eval-V2-Modal: add CodeLlama-13B eval results. --- python/tabby-eval/v2-modal/README.md | 2 +- .../v2-modal/compute_code_completion.py | 100 +++++++++++------- ...13B-10-cross-file-content-evaluation.jsonl | 10 ++ ...13B-10-cross-file-content-prediction.jsonl | 10 ++ ...20240717-CodeLlama-13B-10-evaluation.jsonl | 10 ++ ...20240717-CodeLlama-13B-10-prediction.jsonl | 10 ++ ...der-1B-cross-file-content-evaluation.jsonl | 1 - ...der-1B-cross-file-content-prediction.jsonl | 1 - .../20240717-StarCoder-1B-evaluation.jsonl | 1 - .../20240717-StarCoder-1B-prediction.jsonl | 1 - .../data/{one-record.jsonl => data-1.jsonl} | 0 .../data/{ten-records.jsonl => data-10.jsonl} | 0 12 files changed, 100 insertions(+), 46 deletions(-) create mode 100644 python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl create mode 100644 python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl delete mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl delete mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl delete mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl delete mode 100644 python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl rename python/tabby-eval/v2-modal/data/{one-record.jsonl => data-1.jsonl} (100%) rename python/tabby-eval/v2-modal/data/{ten-records.jsonl => data-10.jsonl} (100%) diff --git a/python/tabby-eval/v2-modal/README.md b/python/tabby-eval/v2-modal/README.md index 4e672d3b802a..e9a011eb2fd4 100644 --- a/python/tabby-eval/v2-modal/README.md +++ b/python/tabby-eval/v2-modal/README.md @@ -18,7 +18,7 @@ python compute_code_completion.py \ --endpoint https://moqimoqidea--tabby-server-app-serve-dev.modal.run \ --token auth_f1bd0151d4ff4dc6b0ea56cfc82a8b82 \ --model TabbyML/StarCoder-1B \ - --jsonl_file data/one-record.jsonl \ + --jsonl_file data/data-1.jsonl \ --output_jsonl_file_prefix data/20240717-StarCoder-1B ``` diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index 4ee937a7b2e3..d13a81b18d55 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -22,17 +22,23 @@ ) +def generate_headers(token): + headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + } + if token: + headers["Authorization"] = f'Bearer {token}' + + return headers + + def check_service_health(endpoint, token): def modal_tabby_ready(): - url = "{}/v1/health".format(endpoint) - headers = { - "Content-Type": "application/json", - "Accept": "application/json", - "Authorization": f'Bearer {token}' - } - try: - response = httpx.get(url=url, headers=headers, timeout=5) + response = httpx.get(url=("{}/v1/health".format(endpoint)), + headers=generate_headers(token), + timeout=5) if response.status_code == 200: logging.info("Server details: {}".format(response.json())) return True @@ -45,7 +51,7 @@ def modal_tabby_ready(): while not modal_tabby_ready(): time.sleep(5) - logging.info("Modal tabby server ready!") + logging.info("Tabby server ready!\n\n") def monitor_serve_output(process): @@ -82,19 +88,22 @@ def send_sigint_to_process(process): logging.error(f"Failed to send SIGINT signal: {e}") -def send_request_with_retry(url, headers, payload, timeout=10, max_retries=10): +def send_request_with_retry(url, headers, data, timeout=10, max_retries=10): retries = 0 response = None while retries < max_retries: try: - response = httpx.post(url=url, headers=headers, content=json.dumps(payload), timeout=timeout) + response = httpx.post(url=url, + headers=headers, + content=json.dumps(data), + timeout=timeout) if response.status_code == 200: return response else: retries += 1 time.sleep(1) - except httpx.RequestError as e: + except Exception as e: logging.error(f"Get code completion failed: {e}") retries += 1 time.sleep(1) @@ -116,12 +125,15 @@ def get_model_prompt_template(model_id: str): registry, model_name = parse_model_id(model_id) url = f"https://raw.githubusercontent.com/{registry}/registry-tabby/main/models.json" - response = httpx.get(url=url) - response.raise_for_status() + try: + response = httpx.get(url=url) + response.raise_for_status() - for model in response.json(): - if model["name"] == model_name: - return model.get("prompt_template", None) + for model in response.json(): + if model["name"] == model_name: + return model.get("prompt_template", None) + except Exception as e: + logging.error(f"Failed to get model prompt template: {e}") return None @@ -132,30 +144,32 @@ def generate_predictions(endpoint: str, prediction_jsonl_file: str, data_function, prompt_template: str = None): - logging.info(f"Generating predictions to {prediction_jsonl_file}...") + logging.info(f"{prediction_jsonl_file} Start generating predictions ...") df = pd.read_json(jsonl_file, lines=True) df_flat = json_normalize(df.to_dict(orient="records")) - headers = { - 'Content-Type': 'application/json', - 'Accept': 'application/json', - 'Authorization': f'Bearer {token}' - } - predictions = [] prediction_status = [] for index, row in df_flat.iterrows(): - data = data_function(row, prompt_template) if prompt_template else data_function(row) - - # TODO: Add parallelism support url = f"{endpoint}/v1/completions" - response = send_request_with_retry(url, headers, data, timeout=10, max_retries=10) + data = data_function(row, prompt_template) if prompt_template else data_function(row) - if response.status_code == 200: - predictions.append(response.json()['choices'][0]['text']) - prediction_status.append("success") - else: - predictions.append("Request failed after retry.") + try: + # TODO: Add parallelism support + response = send_request_with_retry(url=url, + headers=generate_headers(token), + data=data, + timeout=10, + max_retries=1) + if response.status_code == 200: + predictions.append(response.json()['choices'][0]['text']) + prediction_status.append("success") + else: + predictions.append("Request get status code: {}".format(response.status_code)) + prediction_status.append("failed") + except Exception as e: + logging.error(f"Failed to get prediction: {e}") + predictions.append("Request get exception: {}".format(e)) prediction_status.append("failed") df_flat['prediction'] = predictions @@ -165,9 +179,10 @@ def generate_predictions(endpoint: str, total_records = len(df_flat) success_count = len(df_success) failed_count = total_records - success_count - logging.info(f"Total predictions: {total_records}, Success: {success_count}, Failed: {failed_count}") + logging.info(f"{prediction_jsonl_file} Total predictions: {total_records}, " + f"Success: {success_count}, Failed: {failed_count}\n\n") - df_success.to_json(prediction_jsonl_file, orient='records', lines=True) + df_success.to_json(prediction_jsonl_file, orient='records', lines=True, force_ascii=False) def default_data_function(row): @@ -183,12 +198,15 @@ def default_data_function(row): def cross_file_data_function(row, prompt_template): crossfile_context_list = row['segments.crossfile_context.list'] sorted_list = sorted(crossfile_context_list, key=lambda x: x['score']) + combined_context = "" + + for item in sorted_list: + combined_context += f"// Path: {item['filename']}\n" + retrieved_chunk = item['retrieved_chunk'] + + for line in retrieved_chunk.split("\n"): + combined_context += f"// {line}\n" - # TODO: The added prefix comments should be consistent with the language, for the time being use "//" for all - combined_context = "\n".join( - f"// Path: {item['filename']}\n" + "\n".join(f"// {line}" for line in item['retrieved_chunk'].split("\n")) - for item in sorted_list - ) + "\n" logging.debug(f"Combined context in cross_file_data_function: {combined_context}") return { @@ -243,7 +261,7 @@ def eval_code_completion(endpoint: str, if __name__ == "__main__": parser = argparse.ArgumentParser(description="eval tabby code completion.") parser.add_argument("--endpoint", type=str, required=True, help="tabby server endpoint.") - parser.add_argument("--token", type=str, required=True, default="", help="tabby server token.") + parser.add_argument("--token", type=str, required=False, default="", help="tabby server token.") parser.add_argument("--model", type=str, required=True, help="evaluation model.") parser.add_argument("--jsonl_file", type=str, default="data.jsonl", help="evaluation jsonl file.") parser.add_argument("--output_jsonl_file_prefix", type=str, help=""" diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl new file mode 100644 index 000000000000..112df177b2d1 --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl @@ -0,0 +1,10 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"InstallerEntryData installerEntryData)\n\t\t{","segments.prefix":"\/\/#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(","segments.suffix":"\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"\/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\t\tBuildProjectsList();\n\/\/ \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tLaunchInstaller(entry);\n\/\/ \t\t\t\t\t\treturn;\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\/\/ \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\/\/ \t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\/\/ \t\t\t\t\treturn;\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t{\n\/\/ \t\tGD.Print(\"*********** Delete file!\");\n\/\/ \t}\n\/\/ \tprivate static void CreateDirectoryForUser(string directory)\n\/\/ \t{\n\/\/ \t\tvar path = Path.Combine(BasePath, directory);\n\/\/ \t\tif (!DirAccess.DirExistsAbsolute(path))\n\/\/ \t\t{\n\/\/ \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\/\/ \t\t}\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\/\/ \t\t\t};\n\/\/ \t\t\tprojectEntries.Add(project);\n\/\/ \t\t\tLaunchProject(directoryPath, false);\n\/\/ \t\t}\n\/\/ \t\tvoid _onFilesDropped(string[] files)\n\/\/ \t\t{\n\/\/ \t\t\tfor (int i = 0; i < files.Length; i++)\n\/\/ \t\t\t{\n\/\/ \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t}\n\/\/ \tpublic static void WriteUserText(string path, string json)\n\/\/ \t{\n\/\/ \t\tWriteAllText(PathCombine(BasePath, path), json);\n\/\/ \t}\n\/\/ \tpublic static bool UserFileExists(string path)\n\/\/ \t{\n\/\/ \t\treturn FileExists(PathCombine(BasePath, path));\n\/\/ \t}\n\/\/ \tpublic static void Delete(string path)\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\tInstallVersion(versionKey);\n\/\/ \t\t\t}\n\/\/ \t\t\tSaveProjectsList();\n\/\/ \t\t\tBuildProjectsList();\n\/\/ \t\t}\n\/\/ \t\tvoid SaveConfig()\n\/\/ \t\t{\n\/\/ \t\t\tvar json = DataBuilder.GetConfigJson(config);\n\/\/ \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\/\/ \t\t}\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":29.4318868674},{"retrieved_chunk":"\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":16.1348638558},{"retrieved_chunk":"\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":14.8922002769},{"retrieved_chunk":"\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":13.921454072},{"retrieved_chunk":"\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":13.5350884766}],"metadata.task_id":"project_cc_csharp\/55","metadata.repository":"NathanWarden-ready-to-launch-58eba6d","metadata.file":"godot-project\/Scripts\/DataManagement\/DataPaths.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":94,"metadata.right_context_start_lineno":96,"prediction":"InstallerEntryData installerEntryData)\n\t\t{","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> WorkbooksData {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7105263158,"line_accuracy":0.5,"avg_line_edit_distance":0.8413461538} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n public void SetBreakpoint(ulong address)\n {\n Session.SendCommandStrict(\"breakpoint set address={0:X}\", address);\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.1988950276,"line_accuracy":0.0,"avg_line_edit_distance":0.0} +{"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.2780748663,"line_accuracy":0.0,"avg_line_edit_distance":0.4090909091} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public int NewPlaylistItemId { get; set; }\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.8363636364,"line_accuracy":0.5,"avg_line_edit_distance":0.9318181818} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemMarkerId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemIndependentMediaMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int IndependentMediaId { get; set; }\n\/\/ public long DurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemLocationMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int LocationId { get; set; }\n\/\/ public int MajorMultimediaType { get; set; }\n\/\/ public long? BaseDurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlayListItem.cs\n\/\/ public int Accuracy { get; set; }\n\/\/ public int EndAction { get; set; }\n\/\/ public string ThumbnailFilePath { get; set; } = null!;\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemMarkerParagraphMap\n\/\/ {\n\/\/ public int PlaylistItemMarkerId { get; set; }\n\/\/ public int MepsDocumentId { get; set; }\n\/\/ public int ParagraphIndex { get; set; }\n\/\/ public int MarkerIndexWithinParagraph { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs","score":40.1396202216},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs","score":35.276235533},{"retrieved_chunk":" public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlayListItem.cs","score":29.760486252},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":25.3790812253},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs","score":25.2581961912}],"metadata.task_id":"project_cc_csharp\/29","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":14,"metadata.right_context_start_lineno":16,"prediction":"Ignore]\n public int NewPlaylistItemMarkerId {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl new file mode 100644 index 000000000000..370118613156 --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl @@ -0,0 +1,10 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} +{"language":"csharp","groundtruth":"InstallerEntryData installerEntryData)\n\t\t{","segments.prefix":"\/\/#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(","segments.suffix":"\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"\/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\t\tBuildProjectsList();\n\/\/ \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tLaunchInstaller(entry);\n\/\/ \t\t\t\t\t\treturn;\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\/\/ \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\/\/ \t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\/\/ \t\t\t\t\treturn;\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t{\n\/\/ \t\tGD.Print(\"*********** Delete file!\");\n\/\/ \t}\n\/\/ \tprivate static void CreateDirectoryForUser(string directory)\n\/\/ \t{\n\/\/ \t\tvar path = Path.Combine(BasePath, directory);\n\/\/ \t\tif (!DirAccess.DirExistsAbsolute(path))\n\/\/ \t\t{\n\/\/ \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\/\/ \t\t}\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\/\/ \t\t\t};\n\/\/ \t\t\tprojectEntries.Add(project);\n\/\/ \t\t\tLaunchProject(directoryPath, false);\n\/\/ \t\t}\n\/\/ \t\tvoid _onFilesDropped(string[] files)\n\/\/ \t\t{\n\/\/ \t\t\tfor (int i = 0; i < files.Length; i++)\n\/\/ \t\t\t{\n\/\/ \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t}\n\/\/ \tpublic static void WriteUserText(string path, string json)\n\/\/ \t{\n\/\/ \t\tWriteAllText(PathCombine(BasePath, path), json);\n\/\/ \t}\n\/\/ \tpublic static bool UserFileExists(string path)\n\/\/ \t{\n\/\/ \t\treturn FileExists(PathCombine(BasePath, path));\n\/\/ \t}\n\/\/ \tpublic static void Delete(string path)\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\tInstallVersion(versionKey);\n\/\/ \t\t\t}\n\/\/ \t\t\tSaveProjectsList();\n\/\/ \t\t\tBuildProjectsList();\n\/\/ \t\t}\n\/\/ \t\tvoid SaveConfig()\n\/\/ \t\t{\n\/\/ \t\t\tvar json = DataBuilder.GetConfigJson(config);\n\/\/ \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\/\/ \t\t}\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":29.4318868674},{"retrieved_chunk":"\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":16.1348638558},{"retrieved_chunk":"\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":14.8922002769},{"retrieved_chunk":"\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":13.921454072},{"retrieved_chunk":"\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":13.5350884766}],"metadata.task_id":"project_cc_csharp\/55","metadata.repository":"NathanWarden-ready-to-launch-58eba6d","metadata.file":"godot-project\/Scripts\/DataManagement\/DataPaths.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":94,"metadata.right_context_start_lineno":96,"prediction":"InstallerEntryData installerEntryData)\n\t\t{","prediction_status":"success"} +{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","prediction_status":"success"} +{"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> WorkbooksData {","prediction_status":"success"} +{"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success"} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n public void SetBreakpoint(ulong address)\n {\n Session.SendCommandStrict(\"breakpoint set address={0:X}\", address);\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success"} +{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public int NewPlaylistItemId { get; set; }\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemMarkerId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemIndependentMediaMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int IndependentMediaId { get; set; }\n\/\/ public long DurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemLocationMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int LocationId { get; set; }\n\/\/ public int MajorMultimediaType { get; set; }\n\/\/ public long? BaseDurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlayListItem.cs\n\/\/ public int Accuracy { get; set; }\n\/\/ public int EndAction { get; set; }\n\/\/ public string ThumbnailFilePath { get; set; } = null!;\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemMarkerParagraphMap\n\/\/ {\n\/\/ public int PlaylistItemMarkerId { get; set; }\n\/\/ public int MepsDocumentId { get; set; }\n\/\/ public int ParagraphIndex { get; set; }\n\/\/ public int MarkerIndexWithinParagraph { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs","score":40.1396202216},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs","score":35.276235533},{"retrieved_chunk":" public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlayListItem.cs","score":29.760486252},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":25.3790812253},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs","score":25.2581961912}],"metadata.task_id":"project_cc_csharp\/29","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":14,"metadata.right_context_start_lineno":16,"prediction":"Ignore]\n public int NewPlaylistItemMarkerId {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl new file mode 100644 index 000000000000..f7979bc5812b --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl @@ -0,0 +1,10 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"InstallerEntryData installerEntryData)\n\t\t{","segments.prefix":"\/\/#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(","segments.suffix":"\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"\/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\t\tBuildProjectsList();\n\/\/ \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tLaunchInstaller(entry);\n\/\/ \t\t\t\t\t\treturn;\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\/\/ \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\/\/ \t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\/\/ \t\t\t\t\treturn;\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t{\n\/\/ \t\tGD.Print(\"*********** Delete file!\");\n\/\/ \t}\n\/\/ \tprivate static void CreateDirectoryForUser(string directory)\n\/\/ \t{\n\/\/ \t\tvar path = Path.Combine(BasePath, directory);\n\/\/ \t\tif (!DirAccess.DirExistsAbsolute(path))\n\/\/ \t\t{\n\/\/ \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\/\/ \t\t}\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\/\/ \t\t\t};\n\/\/ \t\t\tprojectEntries.Add(project);\n\/\/ \t\t\tLaunchProject(directoryPath, false);\n\/\/ \t\t}\n\/\/ \t\tvoid _onFilesDropped(string[] files)\n\/\/ \t\t{\n\/\/ \t\t\tfor (int i = 0; i < files.Length; i++)\n\/\/ \t\t\t{\n\/\/ \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t}\n\/\/ \tpublic static void WriteUserText(string path, string json)\n\/\/ \t{\n\/\/ \t\tWriteAllText(PathCombine(BasePath, path), json);\n\/\/ \t}\n\/\/ \tpublic static bool UserFileExists(string path)\n\/\/ \t{\n\/\/ \t\treturn FileExists(PathCombine(BasePath, path));\n\/\/ \t}\n\/\/ \tpublic static void Delete(string path)\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\tInstallVersion(versionKey);\n\/\/ \t\t\t}\n\/\/ \t\t\tSaveProjectsList();\n\/\/ \t\t\tBuildProjectsList();\n\/\/ \t\t}\n\/\/ \t\tvoid SaveConfig()\n\/\/ \t\t{\n\/\/ \t\t\tvar json = DataBuilder.GetConfigJson(config);\n\/\/ \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\/\/ \t\t}\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":29.4318868674},{"retrieved_chunk":"\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":16.1348638558},{"retrieved_chunk":"\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":14.8922002769},{"retrieved_chunk":"\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":13.921454072},{"retrieved_chunk":"\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":13.5350884766}],"metadata.task_id":"project_cc_csharp\/55","metadata.repository":"NathanWarden-ready-to-launch-58eba6d","metadata.file":"godot-project\/Scripts\/DataManagement\/DataPaths.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":94,"metadata.right_context_start_lineno":96,"prediction":"InstallerEntryData installerEntryData)\n\t\t{","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"user_id\")]\n public int UserId { get; set; }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7096774194,"line_accuracy":0.0,"avg_line_edit_distance":0.7131868132} +{"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> Workbooks {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.9333333333,"line_accuracy":0.0,"avg_line_edit_distance":0.9333333333} +{"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7105263158,"line_accuracy":0.5,"avg_line_edit_distance":0.8413461538} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n var module = new XboxModule();\n module.Name = line.Substring(0, line.IndexOf(' '));\n module.Base = ulong.Parse(line.Substring(line.IndexOf(' ') + 1, 8), NumberStyles.HexNumber);\n module.Size = ulong.Parse(line.Substring(line.IndexOf(' ', line.IndexOf(' ') + 1) + 1, 8), NumberStyles.HexNumber);\n modules.Add(module);\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.0927152318,"line_accuracy":0.0,"avg_line_edit_distance":0.0} +{"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.2780748663,"line_accuracy":0.0,"avg_line_edit_distance":0.4090909091} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public Playlist Playlist {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.8181818182,"line_accuracy":0.5,"avg_line_edit_distance":0.8888888889} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemMarkerId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemIndependentMediaMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int IndependentMediaId { get; set; }\n\/\/ public long DurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemLocationMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int LocationId { get; set; }\n\/\/ public int MajorMultimediaType { get; set; }\n\/\/ public long? BaseDurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlayListItem.cs\n\/\/ public int Accuracy { get; set; }\n\/\/ public int EndAction { get; set; }\n\/\/ public string ThumbnailFilePath { get; set; } = null!;\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemMarkerParagraphMap\n\/\/ {\n\/\/ public int PlaylistItemMarkerId { get; set; }\n\/\/ public int MepsDocumentId { get; set; }\n\/\/ public int ParagraphIndex { get; set; }\n\/\/ public int MarkerIndexWithinParagraph { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs","score":40.1396202216},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs","score":35.276235533},{"retrieved_chunk":" public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlayListItem.cs","score":29.760486252},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":25.3790812253},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs","score":25.2581961912}],"metadata.task_id":"project_cc_csharp\/29","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":14,"metadata.right_context_start_lineno":16,"prediction":"Ignore]\n public PlaylistItem PlaylistItem {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7843137255,"line_accuracy":0.5,"avg_line_edit_distance":0.8720930233} diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl new file mode 100644 index 000000000000..b53cc2d467a5 --- /dev/null +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl @@ -0,0 +1,10 @@ +{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} +{"language":"csharp","groundtruth":"InstallerEntryData installerEntryData)\n\t\t{","segments.prefix":"\/\/#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(","segments.suffix":"\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"\/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\t\tBuildProjectsList();\n\/\/ \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tLaunchInstaller(entry);\n\/\/ \t\t\t\t\t\treturn;\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\/\/ \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\/\/ \t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\/\/ \t\t\t\t\treturn;\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t{\n\/\/ \t\tGD.Print(\"*********** Delete file!\");\n\/\/ \t}\n\/\/ \tprivate static void CreateDirectoryForUser(string directory)\n\/\/ \t{\n\/\/ \t\tvar path = Path.Combine(BasePath, directory);\n\/\/ \t\tif (!DirAccess.DirExistsAbsolute(path))\n\/\/ \t\t{\n\/\/ \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\/\/ \t\t}\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\/\/ \t\t\t};\n\/\/ \t\t\tprojectEntries.Add(project);\n\/\/ \t\t\tLaunchProject(directoryPath, false);\n\/\/ \t\t}\n\/\/ \t\tvoid _onFilesDropped(string[] files)\n\/\/ \t\t{\n\/\/ \t\t\tfor (int i = 0; i < files.Length; i++)\n\/\/ \t\t\t{\n\/\/ \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t}\n\/\/ \tpublic static void WriteUserText(string path, string json)\n\/\/ \t{\n\/\/ \t\tWriteAllText(PathCombine(BasePath, path), json);\n\/\/ \t}\n\/\/ \tpublic static bool UserFileExists(string path)\n\/\/ \t{\n\/\/ \t\treturn FileExists(PathCombine(BasePath, path));\n\/\/ \t}\n\/\/ \tpublic static void Delete(string path)\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\tInstallVersion(versionKey);\n\/\/ \t\t\t}\n\/\/ \t\t\tSaveProjectsList();\n\/\/ \t\t\tBuildProjectsList();\n\/\/ \t\t}\n\/\/ \t\tvoid SaveConfig()\n\/\/ \t\t{\n\/\/ \t\t\tvar json = DataBuilder.GetConfigJson(config);\n\/\/ \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\/\/ \t\t}\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":29.4318868674},{"retrieved_chunk":"\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":16.1348638558},{"retrieved_chunk":"\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":14.8922002769},{"retrieved_chunk":"\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":13.921454072},{"retrieved_chunk":"\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":13.5350884766}],"metadata.task_id":"project_cc_csharp\/55","metadata.repository":"NathanWarden-ready-to-launch-58eba6d","metadata.file":"godot-project\/Scripts\/DataManagement\/DataPaths.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":94,"metadata.right_context_start_lineno":96,"prediction":"InstallerEntryData installerEntryData)\n\t\t{","prediction_status":"success"} +{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"user_id\")]\n public int UserId { get; set; }","prediction_status":"success"} +{"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> Workbooks {","prediction_status":"success"} +{"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success"} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n var module = new XboxModule();\n module.Name = line.Substring(0, line.IndexOf(' '));\n module.Base = ulong.Parse(line.Substring(line.IndexOf(' ') + 1, 8), NumberStyles.HexNumber);\n module.Size = ulong.Parse(line.Substring(line.IndexOf(' ', line.IndexOf(' ') + 1) + 1, 8), NumberStyles.HexNumber);\n modules.Add(module);\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success"} +{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public Playlist Playlist {","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemMarkerId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemIndependentMediaMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int IndependentMediaId { get; set; }\n\/\/ public long DurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemLocationMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int LocationId { get; set; }\n\/\/ public int MajorMultimediaType { get; set; }\n\/\/ public long? BaseDurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlayListItem.cs\n\/\/ public int Accuracy { get; set; }\n\/\/ public int EndAction { get; set; }\n\/\/ public string ThumbnailFilePath { get; set; } = null!;\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemMarkerParagraphMap\n\/\/ {\n\/\/ public int PlaylistItemMarkerId { get; set; }\n\/\/ public int MepsDocumentId { get; set; }\n\/\/ public int ParagraphIndex { get; set; }\n\/\/ public int MarkerIndexWithinParagraph { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs","score":40.1396202216},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs","score":35.276235533},{"retrieved_chunk":" public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlayListItem.cs","score":29.760486252},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":25.3790812253},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs","score":25.2581961912}],"metadata.task_id":"project_cc_csharp\/29","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":14,"metadata.right_context_start_lineno":16,"prediction":"Ignore]\n public PlaylistItem PlaylistItem {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl deleted file mode 100644 index dd9a51070031..000000000000 --- a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-evaluation.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl deleted file mode 100644 index 0b67833a20cf..000000000000 --- a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-cross-file-content-prediction.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl deleted file mode 100644 index dd9a51070031..000000000000 --- a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-evaluation.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} diff --git a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl deleted file mode 100644 index 0b67833a20cf..000000000000 --- a/python/tabby-eval/v2-modal/data/20240717-StarCoder-1B-prediction.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/one-record.jsonl b/python/tabby-eval/v2-modal/data/data-1.jsonl similarity index 100% rename from python/tabby-eval/v2-modal/data/one-record.jsonl rename to python/tabby-eval/v2-modal/data/data-1.jsonl diff --git a/python/tabby-eval/v2-modal/data/ten-records.jsonl b/python/tabby-eval/v2-modal/data/data-10.jsonl similarity index 100% rename from python/tabby-eval/v2-modal/data/ten-records.jsonl rename to python/tabby-eval/v2-modal/data/data-10.jsonl From a86d0feeb9ed03913df96f299571ad203d434a25 Mon Sep 17 00:00:00 2001 From: moqimoqidea Date: Wed, 17 Jul 2024 20:51:28 +0800 Subject: [PATCH 19/19] Eval-V2-Modal: use segments.crossfile_context.text to compute code completion --- .../v2-modal/compute_code_completion.py | 15 +-------------- ...ama-13B-10-cross-file-content-evaluation.jsonl | 4 ++-- ...ama-13B-10-cross-file-content-prediction.jsonl | 4 ++-- .../20240717-CodeLlama-13B-10-evaluation.jsonl | 6 +++--- .../20240717-CodeLlama-13B-10-prediction.jsonl | 6 +++--- 5 files changed, 11 insertions(+), 24 deletions(-) diff --git a/python/tabby-eval/v2-modal/compute_code_completion.py b/python/tabby-eval/v2-modal/compute_code_completion.py index d13a81b18d55..c7b1edacb625 100755 --- a/python/tabby-eval/v2-modal/compute_code_completion.py +++ b/python/tabby-eval/v2-modal/compute_code_completion.py @@ -196,23 +196,10 @@ def default_data_function(row): def cross_file_data_function(row, prompt_template): - crossfile_context_list = row['segments.crossfile_context.list'] - sorted_list = sorted(crossfile_context_list, key=lambda x: x['score']) - combined_context = "" - - for item in sorted_list: - combined_context += f"// Path: {item['filename']}\n" - retrieved_chunk = item['retrieved_chunk'] - - for line in retrieved_chunk.split("\n"): - combined_context += f"// {line}\n" - - logging.debug(f"Combined context in cross_file_data_function: {combined_context}") - return { "debug_options": { "raw_prompt": prompt_template.format( - prefix=combined_context + row['segments.prefix'], + prefix=row['segments.crossfile_context.text'] + row['segments.prefix'], suffix=row['segments.suffix']) } } diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl index 112df177b2d1..86c5a37c872c 100644 --- a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-evaluation.jsonl @@ -1,9 +1,9 @@ {"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} {"language":"csharp","groundtruth":"InstallerEntryData installerEntryData)\n\t\t{","segments.prefix":"\/\/#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(","segments.suffix":"\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"\/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\t\tBuildProjectsList();\n\/\/ \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tLaunchInstaller(entry);\n\/\/ \t\t\t\t\t\treturn;\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\/\/ \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\/\/ \t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\/\/ \t\t\t\t\treturn;\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t{\n\/\/ \t\tGD.Print(\"*********** Delete file!\");\n\/\/ \t}\n\/\/ \tprivate static void CreateDirectoryForUser(string directory)\n\/\/ \t{\n\/\/ \t\tvar path = Path.Combine(BasePath, directory);\n\/\/ \t\tif (!DirAccess.DirExistsAbsolute(path))\n\/\/ \t\t{\n\/\/ \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\/\/ \t\t}\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\/\/ \t\t\t};\n\/\/ \t\t\tprojectEntries.Add(project);\n\/\/ \t\t\tLaunchProject(directoryPath, false);\n\/\/ \t\t}\n\/\/ \t\tvoid _onFilesDropped(string[] files)\n\/\/ \t\t{\n\/\/ \t\t\tfor (int i = 0; i < files.Length; i++)\n\/\/ \t\t\t{\n\/\/ \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t}\n\/\/ \tpublic static void WriteUserText(string path, string json)\n\/\/ \t{\n\/\/ \t\tWriteAllText(PathCombine(BasePath, path), json);\n\/\/ \t}\n\/\/ \tpublic static bool UserFileExists(string path)\n\/\/ \t{\n\/\/ \t\treturn FileExists(PathCombine(BasePath, path));\n\/\/ \t}\n\/\/ \tpublic static void Delete(string path)\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\tInstallVersion(versionKey);\n\/\/ \t\t\t}\n\/\/ \t\t\tSaveProjectsList();\n\/\/ \t\t\tBuildProjectsList();\n\/\/ \t\t}\n\/\/ \t\tvoid SaveConfig()\n\/\/ \t\t{\n\/\/ \t\t\tvar json = DataBuilder.GetConfigJson(config);\n\/\/ \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\/\/ \t\t}\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":29.4318868674},{"retrieved_chunk":"\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":16.1348638558},{"retrieved_chunk":"\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":14.8922002769},{"retrieved_chunk":"\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":13.921454072},{"retrieved_chunk":"\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":13.5350884766}],"metadata.task_id":"project_cc_csharp\/55","metadata.repository":"NathanWarden-ready-to-launch-58eba6d","metadata.file":"godot-project\/Scripts\/DataManagement\/DataPaths.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":94,"metadata.right_context_start_lineno":96,"prediction":"InstallerEntryData installerEntryData)\n\t\t{","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} -{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} +{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"user_id\")]\n public int UserId { get; set; }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7096774194,"line_accuracy":0.0,"avg_line_edit_distance":0.7131868132} {"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> WorkbooksData {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} {"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7105263158,"line_accuracy":0.5,"avg_line_edit_distance":0.8413461538} -{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n public void SetBreakpoint(ulong address)\n {\n Session.SendCommandStrict(\"breakpoint set address={0:X}\", address);\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.1988950276,"line_accuracy":0.0,"avg_line_edit_distance":0.0} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n return _cache.GetOrCreate(nameof(Modules), () =>\n {\n var modules = new List();\n Session.SendCommandStrict(\"modules\");\n foreach (string module in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = module.ParseXboxResponseLine();\n var info = new XboxModule();\n info.Name = (string)moduleInfo[\"name\"];\n info.Base = (long)moduleInfo[\"base\"];\n info.Size = (long)moduleInfo[\"size\"];\n modules.Add(info);\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.0714285714,"line_accuracy":0.0,"avg_line_edit_distance":0.0} {"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} {"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.2780748663,"line_accuracy":0.0,"avg_line_edit_distance":0.4090909091} {"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public int NewPlaylistItemId { get; set; }\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.8363636364,"line_accuracy":0.5,"avg_line_edit_distance":0.9318181818} diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl index 370118613156..24b252a7c4c5 100644 --- a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-cross-file-content-prediction.jsonl @@ -1,9 +1,9 @@ {"language":"csharp","groundtruth":"LassoProfile> GetLassoProfiles()\n {","segments.prefix":"using LassoProcessManager.Models.Rules;\nusing Newtonsoft.Json;\nusing ProcessManager.Models.Configs;\nusing System.Reflection;\n\nnamespace ProcessManager.Providers\n{\n public class ConfigProvider : IConfigProvider\n {\n private const string ConfigFileName = \"Config.json\";\n private ManagerConfig managerConfig;\n\n private ILogProvider LogProvider { get; set; }\n\n public ConfigProvider(ILogProvider logProvider)\n => this.LogProvider = logProvider;\n\n public ManagerConfig GetManagerConfig()\n {\n if (managerConfig != null)\n return managerConfig;\n\n string configPath = GetConfigFilePath();\n try\n {\n managerConfig = JsonConvert.DeserializeObject(File.ReadAllText(GetConfigFilePath()));\n return managerConfig;\n }\n catch\n {\n LogProvider.Log($\"Failed to load config at '{configPath}'.\");\n }\n\n return null;\n }\n\n public List GetRules()\n {\n List rules = new List();\n rules.AddRange(managerConfig.ProcessRules);\n rules.AddRange(managerConfig.FolderRules);\n\n return rules;\n }\n\n public Dictionary lassoProfiles = new Dictionary();\n\n \/\/ Load lasso profiles\n foreach (var profile in managerConfig.Profiles)\n {\n if (!lassoProfiles.ContainsKey(profile.Name))\n {\n lassoProfiles.Add(profile.Name, profile);\n }\n }\n\n return lassoProfiles;\n }\n\n private string GetConfigFilePath()\n => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigFileName);\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Providers\/IConfigProvider.cs\n\/\/ ManagerConfig GetManagerConfig();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Geth the list of lasso rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ List GetRules();\n\/\/ Dictionary GetLassoProfiles();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Models\/Configs\/ManagerConfig.cs\n\/\/ public ProcessRule[] ProcessRules { get; set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ List of folders rules.\n\/\/ \/\/\/ <\/summary>\n\/\/ public FolderRule[] FolderRules { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ public void Dispose()\n\/\/ {\n\/\/ if (processStartEvent != null) \n\/\/ {\n\/\/ processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n\/\/ processStartEvent.Dispose();\n\/\/ processStartEvent = null;\n\/\/ }\n\/\/ }\n\/\/ public bool Setup()\n\n\/\/ the below code fragment can be found in:\n\/\/ ProcessManager\/Managers\/LassoManager.cs\n\/\/ {\n\/\/ int failCount = 0;\n\/\/ Dictionary successCount = new Dictionary();\n\/\/ foreach (var process in Process.GetProcesses())\n\/\/ {\n\/\/ LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n\/\/ bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n\/\/ if (success)\n\/\/ {\n\/\/ if (!successCount.ContainsKey(profileName))\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" ManagerConfig GetManagerConfig();\n \/\/\/ \n \/\/\/ Geth the list of lasso rules.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n List GetRules();\n Dictionary GetLassoProfiles();\n }\n}","filename":"ProcessManager\/Providers\/IConfigProvider.cs","score":22.7999942753},{"retrieved_chunk":" public ProcessRule[] ProcessRules { get; set; }\n \/\/\/ \n \/\/\/ List of folders rules.\n \/\/\/ <\/summary>\n public FolderRule[] FolderRules { get; set; }\n }\n}","filename":"ProcessManager\/Models\/Configs\/ManagerConfig.cs","score":20.7281934979},{"retrieved_chunk":" public void Dispose()\n {\n if (processStartEvent != null) \n {\n processStartEvent.EventArrived -= ProcessStartEvent_EventArrived;\n processStartEvent.Dispose();\n processStartEvent = null;\n }\n }\n public bool Setup()","filename":"ProcessManager\/Managers\/LassoManager.cs","score":14.5062472942},{"retrieved_chunk":" {\n int failCount = 0;\n Dictionary successCount = new Dictionary();\n foreach (var process in Process.GetProcesses())\n {\n LassoProfile lassoProfile = GetLassoProfileForProcess(process);\n bool success = TrySetProcessProfile(process, lassoProfile, out string profileName);\n if (success)\n {\n if (!successCount.ContainsKey(profileName))","filename":"ProcessManager\/Managers\/LassoManager.cs","score":11.7891491159}],"metadata.task_id":"project_cc_csharp\/27","metadata.repository":"kenshinakh1-LassoProcessManager-bcc481f","metadata.file":"ProcessManager\/Providers\/ConfigProvider.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":45,"metadata.right_context_start_lineno":47,"prediction":"LassoProfile> GetLassoProfiles()\n {","prediction_status":"success"} {"language":"csharp","groundtruth":"InstallerEntryData installerEntryData)\n\t\t{","segments.prefix":"\/\/#define PRINT_DEBUG\n\nusing System;\nusing System.IO;\nusing Godot;\nusing Mono.Unix;\nusing Directory = System.IO.Directory;\nusing Environment = System.Environment;\nusing File = System.IO.File;\nusing Path = System.IO.Path;\n\nnamespace GodotLauncher\n{\n\tpublic class DataPaths\n\t{\n\t\tstatic string AppDataPath => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\t\tstatic string BasePath => Path.Combine(AppDataPath, \"ReadyToLaunch\");\n\t\tpublic static string platformOverride;\n\n\n\t\tpublic static string SanitizeProjectPath(string path)\n\t\t{\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\tpath = new FileInfo(path).DirectoryName;\n\t\t\t}\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static void EnsureProjectExists(string path)\n\t\t{\n\t\t\tvar filePath = Path.Combine(path, \"project.godot\");\n\t\t\tif (!File.Exists(filePath)) File.WriteAllText(filePath, \"\");\n\t\t}\n\n\n\t\tpublic static string GetExecutablePath(InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring platformName = GetPlatformName();\n\t\t\tstring path = Path.Combine(BasePath, platformName, installerEntryData.BuildType, installerEntryData.version);\n\n\t\t\tpath = Path.Combine(path, installerEntryData.ExecutableName);\n\n\t\t\treturn path;\n\t\t}\n\n\n\t\tpublic static string GetPlatformName()\n\t\t{\n\t\t\tif (!string.IsNullOrEmpty(platformOverride)) return platformOverride;\n\t\t\treturn OS.GetName();\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, byte[] data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllBytes(path, data);\n\t\t}\n\n\n\t\tpublic static void WriteFile(string fileName, string data)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Writing: \" + path);\n\t\t\t#endif\n\t\t\tFile.WriteAllText(path, data);\n\t\t}\n\n\n\t\tpublic static string ReadFile(string fileName, string defaultData = null)\n\t\t{\n\t\t\tvar path = Path.Combine(BasePath, fileName);\n\t\t\tif (File.Exists(path))\n\t\t\t{\n\t\t\t\t#if PRINT_DEBUG\n\t\t\t\tGD.Print(\"Reading: \" + path);\n\t\t\t\t#endif\n\t\t\t\treturn File.ReadAllText(path);\n\t\t\t}\n\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"File not found: \" + path);\n\t\t\t#endif\n\t\t\treturn defaultData;\n\t\t}\n\n\n\t\tpublic static bool ExecutableExists(","segments.suffix":"\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\tbool exists = File.Exists(path);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Checking if path exists: \" + path + \" exists=\" + exists);\n\t\t\t#endif\n\t\t\treturn exists;\n\t\t}\n\n\n\t\tpublic static void ExtractArchive(string fileName, InstallerEntryData installerEntryData)\n\t\t{\n\t\t\tstring source = Path.Combine(BasePath, fileName);\n\t\t\tstring dest = Path.Combine(BasePath, GetPlatformName(), installerEntryData.BuildType, installerEntryData.version);\n\t\t\tif (!Directory.Exists(dest)) System.IO.Compression.ZipFile.ExtractToDirectory(source, dest);\n\t\t\tFile.Delete(source);\n\t\t}\n\n\n\t\tpublic static void DeleteVersion(string version, string buildType)\n\t\t{\n\t\t\tDirectory.Delete(Path.Combine(BasePath, GetPlatformName(), buildType, version), true);\n\t\t}\n\n\n\t\tpublic static void LaunchGodot(InstallerEntryData installerEntryData, string arguments = \"\")\n\t\t{\n\t\t\tstring path = GetExecutablePath(installerEntryData);\n\t\t\t#if PRINT_DEBUG\n\t\t\tGD.Print(\"Launching: \" + path);\n\t\t\t#endif\n\t\t\tif (!OS.GetName().Equals(\"Windows\"))\n\t\t\t{\n\t\t\t\tvar unixFile = new UnixFileInfo(path);\n\t\t\t\tunixFile.FileAccessPermissions |= FileAccessPermissions.UserExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.GroupExecute\n\t\t\t\t\t\t\t\t\t\t\t\t | FileAccessPermissions.OtherExecute;\n\t\t\t}\n\n\t\t\tusing var process = new System.Diagnostics.Process();\n\t\t\tprocess.StartInfo.FileName = path;\n\t\t\tprocess.StartInfo.WorkingDirectory = BasePath;\n\t\t\tprocess.StartInfo.Arguments = arguments;\n\t\t\tprocess.Start();\n\t\t}\n\n\n\t\tpublic static void CreateInstallationDirectory()\n\t\t{\n\t\t\tMoveOldInstallationDirectory(\"ReadyForLaunch\");\n\t\t\tMoveOldInstallationDirectory(\"GodotLauncher\");\n\t\t\tDirectory.CreateDirectory(BasePath);\n\t\t}\n\n\n\t\tstatic void MoveOldInstallationDirectory(string oldName)\n\t\t{\n\t\t\tvar oldPath = Path.Combine(AppDataPath, oldName);\n\t\t\tif (!Directory.Exists(oldPath) || Directory.Exists(BasePath))\n\t\t\t\treturn;\n\t\t\tDirectory.Move(oldPath, BasePath);\n\t\t}\n\n\n\t\tpublic static void ShowInFolder(string filePath)\n\t\t{\n\t\t\tfilePath = \"\\\"\" + filePath + \"\\\"\";\n\t\t\tswitch (OS.GetName())\n\t\t\t{\n\t\t\t\tcase \"Linux\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"xdg-open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Windows\":\n\t\t\t\t\tstring argument = \"\/select, \" + filePath;\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"macOS\":\n\t\t\t\t\tSystem.Diagnostics.Process.Start(\"open\", filePath);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OS not defined! \" + OS.GetName());\n\t\t\t}\n\t\t}\n\t}\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\t\tBuildProjectsList();\n\/\/ \t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tLaunchInstaller(entry);\n\/\/ \t\t\t\t\t\treturn;\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\/\/ \t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\/\/ \t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\/\/ \t\t\t\t\treturn;\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t{\n\/\/ \t\tGD.Print(\"*********** Delete file!\");\n\/\/ \t}\n\/\/ \tprivate static void CreateDirectoryForUser(string directory)\n\/\/ \t{\n\/\/ \t\tvar path = Path.Combine(BasePath, directory);\n\/\/ \t\tif (!DirAccess.DirExistsAbsolute(path))\n\/\/ \t\t{\n\/\/ \t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\/\/ \t\t}\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\/\/ \t\t\t};\n\/\/ \t\t\tprojectEntries.Add(project);\n\/\/ \t\t\tLaunchProject(directoryPath, false);\n\/\/ \t\t}\n\/\/ \t\tvoid _onFilesDropped(string[] files)\n\/\/ \t\t{\n\/\/ \t\t\tfor (int i = 0; i < files.Length; i++)\n\/\/ \t\t\t{\n\/\/ \t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/FileHelper.cs\n\/\/ \t}\n\/\/ \tpublic static void WriteUserText(string path, string json)\n\/\/ \t{\n\/\/ \t\tWriteAllText(PathCombine(BasePath, path), json);\n\/\/ \t}\n\/\/ \tpublic static bool UserFileExists(string path)\n\/\/ \t{\n\/\/ \t\treturn FileExists(PathCombine(BasePath, path));\n\/\/ \t}\n\/\/ \tpublic static void Delete(string path)\n\n\/\/ the below code fragment can be found in:\n\/\/ godot-project\/Scripts\/DataManagement\/LauncherManager.cs\n\/\/ \t\t\t\tInstallVersion(versionKey);\n\/\/ \t\t\t}\n\/\/ \t\t\tSaveProjectsList();\n\/\/ \t\t\tBuildProjectsList();\n\/\/ \t\t}\n\/\/ \t\tvoid SaveConfig()\n\/\/ \t\t{\n\/\/ \t\t\tvar json = DataBuilder.GetConfigJson(config);\n\/\/ \t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\/\/ \t\t}\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"\t\t\t\t\tBuildProjectsList();\n\t\t\t\t\tif (entry.version.StartsWith(\"1.\") || entry.version.StartsWith(\"2.\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tLaunchInstaller(entry);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar additionalFlags = run ? \"\" : \"-e\";\n\t\t\t\t\tDataPaths.LaunchGodot(entry, additionalFlags + \" --path \\\"\" + path + \"\\\"\");\n\t\t\t\t\t\/\/OS.WindowMinimized = config.minimizeOnLaunch;\n\t\t\t\t\treturn;","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":29.4318868674},{"retrieved_chunk":"\t{\n\t\tGD.Print(\"*********** Delete file!\");\n\t}\n\tprivate static void CreateDirectoryForUser(string directory)\n\t{\n\t\tvar path = Path.Combine(BasePath, directory);\n\t\tif (!DirAccess.DirExistsAbsolute(path))\n\t\t{\n\t\t\tDirAccess.MakeDirRecursiveAbsolute(path);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":16.1348638558},{"retrieved_chunk":"\t\t\t\ttimestamp = DateTime.UtcNow.Ticks\n\t\t\t};\n\t\t\tprojectEntries.Add(project);\n\t\t\tLaunchProject(directoryPath, false);\n\t\t}\n\t\tvoid _onFilesDropped(string[] files)\n\t\t{\n\t\t\tfor (int i = 0; i < files.Length; i++)\n\t\t\t{\n\t\t\t\tstring path = DataPaths.SanitizeProjectPath(files[i]);","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":14.8922002769},{"retrieved_chunk":"\t}\n\tpublic static void WriteUserText(string path, string json)\n\t{\n\t\tWriteAllText(PathCombine(BasePath, path), json);\n\t}\n\tpublic static bool UserFileExists(string path)\n\t{\n\t\treturn FileExists(PathCombine(BasePath, path));\n\t}\n\tpublic static void Delete(string path)","filename":"godot-project\/Scripts\/DataManagement\/FileHelper.cs","score":13.921454072},{"retrieved_chunk":"\t\t\t\tInstallVersion(versionKey);\n\t\t\t}\n\t\t\tSaveProjectsList();\n\t\t\tBuildProjectsList();\n\t\t}\n\t\tvoid SaveConfig()\n\t\t{\n\t\t\tvar json = DataBuilder.GetConfigJson(config);\n\t\t\tDataPaths.WriteFile(ConfigFileName, json);\n\t\t}","filename":"godot-project\/Scripts\/DataManagement\/LauncherManager.cs","score":13.5350884766}],"metadata.task_id":"project_cc_csharp\/55","metadata.repository":"NathanWarden-ready-to-launch-58eba6d","metadata.file":"godot-project\/Scripts\/DataManagement\/DataPaths.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":94,"metadata.right_context_start_lineno":96,"prediction":"InstallerEntryData installerEntryData)\n\t\t{","prediction_status":"success"} -{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","prediction_status":"success"} +{"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"user_id\")]\n public int UserId { get; set; }","prediction_status":"success"} {"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> WorkbooksData {","prediction_status":"success"} {"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success"} -{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n public void SetBreakpoint(ulong address)\n {\n Session.SendCommandStrict(\"breakpoint set address={0:X}\", address);\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n return _cache.GetOrCreate(nameof(Modules), () =>\n {\n var modules = new List();\n Session.SendCommandStrict(\"modules\");\n foreach (string module in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = module.ParseXboxResponseLine();\n var info = new XboxModule();\n info.Name = (string)moduleInfo[\"name\"];\n info.Base = (long)moduleInfo[\"base\"];\n info.Size = (long)moduleInfo[\"size\"];\n modules.Add(info);\n }","prediction_status":"success"} {"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success"} {"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success"} {"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public int NewPlaylistItemId { get; set; }\n }","prediction_status":"success"} diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl index f7979bc5812b..45dd1b717963 100644 --- a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-evaluation.jsonl @@ -3,8 +3,8 @@ {"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"user_id\")]\n public int UserId { get; set; }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7096774194,"line_accuracy":0.0,"avg_line_edit_distance":0.7131868132} {"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> Workbooks {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.9333333333,"line_accuracy":0.0,"avg_line_edit_distance":0.9333333333} {"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7105263158,"line_accuracy":0.5,"avg_line_edit_distance":0.8413461538} -{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n var module = new XboxModule();\n module.Name = line.Substring(0, line.IndexOf(' '));\n module.Base = ulong.Parse(line.Substring(line.IndexOf(' ') + 1, 8), NumberStyles.HexNumber);\n module.Size = ulong.Parse(line.Substring(line.IndexOf(' ', line.IndexOf(' ') + 1) + 1, 8), NumberStyles.HexNumber);\n modules.Add(module);\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.0927152318,"line_accuracy":0.0,"avg_line_edit_distance":0.0} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n var modules = new List();\n Session.SendCommandStrict(\"modulelist\");\n foreach (string module in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = module.ParseXboxResponseLine();\n var info = new XboxModule();\n info.Name = (string)moduleInfo[\"name\"];\n info.Base = (long)moduleInfo[\"base\"];\n info.Size = (long)moduleInfo[\"size\"];\n modules.Add(info);\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.0794701987,"line_accuracy":0.0,"avg_line_edit_distance":0.0} {"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success","block_accuracy":1,"block_edit_distance":1.0,"line_accuracy":1.0,"avg_line_edit_distance":1.0} -{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.2780748663,"line_accuracy":0.0,"avg_line_edit_distance":0.4090909091} -{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public Playlist Playlist {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.8181818182,"line_accuracy":0.5,"avg_line_edit_distance":0.8888888889} +{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n \/\/\/ \n \/\/\/ 启动服务\n \/\/\/ <\/summary>\n [SupportedOSPlatform(\"windows\")]\n public override void Start()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.2828282828,"line_accuracy":0.0,"avg_line_edit_distance":0.2666666667} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public Playlist Playlist { get; set; } = null!;\n public int PlaylistId { get; set; }","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.522875817,"line_accuracy":0.5,"avg_line_edit_distance":0.811827957} {"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemMarkerId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemIndependentMediaMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int IndependentMediaId { get; set; }\n\/\/ public long DurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemLocationMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int LocationId { get; set; }\n\/\/ public int MajorMultimediaType { get; set; }\n\/\/ public long? BaseDurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlayListItem.cs\n\/\/ public int Accuracy { get; set; }\n\/\/ public int EndAction { get; set; }\n\/\/ public string ThumbnailFilePath { get; set; } = null!;\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemMarkerParagraphMap\n\/\/ {\n\/\/ public int PlaylistItemMarkerId { get; set; }\n\/\/ public int MepsDocumentId { get; set; }\n\/\/ public int ParagraphIndex { get; set; }\n\/\/ public int MarkerIndexWithinParagraph { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs","score":40.1396202216},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs","score":35.276235533},{"retrieved_chunk":" public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlayListItem.cs","score":29.760486252},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":25.3790812253},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs","score":25.2581961912}],"metadata.task_id":"project_cc_csharp\/29","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":14,"metadata.right_context_start_lineno":16,"prediction":"Ignore]\n public PlaylistItem PlaylistItem {","prediction_status":"success","block_accuracy":0,"block_edit_distance":0.7843137255,"line_accuracy":0.5,"avg_line_edit_distance":0.8720930233} diff --git a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl index b53cc2d467a5..76ac0a61a6d8 100644 --- a/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl +++ b/python/tabby-eval/v2-modal/data/20240717-CodeLlama-13B-10-prediction.jsonl @@ -3,8 +3,8 @@ {"language":"csharp","groundtruth":"JsonProperty(\"likes_given\")]\n public int LikesGiven {","segments.prefix":"using Newtonsoft.Json;\n\nnamespace DotNetDevBadgeWeb.Model\n{\n public class UserSummary\n {\n [","segments.suffix":" get; set; }\n\n [JsonProperty(\"likes_received\")]\n public int LikesReceived { get; set; }\n\n [JsonProperty(\"topics_entered\")]\n public int TopicsEntered { get; set; }\n\n [JsonProperty(\"posts_read_count\")]\n public int PostsReadCount { get; set; }\n\n [JsonProperty(\"days_visited\")]\n public int DaysVisited { get; set; }\n\n [JsonProperty(\"topic_count\")]\n public int TopicCount { get; set; }\n\n [JsonProperty(\"post_count\")]\n public int PostCount { get; set; }\n\n [JsonProperty(\"time_read\")]\n public int TimeRead { get; set; }\n\n [JsonProperty(\"recent_time_read\")]\n public int RecentTimeRead { get; set; }\n\n [JsonProperty(\"bookmark_count\")]\n public int BookmarkCount { get; set; }\n\n [JsonProperty(\"can_see_summary_stats\")]\n public bool CanSeeSummaryStats { get; set; }\n\n [JsonProperty(\"solved_count\")]\n public int SolvedCount { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs\n\/\/ private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n\/\/ private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n\/\/ private readonly IHttpClientFactory _httpClientFactory;\n\/\/ public ForumDataProvider(IHttpClientFactory httpClientFactory)\n\/\/ {\n\/\/ _httpClientFactory = httpClientFactory;\n\/\/ }\n\/\/ private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n\/\/ {\n\/\/ using HttpClient client = _httpClientFactory.CreateClient();\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs\n\/\/ public string Username { get; set; }\n\/\/ [JsonProperty(\"name\")]\n\/\/ public string Name { get; set; }\n\/\/ [JsonProperty(\"avatar_template\")]\n\/\/ public string AvatarTemplate { get; set; }\n\/\/ [JsonProperty(\"flair_name\")]\n\/\/ public object FlairName { get; set; }\n\/\/ [JsonProperty(\"trust_level\")]\n\/\/ public int TrustLevel { get; set; }\n\/\/ [JsonProperty(\"admin\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs\n\/\/ using DotNetDevBadgeWeb.Model;\n\/\/ namespace DotNetDevBadgeWeb.Interfaces\n\/\/ {\n\/\/ public interface IProvider\n\/\/ {\n\/\/ Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n\/\/ Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n\/\/ Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs\n\/\/ private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n\/\/ private readonly IProvider _forumProvider;\n\/\/ private readonly IMeasureTextV1 _measureTextV1;\n\/\/ public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n\/\/ {\n\/\/ _forumProvider = forumProvider;\n\/\/ _measureTextV1 = measureTextV1;\n\/\/ }\n\/\/ public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs\n\/\/ {\n\/\/ app.UseMiddleware();\n\/\/ app.MapBadgeEndpointsV1();\n\/\/ return app;\n\/\/ }\n\/\/ internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n\/\/ {\n\/\/ app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n\/\/ {\n\/\/ string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" private const string BADGE_URL = \"https:\/\/forum.dotnetdev.kr\/user-badges\/{0}.json?grouped=true\";\n private const string SUMMARY_URL = \"https:\/\/forum.dotnetdev.kr\/u\/{0}\/summary.json\";\n private readonly IHttpClientFactory _httpClientFactory;\n public ForumDataProvider(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n private async Task GetResponseStringAsync(Uri uri, CancellationToken token)\n {\n using HttpClient client = _httpClientFactory.CreateClient();","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Provider\/ForumDataProvider.cs","score":20.9984816419},{"retrieved_chunk":" public string Username { get; set; }\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n [JsonProperty(\"avatar_template\")]\n public string AvatarTemplate { get; set; }\n [JsonProperty(\"flair_name\")]\n public object FlairName { get; set; }\n [JsonProperty(\"trust_level\")]\n public int TrustLevel { get; set; }\n [JsonProperty(\"admin\")]","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/User.cs","score":20.7334672994},{"retrieved_chunk":"using DotNetDevBadgeWeb.Model;\nnamespace DotNetDevBadgeWeb.Interfaces\n{\n public interface IProvider\n {\n Task<(UserSummary summary, User user)> GetUserInfoAsync(string id, CancellationToken token);\n Task<(byte[] avatar, UserSummary summary, User user)> GetUserInfoWithAvatarAsync(string id, CancellationToken token);\n Task<(int gold, int silver, int bronze)> GetBadgeCountAsync(string id, CancellationToken token);\n }\n}","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Interfaces\/IProvider.cs","score":12.0881992071},{"retrieved_chunk":" private const float TEXT_MAX_WIDTH = LOGO_X - TEXT_X - 10;\n private readonly IProvider _forumProvider;\n private readonly IMeasureTextV1 _measureTextV1;\n public BadgeCreatorV1(IProvider forumProvider, IMeasureTextV1 measureTextV1)\n {\n _forumProvider = forumProvider;\n _measureTextV1 = measureTextV1;\n }\n public async Task GetSmallBadge(string id, ETheme theme, CancellationToken token)\n {","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Core\/Badge\/BadgeCreatorV1.cs","score":10.7385536239},{"retrieved_chunk":" {\n app.UseMiddleware();\n app.MapBadgeEndpointsV1();\n return app;\n }\n internal static WebApplication MapBadgeEndpointsV1(this WebApplication app)\n {\n app.MapGet(\"\/api\/v1\/badge\/small\", async (HttpContext context, [FromQuery] string id, [FromQuery] ETheme? theme, IBadgeV1 badge, CancellationToken token) =>\n {\n string response = await badge.GetSmallBadge(id, theme ?? ETheme.Light, token);","filename":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Endpoints\/Badge\/BadgeEndpoints.cs","score":7.9980978179}],"metadata.task_id":"project_cc_csharp\/48","metadata.repository":"chanos-dev-dotnetdev-badge-5740a40","metadata.file":"src\/dotnetdev-badge\/dotnetdev-badge.web\/Model\/UserSummary.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"JsonProperty(\"user_id\")]\n public int UserId { get; set; }","prediction_status":"success"} {"language":"csharp","groundtruth":"JXLWorkbookData> WorkbooksData {","segments.prefix":"using System.Collections.Generic;\n\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLDataExtracted\n {\n public List<","segments.suffix":" get; set; } = new List();\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs\n\/\/ {\n\/\/ public List Workbooks { get; set; } = new List();\n\/\/ public int SearchLimitRow { get; set; }\n\/\/ public int SearchLimitColumn { get; set; }\n\/\/ public List WorksheetIndexes { get; set; } = new List();\n\/\/ public List Worksheets { get; set; } = new List();\n\/\/ public bool ReadAllWorksheets { get; set; }\n\/\/ public List HeadersToSearch { get; set; } = new List();\n\/\/ public DataTable GetDataTable()\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs\n\/\/ public class DataTableExtractor :\n\/\/ IDataTableExtractorConfiguration,\n\/\/ IDataTableExtractorWorkbookConfiguration,\n\/\/ IDataTableExtractorSearchConfiguration,\n\/\/ IDataTableExtractorWorksheetConfiguration\n\/\/ {\n\/\/ private bool _readAllWorksheets;\n\/\/ private int _searchLimitRow;\n\/\/ private int _searchLimitColumn;\n\/\/ private readonly List _workbooks = new List();\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLWorksheetData\n\/\/ {\n\/\/ public string WorksheetName { get; set; } = string.Empty;\n\/\/ public List Rows { get; set; } = new List();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs\n\/\/ using System.Collections.Generic;\n\/\/ namespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n\/\/ {\n\/\/ public class JXLExtractedRow\n\/\/ {\n\/\/ public Dictionary Columns { get; set; } = new Dictionary();\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetWorkbooksData();\n\/\/ \/\/\/ \n\/\/ \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/returns>\n\/\/ \/\/\/ \n\/\/ List GetExtractedRows();\n\/\/ \/\/\/ \n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n public List Workbooks { get; set; } = new List();\n public int SearchLimitRow { get; set; }\n public int SearchLimitColumn { get; set; }\n public List WorksheetIndexes { get; set; } = new List();\n public List Worksheets { get; set; } = new List();\n public bool ReadAllWorksheets { get; set; }\n public List HeadersToSearch { get; set; } = new List();\n public DataTable GetDataTable()\n {","filename":"JdeJabali.JXLDataTableExtractor\/DataExtraction\/DataReader.cs","score":21.8803902387},{"retrieved_chunk":" public class DataTableExtractor :\n IDataTableExtractorConfiguration,\n IDataTableExtractorWorkbookConfiguration,\n IDataTableExtractorSearchConfiguration,\n IDataTableExtractorWorksheetConfiguration\n {\n private bool _readAllWorksheets;\n private int _searchLimitRow;\n private int _searchLimitColumn;\n private readonly List _workbooks = new List();","filename":"JdeJabali.JXLDataTableExtractor\/DataTableExtractor.cs","score":20.5971282486},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLWorksheetData\n {\n public string WorksheetName { get; set; } = string.Empty;\n public List Rows { get; set; } = new List();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLWorksheetData.cs","score":20.4405637372},{"retrieved_chunk":"using System.Collections.Generic;\nnamespace JdeJabali.JXLDataTableExtractor.JXLExtractedData\n{\n public class JXLExtractedRow\n {\n public Dictionary Columns { get; set; } = new Dictionary();\n }\n}","filename":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLExtractedRow.cs","score":20.1742784403},{"retrieved_chunk":" \/\/\/ <\/returns>\n \/\/\/ \n List GetWorkbooksData();\n \/\/\/ \n \/\/\/ Only retrieves the extracted rows from all the workbooks and worksheets.\n \/\/\/ <\/summary>\n \/\/\/ <\/returns>\n \/\/\/ \n List GetExtractedRows();\n \/\/\/ ","filename":"JdeJabali.JXLDataTableExtractor\/Configuration\/IDataExtraction.cs","score":19.0284015838}],"metadata.task_id":"project_cc_csharp\/50","metadata.repository":"JdeJabali-JXLDataTableExtractor-90a12f4","metadata.file":"JdeJabali.JXLDataTableExtractor\/JXLExtractedData\/JXLDataExtracted.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":7,"prediction":"JXLWorkbookData> Workbooks {","prediction_status":"success"} {"language":"csharp","groundtruth":"WebSocketHub webSocketHub, Func acceptIf, Func keyGenerator)\n {","segments.prefix":"using System.Net.WebSockets;\nusing System.Text;\nusing Microsoft.AspNetCore.Http;\nusing Newtonsoft.Json;\n\nnamespace TraTech.WebSocketHub\n{\n public class WebSocketHubMiddleware\n where TKey : notnull\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly RequestDelegate _next;\n private readonly Func _acceptIf;\n private readonly WebSocketHub _webSocketHub;\n private readonly Func _keyGenerator;\n private readonly byte[] _receiveBuffer;\n\n public WebSocketHubMiddleware(IServiceProvider serviceProvider, RequestDelegate next, ","segments.suffix":"\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _next = next ?? throw new ArgumentNullException(nameof(next));\n _acceptIf = acceptIf ?? throw new ArgumentNullException(nameof(acceptIf));\n _webSocketHub = webSocketHub ?? throw new ArgumentNullException(nameof(webSocketHub));\n _keyGenerator = keyGenerator ?? throw new ArgumentNullException(nameof(keyGenerator));\n _receiveBuffer = new byte[_webSocketHub.Options.ReceiveBufferSize];\n }\n\n public async Task Invoke(HttpContext httpContext)\n {\n\n if (httpContext.WebSockets.IsWebSocketRequest && _acceptIf(httpContext))\n {\n try\n {\n WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();\n\n var key = _keyGenerator(httpContext);\n _webSocketHub.Add(key, webSocket);\n\n while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.CloseSent)\n {\n try\n {\n WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment(_receiveBuffer), CancellationToken.None);\n string request = Encoding.UTF8.GetString(_receiveBuffer, 0, result.Count);\n\n if (result.MessageType == WebSocketMessageType.Close)\n {\n break;\n }\n\n Message? serializedRequest = _webSocketHub.DeserializeMessage(request);\n if (serializedRequest == null) { throw new NullReferenceException(nameof(serializedRequest)); }\n\n Type? handlerType = await _webSocketHub.Options.WebSocketRequestHandler.GetHandlerAsync(serializedRequest.Type);\n if (handlerType == null) { throw new NullReferenceException(nameof(handlerType)); }\n\n if (_serviceProvider.GetService(handlerType) is not IWebSocketRequestHandler service) { throw new NullReferenceException(nameof(service)); }\n\n await service.HandleRequestAsync(\n JsonConvert.SerializeObject(key, _webSocketHub.Options.JsonSerializerSettings),\n JsonConvert.SerializeObject(serializedRequest.Payload, _webSocketHub.Options.JsonSerializerSettings)\n );\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n continue;\n }\n }\n\n await _webSocketHub.RemoveAsync(key, webSocket);\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp.ToString());\n }\n }\n else\n {\n await _next(httpContext);\n }\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs\n\/\/ public WebSocket2Controller(WebSocketHub webSocketHub)\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\/\/ public IActionResult GetSocketListWithSelector(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs\n\/\/ {\n\/\/ _webSocketHub = webSocketHub;\n\/\/ }\n\/\/ [HttpGet(\"GetSocketList\")]\n\/\/ public IActionResult GetSocketList(int id)\n\/\/ {\n\/\/ var socketListOfUser = _webSocketHub.GetSocketList(id);\n\/\/ return Ok(socketListOfUser);\n\/\/ }\n\/\/ [HttpGet(\"GetSocketListWithSelector\")]\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs\n\/\/ \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n\/\/ \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n\/\/ \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n\/\/ \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n\/\/ \/\/\/ <\/remarks>\n\/\/ public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ public WebSocketHub(IOptions options)\n\/\/ {\n\/\/ if (options == null) throw new ArgumentNullException(nameof(options));\n\/\/ Options = options.Value;\n\/\/ _webSocketDictionary = new();\n\/\/ }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The Message object to encode.<\/param>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/WebSocketHub\/Core\/src\/WebSocketHub.cs\n\/\/ private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n\/\/ public WebSocketHubOptions Options { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ The options to configure the WebSocketHub.<\/param>\n\/\/ \/\/\/ Thrown when is null.<\/exception>\n\/\/ \/\/\/ \n\/\/ \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n\/\/ \/\/\/ <\/remarks>\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public WebSocket2Controller(WebSocketHub webSocketHub)\n {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketListWithSelector\")]\n public IActionResult GetSocketListWithSelector(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList((key) => key.Id == id);\n return Ok(socketListOfUser);\n }","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket2Controller.cs","score":45.1993526742},{"retrieved_chunk":" {\n _webSocketHub = webSocketHub;\n }\n [HttpGet(\"GetSocketList\")]\n public IActionResult GetSocketList(int id)\n {\n var socketListOfUser = _webSocketHub.GetSocketList(id);\n return Ok(socketListOfUser);\n }\n [HttpGet(\"GetSocketListWithSelector\")]","filename":"src\/ExampleWebApplication\/Controllers\/WebSocket1Controller.cs","score":45.0233319814},{"retrieved_chunk":" \/\/\/ Attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map.\n \/\/\/ <\/summary>\n \/\/\/ The type of WebSocket request handler to add.<\/typeparam>\n \/\/\/ The message type associated with the WebSocket request handler.<\/param>\n \/\/\/ true if the WebSocket request handler was added to the handler type map; otherwise, false.<\/returns>\n \/\/\/ Thrown when is not assignable from IWebSocketRequestHandler.<\/exception>\n \/\/\/ \n \/\/\/ This method attempts to add a WebSocket request handler of type THandler for the specified message type to the handler type map. The THandler type must implement the IWebSocketRequestHandler interface and have a public constructor. If the message type is already associated with a WebSocket request handler type, this method returns false. Otherwise, it adds the message type and WebSocket request handler type to the handler type map and returns true.\n \/\/\/ <\/remarks>\n public bool TryAddHandler<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>(string messageType)","filename":"src\/WebSocketHub\/Core\/src\/WebSocketRequestHandlerProvider.cs","score":38.9848761059},{"retrieved_chunk":" public WebSocketHub(IOptions options)\n {\n if (options == null) throw new ArgumentNullException(nameof(options));\n Options = options.Value;\n _webSocketDictionary = new();\n }\n \/\/\/ \n \/\/\/ Encodes the specified Message object into a UTF-8 encoded byte array.\n \/\/\/ <\/summary>\n \/\/\/ The Message object to encode.<\/param>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":37.9868121152},{"retrieved_chunk":" private static readonly Func _openSocketSelector = socket => socket.State == WebSocketState.Open;\n public WebSocketHubOptions Options { get; private set; }\n \/\/\/ \n \/\/\/ Initializes a new instance of the WebSocketHub class with the specified options.\n \/\/\/ <\/summary>\n \/\/\/ The options to configure the WebSocketHub.<\/param>\n \/\/\/ Thrown when is null.<\/exception>\n \/\/\/ \n \/\/\/ This constructor initializes a new instance of the WebSocketHub class with the specified options. It also initializes an empty WebSocket dictionary.\n \/\/\/ <\/remarks>","filename":"src\/WebSocketHub\/Core\/src\/WebSocketHub.cs","score":31.7165158873}],"metadata.task_id":"project_cc_csharp\/68","metadata.repository":"TRA-Tech-dotnet-websocket-9049854","metadata.file":"src\/WebSocketHub\/Core\/src\/WebSocketHubMiddleware.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":17,"metadata.right_context_start_lineno":19,"prediction":"Func acceptIf, WebSocketHub webSocketHub, Func keyGenerator)\n {","prediction_status":"success"} -{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n var module = new XboxModule();\n module.Name = line.Substring(0, line.IndexOf(' '));\n module.Base = ulong.Parse(line.Substring(line.IndexOf(' ') + 1, 8), NumberStyles.HexNumber);\n module.Size = ulong.Parse(line.Substring(line.IndexOf(' ', line.IndexOf(' ') + 1) + 1, 8), NumberStyles.HexNumber);\n modules.Add(module);\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Thread> Threads => GetThreads();","segments.prefix":"using System.Text;\nusing System.Net;\nusing Microsoft.Extensions.Caching.Memory;\nusing Serilog;\nusing Serilog.Events;\nusing Iced.Intel;\nusing static Iced.Intel.AssemblerRegisters;\n\nnamespace OGXbdmDumper\n{\n public class Xbox : IDisposable\n {\n #region Properties\n\n private bool _disposed;\n\n private const int _cacheDuration = 1; \/\/ in minutes\n\n private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(_cacheDuration) });\n\n private bool? _hasFastGetmem;\n\n public ScratchBuffer StaticScratch;\n\n public bool HasFastGetmem\n {\n get\n {\n if (_hasFastGetmem == null)\n {\n try\n {\n long testAddress = 0x10000;\n if (IsValidAddress(testAddress))\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length=1\", testAddress.ToHexString());\n Session.ClearReceiveBuffer();\n _hasFastGetmem = true;\n Log.Information(\"Fast getmem support detected.\");\n } \n else _hasFastGetmem = false;\n }\n catch\n {\n _hasFastGetmem = false;\n }\n }\n return _hasFastGetmem.Value;\n }\n }\n\n \/\/\/ \n \/\/\/ Determines whether precautions (usually at the expense of performance) should be taken to prevent crashing the xbox.\n \/\/\/ <\/summary>\n public bool SafeMode { get; set; } = true;\n\n public bool IsConnected => Session.IsConnected;\n\n public int SendTimeout { get => Session.SendTimeout; set => Session.SendTimeout = value; }\n\n public int ReceiveTimeout { get => Session.ReceiveTimeout; set => Session.ReceiveTimeout = value; }\n\n public Connection Session { get; private set; } = new Connection();\n\n public ConnectionInfo? ConnectionInfo { get; protected set; }\n\n \/\/\/ \n \/\/\/ The Xbox memory stream.\n \/\/\/ <\/summary>\n public XboxMemoryStream Memory { get; private set; }\n\n public Kernel Kernel { get; private set; }\n\n public List Modules => GetModules();\n\n public List<","segments.suffix":"\n\n public Version Version => GetVersion();\n\n #endregion\n\n #region Connection\n\n public void Connect(string host, int port = 731)\n {\n _cache.Clear();\n ConnectionInfo = Session.Connect(host, port);\n\n \/\/ init subsystems\n Memory = new XboxMemoryStream(this);\n Kernel = new Kernel(this);\n StaticScratch = new ScratchBuffer(this);\n\n Log.Information(\"Loaded Modules:\");\n foreach (var module in Modules)\n {\n Log.Information(\"\\t{0} ({1})\", module.Name, module.TimeStamp);\n }\n\n Log.Information(\"Xbdm Version {0}\", Version);\n Log.Information(\"Kernel Version {0}\", Kernel.Version);\n\n \/\/ enable remote code execution and use the remainder reloc section as scratch\n PatchXbdm(this);\n }\n\n public void Disconnect()\n {\n Session.Disconnect();\n ConnectionInfo = null;\n _cache.Clear();\n }\n\n public List Discover(int timeout = 500)\n {\n return ConnectionInfo.DiscoverXbdm(731, timeout);\n }\n\n public void Connect(IPEndPoint endpoint)\n {\n Connect(endpoint.Address.ToString(), endpoint.Port);\n }\n\n public void Connect(int timeout = 500)\n {\n Connect(Discover(timeout).First().Endpoint);\n }\n\n #endregion\n\n #region Memory\n\n public bool IsValidAddress(long address)\n {\n try\n {\n Session.SendCommandStrict(\"getmem addr={0} length=1\", address.ToHexString());\n return \"??\" != Session.ReceiveMultilineResponse()[0];\n }\n catch\n {\n return false;\n }\n }\n\n public void ReadMemory(long address, Span buffer)\n {\n if (HasFastGetmem && !SafeMode)\n {\n Session.SendCommandStrict(\"getmem2 addr={0} length={1}\", address.ToHexString(), buffer.Length);\n Session.Read(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else if (!SafeMode)\n {\n \/\/ custom getmem2\n Session.SendCommandStrict(\"funccall type=1 addr={0} length={1}\", address, buffer.Length);\n Session.ReadExactly(buffer);\n if (Log.IsEnabled(LogEventLevel.Verbose))\n {\n Log.Verbose(buffer.ToHexString());\n }\n }\n else\n {\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", address.ToHexString(), buffer.Length);\n\n int bytesRead = 0;\n string hexString;\n while ((hexString = Session.ReceiveLine()) != \".\")\n {\n Span slice = buffer.Slice(bytesRead, hexString.Length \/ 2);\n slice.FromHexString(hexString);\n bytesRead += slice.Length;\n }\n }\n }\n\n public void ReadMemory(long address, byte[] buffer, int offset, int count)\n {\n ReadMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void ReadMemory(long address, int count, Stream destination)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (destination == null) throw new ArgumentNullException(nameof(destination));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesToRead = Math.Min(buffer.Length, count);\n\n Span slice = buffer.Slice(0, bytesToRead);\n ReadMemory(address, slice);\n destination.Write(slice);\n\n count -= bytesToRead;\n address += (uint)bytesToRead;\n }\n }\n\n public void WriteMemory(long address, ReadOnlySpan buffer)\n {\n const int maxBytesPerLine = 240;\n int totalWritten = 0;\n\n while (totalWritten < buffer.Length)\n {\n ReadOnlySpan slice = buffer.Slice(totalWritten, Math.Min(maxBytesPerLine, buffer.Length - totalWritten));\n Session.SendCommandStrict(\"setmem addr={0} data={1}\", (address + totalWritten).ToHexString(), slice.ToHexString());\n totalWritten += slice.Length;\n }\n }\n\n public void WriteMemory(long address, byte[] buffer, int offset, int count)\n {\n WriteMemory(address, buffer.AsSpan(offset, count));\n }\n\n public void WriteMemory(long address, int count, Stream source)\n {\n \/\/ argument checks\n if (address < 0) throw new ArgumentOutOfRangeException(nameof(address));\n if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n Span buffer = stackalloc byte[1024 * 80];\n\n while (count > 0)\n {\n int bytesRead = source.Read(buffer.Slice(0, Math.Min(buffer.Length, count)));\n WriteMemory(address, buffer.Slice(0, bytesRead));\n\n count -= bytesRead;\n address += bytesRead;\n }\n }\n\n #endregion\n\n #region Process\n\n public List GetThreads()\n {\n List threads = new List();\n\n Session.SendCommandStrict(\"threads\");\n foreach (var threadId in Session.ReceiveMultilineResponse())\n {\n Session.SendCommandStrict(\"threadinfo thread={0}\", threadId);\n var info = Connection.ParseKvpResponse(string.Join(Environment.NewLine, Session.ReceiveMultilineResponse()));\n\n threads.Add(new Thread\n {\n Id = Convert.ToInt32(threadId),\n Suspend = (int)(uint)info[\"suspend\"], \/\/ initially -1 in earlier xbdm versions, 0 in later ones\n Priority = (int)(uint)info[\"priority\"],\n TlsBase = (uint)info[\"tlsbase\"],\n\n \/\/ optional depending on xbdm version\n Start = info.ContainsKey(\"start\") ? (uint)info[\"start\"] : 0,\n Base = info.ContainsKey(\"base\") ? (uint)info[\"base\"] : 0,\n Limit = info.ContainsKey(\"limit\") ? (uint)info[\"limit\"] : 0,\n CreationTime = DateTime.FromFileTime(\n (info.ContainsKey(\"createhi\") ? (((long)(uint)info[\"createhi\"]) << 32) : 0) |\n (info.ContainsKey(\"createlo\") ? (uint)info[\"createlo\"] : 0))\n });\n }\n\n return threads;\n }\n\n public List GetModules()\n {\n List modules = new List();\n\n Session.SendCommandStrict(\"modules\");\n foreach (var moduleResponse in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = Connection.ParseKvpResponse(moduleResponse);\n Module module = new Module\n {\n Name = (string)moduleInfo[\"name\"],\n BaseAddress = (uint)moduleInfo[\"base\"],\n Size = (int)(uint)moduleInfo[\"size\"],\n Checksum = (uint)moduleInfo[\"check\"],\n TimeStamp = DateTimeOffset.FromUnixTimeSeconds((uint)moduleInfo[\"timestamp\"]).DateTime,\n Sections = new List(),\n HasTls = moduleInfo.ContainsKey(\"tls\"),\n IsXbe = moduleInfo.ContainsKey(\"xbe\")\n };\n\n Session.SendCommandStrict(\"modsections name=\\\"{0}\\\"\", module.Name);\n foreach (var sectionResponse in Session.ReceiveMultilineResponse())\n {\n var sectionInfo = Connection.ParseKvpResponse(sectionResponse);\n module.Sections.Add(new ModuleSection\n {\n Name = (string)sectionInfo[\"name\"],\n Base = (uint)sectionInfo[\"base\"],\n Size = (int)(uint)sectionInfo[\"size\"],\n Flags = (uint)sectionInfo[\"flags\"]\n });\n }\n\n modules.Add(module);\n }\n\n return modules;\n }\n\n public Version GetVersion()\n {\n var version = _cache.Get(nameof(GetVersion));\n if (version == null)\n {\n try\n {\n \/\/ peek inside VS_VERSIONINFO struct\n var versionAddress = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".rsrc\").Base + 0x98;\n\n \/\/ call getmem directly to avoid dependency loops with ReadMemory checking the version\n Span buffer = stackalloc byte[sizeof(ushort) * 4];\n Session.SendCommandStrict(\"getmem addr={0} length={1}\", versionAddress.ToHexString(), buffer.Length);\n buffer.FromHexString(Session.ReceiveMultilineResponse().First());\n\n version = new Version(\n BitConverter.ToUInt16(buffer.Slice(2, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(0, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(6, sizeof(ushort))),\n BitConverter.ToUInt16(buffer.Slice(4, sizeof(ushort)))\n );\n\n \/\/ cache the result\n _cache.Set(nameof(GetVersion), version);\n }\n catch\n {\n version = new Version(\"0.0.0.0\");\n }\n }\n\n return version;\n }\n\n public void Stop()\n {\n Log.Information(\"Suspending xbox execution.\");\n Session.SendCommand(\"stop\");\n }\n\n public void Go()\n {\n Log.Information(\"Resuming xbox execution.\");\n Session.SendCommand(\"go\");\n }\n\n \/\/\/ \n \/\/\/ Calls an Xbox function.\n \/\/\/ <\/summary>\n \/\/\/ The function address.<\/param>\n \/\/\/ The function arguments.<\/param>\n \/\/\/ Returns an object that unboxes eax by default, but allows for reading st0 for floating-point return values.<\/returns>\n public uint Call(long address, params object[] args)\n {\n \/\/ TODO: call context (~4039+ which requires qwordparam)\n\n \/\/ injected script pushes arguments in reverse order for simplicity, this corrects that\n var reversedArgs = args.Reverse().ToArray();\n\n StringBuilder command = new StringBuilder();\n command.AppendFormat(\"funccall type=0 addr={0} \", address);\n for (int i = 0; i < reversedArgs.Length; i++)\n {\n command.AppendFormat(\"arg{0}={1} \", i, Convert.ToUInt32(reversedArgs[i]));\n }\n\n var returnValues = Connection.ParseKvpResponse(Session.SendCommandStrict(command.ToString()).Message);\n return (uint)returnValues[\"eax\"];\n }\n\n \/\/\/ \n \/\/\/ Original Xbox Debug Monitor runtime patches.\n \/\/\/ Prevents crashdumps from being written to the HDD and enables remote code execution.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n private void PatchXbdm(Xbox target)\n {\n \/\/ the spin routine to be patched in after the signature patterns\n \/\/ spin:\n \/\/ jmp spin\n \/\/ int 3\n var spinBytes = new byte[] { 0xEB, 0xFE, 0xCC };\n\n \/\/ prevent crashdumps from being written to the hard drive by making it spin instead (only for xbdm versions ~4831+)\n if (target.Signatures.ContainsKey(\"ReadWriteOneSector\"))\n {\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"ReadWriteOneSector\"] + 9, spinBytes);\n }\n else if (target.Signatures.ContainsKey(\"WriteSMBusByte\"))\n {\n \/\/ this will prevent the LED state from changing upon crash\n Log.Information(\"Disabling crashdump functionality.\");\n target.WriteMemory(target.Signatures[\"WriteSMBusByte\"] + 9, spinBytes);\n }\n\n Log.Information(\"Patching xbdm memory to enable remote code execution.\");\n\n uint argThreadStringAddress = StaticScratch.Alloc(\"thread\\0\");\n uint argTypeStringAddress = StaticScratch.Alloc(\"type\\0\");\n uint argAddrStringAddress = StaticScratch.Alloc(\"addr\\0\");\n uint argLengthStringAddress = StaticScratch.Alloc(\"length\\0\");\n uint argFormatStringAddress = StaticScratch.Alloc(\"arg%01d\\0\");\n uint returnFormatAddress = StaticScratch.Alloc(\"eax=0x%X\\0\");\n\n var asm = new Assembler(32);\n\n #region HrSendGetMemory2Data\n\n uint getmem2CallbackAddress = 0;\n if (!HasFastGetmem)\n {\n \/\/ labels\n var label1 = asm.CreateLabel();\n var label2 = asm.CreateLabel();\n var label3 = asm.CreateLabel();\n\n asm.push(ebx);\n asm.mov(ebx, __dword_ptr[esp + 8]); \/\/ pdmcc\n asm.mov(eax, __dword_ptr[ebx + 0x14]); \/\/ size\n asm.test(eax, eax);\n asm.mov(edx, __dword_ptr[ebx + 0x10]);\n asm.ja(label1);\n \/\/asm.push(__dword_ptr[ebx + 8]);\n \/\/asm.call((uint)target.Signatures[\"DmFreePool\"]);\n \/\/asm.and(__dword_ptr[ebx + 8], 0);\n asm.mov(eax, 0x82DB0104);\n asm.jmp(label3);\n\n asm.Label(ref label1);\n asm.mov(ecx, __dword_ptr[ebx + 0xC]); \/\/ buffer size\n asm.cmp(eax, ecx);\n asm.jb(label2);\n asm.mov(eax, ecx);\n\n asm.Label(ref label2);\n asm.push(ebp);\n asm.push(esi);\n asm.mov(esi, __dword_ptr[edx + 0x14]); \/\/ address\n asm.push(edi);\n asm.mov(edi, __dword_ptr[ebx + 8]);\n asm.mov(ecx, eax);\n asm.mov(ebp, ecx);\n asm.shr(ecx, 2);\n asm.rep.movsd();\n asm.mov(ecx, ebp);\n asm.and(ecx, 3);\n asm.rep.movsb();\n asm.sub(__dword_ptr[ebx + 0x14], eax);\n asm.pop(edi);\n asm.mov(__dword_ptr[ebx + 4], eax);\n asm.add(__dword_ptr[edx + 0x14], eax);\n asm.pop(esi);\n asm.mov(eax, 0x2DB0000);\n asm.pop(ebp);\n\n asm.Label(ref label3);\n asm.pop(ebx);\n asm.ret(0xC);\n\n getmem2CallbackAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n }\n\n #endregion\n\n #region HrFunctionCall\n\n \/\/ 3424+ as it depends on sprintf within xbdm, earlier versions can possibly call against the kernel but their exports are different\n asm = new Assembler(32);\n\n \/\/ labels\n var binaryResponseLabel = asm.CreateLabel();\n var getmem2Label = asm.CreateLabel();\n var errorLabel = asm.CreateLabel();\n var successLabel = asm.CreateLabel();\n\n \/\/ prolog\n asm.push(ebp);\n asm.mov(ebp, esp);\n asm.sub(esp, 0x10); \/\/ carve out arbitrary space for local temp variables\n asm.pushad();\n\n \/\/ disable write protection globally, otherwise checked kernel calls may fail when writing to the default scratch space\n asm.mov(eax, cr0);\n asm.and(eax, 0xFFFEFFFF);\n asm.mov(cr0, eax);\n\n \/\/ arguments\n var commandPtr = ebp + 0x8;\n var responseAddress = ebp + 0xC;\n var pdmcc = ebp + 0x14;\n\n \/\/ local variables\n var temp = ebp - 0x4;\n var callAddress = ebp - 0x8;\n var argName = ebp - 0x10;\n\n \/\/ check for thread id\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argThreadStringAddress); \/\/ 'thread', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n var customCommandLabel = asm.CreateLabel();\n asm.je(customCommandLabel);\n\n \/\/ call original code if thread id exists\n asm.push(__dword_ptr[temp]);\n asm.call((uint)target.Signatures[\"DmSetupFunctionCall\"]);\n var doneLabel = asm.CreateLabel();\n asm.jmp(doneLabel);\n\n \/\/ thread argument doesn't exist, must be a custom command\n asm.Label(ref customCommandLabel);\n\n \/\/ determine custom function type\n asm.lea(eax, temp);\n asm.push(eax);\n asm.push(argTypeStringAddress); \/\/ 'type', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(errorLabel);\n\n #region Custom Call (type 0)\n\n asm.cmp(__dword_ptr[temp], 0);\n asm.jne(getmem2Label);\n\n \/\/ get the call address\n asm.lea(eax, __dword_ptr[callAddress]);\n asm.push(eax);\n asm.push(argAddrStringAddress); \/\/ 'addr', 0\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n\n asm.je(errorLabel);\n\n \/\/ push arguments (leave it up to caller to reverse argument order and supply the correct amount)\n asm.xor(edi, edi);\n var nextArgLabel = asm.CreateLabel();\n var noMoreArgsLabel = asm.CreateLabel();\n asm.Label(ref nextArgLabel);\n {\n \/\/ get argument name\n asm.push(edi); \/\/ argument index\n asm.push(argFormatStringAddress); \/\/ format string address\n asm.lea(eax, __dword_ptr[argName]); \/\/ argument name address\n asm.push(eax);\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n\n \/\/ check if it's included in the command\n asm.lea(eax, __[temp]); \/\/ argument value address\n asm.push(eax);\n asm.lea(eax, __[argName]); \/\/ argument name address\n asm.push(eax);\n asm.push(__dword_ptr[commandPtr]); \/\/ command\n asm.call((uint)target.Signatures[\"FGetDwParam\"]);\n asm.test(eax, eax);\n asm.je(noMoreArgsLabel);\n\n \/\/ push it on the stack\n asm.push(__dword_ptr[temp]);\n asm.inc(edi);\n\n \/\/ move on to the next argument\n asm.jmp(nextArgLabel);\n }\n asm.Label(ref noMoreArgsLabel);\n\n \/\/ perform the call\n asm.call(__dword_ptr[callAddress]);\n\n \/\/ print response message\n asm.push(eax); \/\/ integer return value\n asm.push(returnFormatAddress); \/\/ format string address\n asm.push(__dword_ptr[responseAddress]); \/\/ response address\n asm.call((uint)target.Signatures[\"sprintf\"]);\n asm.add(esp, 0xC);\n asm.jmp(successLabel);\n\n #endregion\n\n #region Fast Getmem (type 1)\n\n asm.Label(ref getmem2Label);\n asm.cmp(__dword_ptr[temp], 1);\n asm.jne(errorLabel);\n \n if (!HasFastGetmem)\n {\n \/\/ TODO: figure out why DmAllocatePool crashes, for now, allocate static scratch space (prevents multi-session!)\n StaticScratch.Align16();\n uint getmem2BufferSize = 512;\n uint getmem2buffer = StaticScratch.Alloc(new byte[getmem2BufferSize]);\n\n \/\/ get length and size args\n asm.mov(esi, __dword_ptr[pdmcc]);\n asm.push(__dword_ptr[responseAddress]);\n asm.mov(edi, __dword_ptr[esi + 0x10]);\n asm.lea(eax, __dword_ptr[pdmcc]);\n asm.push(eax);\n asm.push(argAddrStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n asm.push(__dword_ptr[responseAddress]);\n asm.lea(eax, __dword_ptr[responseAddress]);\n asm.push(eax);\n asm.push(argLengthStringAddress);\n asm.push(__dword_ptr[commandPtr]);\n asm.call((uint)target.Signatures[\"FGetNamedDwParam\"]);\n asm.test(eax, eax);\n asm.jz(errorLabel);\n\n asm.mov(eax, __dword_ptr[pdmcc]); \/\/ address\n asm.and(__dword_ptr[edi + 0x10], 0);\n asm.mov(__dword_ptr[edi + 0x14], eax);\n \/\/asm.mov(eax, 0x2000); \/\/ TODO: increase pool size?\n \/\/asm.push(eax);\n \/\/asm.call((uint)target.Signatures[\"DmAllocatePool\"]); \/\/ TODO: crashes in here, possible IRQ issues?\n asm.mov(__dword_ptr[esi + 0xC], getmem2BufferSize); \/\/ buffer size\n asm.mov(__dword_ptr[esi + 8], getmem2buffer); \/\/ buffer address\n asm.mov(eax, __dword_ptr[responseAddress]);\n asm.mov(__dword_ptr[esi + 0x14], eax);\n asm.mov(__dword_ptr[esi], getmem2CallbackAddress);\n asm.jmp(binaryResponseLabel);\n }\n\n #endregion\n\n #region Return Codes\n\n \/\/ if we're here, must be an unknown custom type\n asm.jmp(errorLabel);\n\n \/\/ generic success epilog\n asm.Label(ref successLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0000);\n asm.ret(0x10);\n\n \/\/ successful binary response follows epilog\n asm.Label(ref binaryResponseLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x2DB0003);\n asm.ret(0x10);\n\n \/\/ generic failure epilog\n asm.Label(ref errorLabel);\n asm.popad();\n asm.leave();\n asm.mov(eax, 0x82DB0000);\n asm.ret(0x10);\n\n \/\/ original epilog\n asm.Label(ref doneLabel);\n asm.popad();\n asm.leave();\n asm.ret(0x10);\n\n #endregion\n\n \/\/ inject RPC handler and hook\n uint caveAddress = StaticScratch.Alloc(asm.AssembleBytes(StaticScratch.Region.Address));\n Log.Information(\"HrFuncCall address {0}\", caveAddress.ToHexString());\n asm.Hook(target, target.Signatures[\"HrFunctionCall\"], caveAddress);\n \n #endregion\n }\n\n public string GetDisassembly(long address, int length, bool tabPrefix = true, bool showBytes = false)\n {\n \/\/ read code from xbox memory\n byte[] code = Memory.ReadBytes(address, length);\n\n \/\/ disassemble valid instructions\n var decoder = Iced.Intel.Decoder.Create(32, code);\n decoder.IP = (ulong)address;\n var instructions = new List();\n while (decoder.IP < decoder.IP + (uint)code.Length)\n {\n var insn = decoder.Decode();\n if (insn.IsInvalid)\n break;\n instructions.Add(insn);\n }\n\n \/\/ formatting options\n var formatter = new MasmFormatter();\n formatter.Options.FirstOperandCharIndex = 8;\n formatter.Options.SpaceAfterOperandSeparator = true;\n\n \/\/ convert to string\n var output = new StringOutput();\n var disassembly = new StringBuilder();\n bool firstInstruction = true;\n foreach (var instr in instructions)\n {\n \/\/ skip newline for the first instruction\n if (firstInstruction)\n {\n firstInstruction = false;\n } else disassembly.AppendLine();\n\n \/\/ optionally indent\n if (tabPrefix)\n {\n disassembly.Append('\\t');\n }\n\n \/\/ output address\n disassembly.Append(instr.IP.ToString(\"X8\"));\n disassembly.Append(' ');\n\n \/\/ optionally output instruction bytes\n if (showBytes)\n {\n for (int i = 0; i < instr.Length; i++)\n disassembly.Append(code[(int)(instr.IP - (ulong)address) + i].ToString(\"X2\"));\n int missingBytes = 10 - instr.Length;\n for (int i = 0; i < missingBytes; i++)\n disassembly.Append(\" \");\n disassembly.Append(' ');\n }\n\n \/\/ output the decoded instruction\n formatter.Format(instr, output);\n disassembly.Append(output.ToStringAndReset());\n }\n \n return disassembly.ToString();\n }\n\n public Dictionary Signatures\n {\n get\n {\n var signatures = _cache.Get>(nameof(Signatures));\n if (signatures == null)\n {\n var resolver = new SignatureResolver\n {\n \/\/ NOTE: ensure patterns don't overlap with any hooks! that way we don't have to cache any states; simplicity at the expense of slightly less perf on connect\n\n \/\/ universal pattern\n new SodmaSignature(\"ReadWriteOneSector\")\n { \n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ mov dx, 1F6h\n new OdmPattern(0x3, new byte[] { 0x66, 0xBA, 0xF6, 0x01 }),\n\n \/\/ mov al, 0A0h\n new OdmPattern(0x7, new byte[] { 0xB0, 0xA0 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"WriteSMBusByte\")\n { \n \/\/ mov al, 20h\n new OdmPattern(0x3, new byte[] { 0xB0, 0x20 }),\n\n \/\/ mov dx, 0C004h\n new OdmPattern(0x5, new byte[] { 0x66, 0xBA, 0x04, 0xC0 }),\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetDwParam\")\n { \n \/\/ jz short 0x2C\n new OdmPattern(0x15, new byte[] { 0x74, 0x2C }),\n\n \/\/ push 20h\n new OdmPattern(0x17, new byte[] { 0x6A, 0x20 }),\n\n \/\/ mov [ecx], eax\n new OdmPattern(0x33, new byte[] { 0x89, 0x01 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"FGetNamedDwParam\")\n {\n \/\/ mov ebp, esp\n new OdmPattern(0x1, new byte[] { 0x8B, 0xEC }),\n\n \/\/ jnz short 0x17\n new OdmPattern(0x13, new byte[] { 0x75, 0x17 }),\n\n \/\/ retn 10h\n new OdmPattern(0x30, new byte[] { 0xC2, 0x10, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmSetupFunctionCall\")\n {\n \/\/ test ax, 280h\n new OdmPattern(0x45, new byte[] { 0x66, 0xA9, 0x80, 0x02 }),\n\n \/\/ push 63666D64h\n new OdmPattern(0x54, new byte[] { 0x68, 0x64, 0x6D, 0x66, 0x63 })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x46, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"HrFunctionCall\")\n {\n \/\/ mov eax, 80004005h\n new OdmPattern(0x1B, new byte[] { 0xB8, 0x05, 0x40, 0x00, 0x80 }),\n\n \/\/ mov ebx, 10008h\n new OdmPattern(0x45, new byte[] { 0xBB, 0x08, 0x00, 0x01, 0x00 })\n },\n\n \/\/ xbdm 3424+ contains this (3223 does not, who knows what inbetween does) whereas some early kernel versions do not? or have different kernel export tables for alpha\/dvt3\/dvt4\/dvt6 etc.\n new SodmaSignature(\"sprintf\")\n {\n \/\/ mov esi, [ebp+arg_0]\n new OdmPattern(0x7, new byte[] { 0x8B, 0x75, 0x08 }),\n \n \/\/ mov [ebp+var_1C], 7FFFFFFFh\n new OdmPattern(0x16, new byte[] { 0xC7, 0x45, 0xE4, 0xFF, 0xFF, 0xFF, 0x7F })\n },\n\n \/\/ early revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push ebp\n new OdmPattern(0x0, new byte[] { 0x55 }),\n\n \/\/ mov ebp, esp\n new OdmPattern(0x0, new byte[] { 0x8B, 0xEC }),\n\n \/\/ push 'enoN'\n new OdmPattern(0x3, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 })\n },\n\n \/\/ later revisions\n new SodmaSignature(\"DmAllocatePool\")\n {\n \/\/ push 'enoN'\n new OdmPattern(0x0, new byte[] { 0x68, 0x4E, 0x6F, 0x6E, 0x65 }),\n\n \/\/ retn 4\n new OdmPattern(0xE, new byte[] { 0xC2, 0x04, 0x00 })\n },\n\n \/\/ universal pattern\n new SodmaSignature(\"DmFreePool\")\n {\n \/\/ cmp eax, 0B0000000h\n new OdmPattern(0xF, new byte[] { 0x3D, 0x00, 0x00, 0x00, 0xB0 })\n }\n };\n\n \/\/ read xbdm .text section\n var xbdmTextSegment = GetModules().FirstOrDefault(m => m.Name.Equals(\"xbdm.dll\")).GetSection(\".text\");\n byte[] data = new byte[xbdmTextSegment.Size];\n ReadMemory(xbdmTextSegment.Base, data);\n\n \/\/ scan for signatures\n signatures = resolver.Resolve(data, xbdmTextSegment.Base);\n\n \/\/ cache the result indefinitely\n _cache.Set(nameof(Signatures), signatures);\n }\n\n return signatures;\n }\n }\n\n #endregion\n\n #region File\n\n public char[] GetDrives()\n {\n return Session.SendCommandStrict(\"drivelist\").Message.ToCharArray();\n }\n\n public List GetDirectoryList(string path)\n {\n var list = new List();\n Session.SendCommandStrict(\"dirlist name=\\\"{0}\\\"\", path);\n foreach (string file in Session.ReceiveMultilineResponse())\n {\n var fileInfo = file.ParseXboxResponseLine();\n var info = new XboxFileInformation();\n info.FullName = Path.Combine(path, (string)fileInfo[\"name\"]);\n info.Size = ((long)fileInfo[\"sizehi\"] << 32) | (long)fileInfo[\"sizelo\"];\n info.CreationTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"createhi\"] << 32) | (long)fileInfo[\"createlo\"]);\n info.ChangeTime = DateTime.FromFileTimeUtc(((long)fileInfo[\"changehi\"] << 32) | (long)fileInfo[\"changelo\"]);\n info.Attributes |= file.Contains(\"directory\") ? FileAttributes.Directory : FileAttributes.Normal;\n info.Attributes |= file.Contains(\"readonly\") ? FileAttributes.ReadOnly : 0;\n info.Attributes |= file.Contains(\"hidden\") ? FileAttributes.Hidden : 0;\n list.Add(info);\n }\n\n return list; \n }\n\n public void GetFile(string localPath, string remotePath)\n {\n Session.SendCommandStrict(\"getfile name=\\\"{0}\\\"\", remotePath);\n using var lfs = File.Create(localPath);\n Session.CopyToCount(lfs, Session.Reader.ReadInt32());\n }\n\n #endregion\n\n #region IDisposable\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n \/\/ TODO: dispose managed state (managed objects)\n }\n\n \/\/ TODO: free unmanaged resources (unmanaged objects) and override finalizer\n Session?.Dispose();\n\n \/\/ TODO: set large fields to null\n\n _disposed = true;\n }\n }\n\n ~Xbox()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/ConnectionInfo.cs\n\/\/ var connections = new List();\n\/\/ byte[] datagramBuffer = new byte[1024];\n\/\/ \/\/ iterate through each network interface\n\/\/ Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n\/\/ {\n\/\/ \/\/ only worry about active IPv4 interfaces\n\/\/ if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n\/\/ return;\n\/\/ \/\/ iterate through each ip address assigned to the interface\n\/\/ Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes the session.\n\/\/ \/\/\/ <\/summary>\n\/\/ public Connection()\n\/\/ {\n\/\/ \/\/ initialize defaults\n\/\/ Reader = new BinaryReader(this);\n\/\/ Writer = new BinaryWriter(this);\n\/\/ ResetTcp();\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Connection.cs\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n\/\/ \/\/\/ <\/summary>\n\/\/ public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n\/\/ #endregion\n\/\/ #region Construction\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ throw new ArgumentNullException(nameof(xbox));\n\/\/ Module = xbox.Modules.Find(m => m.Name == Name) ??\n\/\/ throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n\/\/ \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n\/\/ \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n\/\/ var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n\/\/ int size = (int)(initSection.Base - Address);\n\/\/ var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n\/\/ \/\/ resolve exports\n\/\/ Exports = new KernelExports(Address, pe.ExportedFunctions);\n\n\/\/ the below code fragment can be found in:\n\/\/ src\/OGXbdmDumper\/Kernel.cs\n\/\/ \/\/\/ The kernel exports.\n\/\/ \/\/\/ <\/summary>\n\/\/ public KernelExports Exports { get; private set; }\n\/\/ \/\/\/ \n\/\/ \/\/\/ Initializes communication with the Xbox kernel.\n\/\/ \/\/\/ <\/summary>\n\/\/ \/\/\/ <\/param>\n\/\/ public Kernel(Xbox xbox)\n\/\/ {\n\/\/ _xbox = xbox ??\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" var connections = new List();\n byte[] datagramBuffer = new byte[1024];\n \/\/ iterate through each network interface\n Parallel.ForEach(NetworkInterface.GetAllNetworkInterfaces(), nic =>\n {\n \/\/ only worry about active IPv4 interfaces\n if (nic.OperationalStatus != OperationalStatus.Up || !nic.Supports(NetworkInterfaceComponent.IPv4))\n return;\n \/\/ iterate through each ip address assigned to the interface\n Parallel.ForEach(nic.GetIPProperties().UnicastAddresses, ip =>","filename":"src\/OGXbdmDumper\/ConnectionInfo.cs","score":66.5516645798},{"retrieved_chunk":" \/\/\/ \n \/\/\/ Initializes the session.\n \/\/\/ <\/summary>\n public Connection()\n {\n \/\/ initialize defaults\n Reader = new BinaryReader(this);\n Writer = new BinaryWriter(this);\n ResetTcp();\n }","filename":"src\/OGXbdmDumper\/Connection.cs","score":65.6148057322},{"retrieved_chunk":" \/\/\/ \n \/\/\/ The time in milliseconds to wait while sending data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int SendTimeout { get => _client.SendTimeout; set => _client.SendTimeout = value; }\n \/\/\/ \n \/\/\/ The time in milliseconds to wait while receiving data before throwing a TimeoutException.\n \/\/\/ <\/summary>\n public int ReceiveTimeout { get => _client.ReceiveTimeout; set => _client.ReceiveTimeout = value; }\n #endregion\n #region Construction","filename":"src\/OGXbdmDumper\/Connection.cs","score":63.1487147285},{"retrieved_chunk":" throw new ArgumentNullException(nameof(xbox));\n Module = xbox.Modules.Find(m => m.Name == Name) ??\n throw new NullReferenceException(string.Format(\"Failed to load {0} module information!\", Name));\n \/\/ TODO: remove 3rd-party dependency with proper PE parsing logic\n \/\/ grab enough of the kernel in memory to allow parsing it (possibly only need through the data section)\n var initSection = Module.Sections.Find(m => m.Name == \"INIT\");\n int size = (int)(initSection.Base - Address);\n var pe = new PeFile(_xbox.Memory.ReadBytes(Address, size));\n \/\/ resolve exports\n Exports = new KernelExports(Address, pe.ExportedFunctions);","filename":"src\/OGXbdmDumper\/Kernel.cs","score":62.6153366094},{"retrieved_chunk":" \/\/\/ The kernel exports.\n \/\/\/ <\/summary>\n public KernelExports Exports { get; private set; }\n \/\/\/ \n \/\/\/ Initializes communication with the Xbox kernel.\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n public Kernel(Xbox xbox)\n {\n _xbox = xbox ??","filename":"src\/OGXbdmDumper\/Kernel.cs","score":60.8857066947}],"metadata.task_id":"project_cc_csharp\/20","metadata.repository":"Ernegien-OGXbdmDumper-07a1e82","metadata.file":"src\/OGXbdmDumper\/Xbox.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":75,"metadata.right_context_start_lineno":76,"prediction":"\n {\n var modules = new List();\n Session.SendCommandStrict(\"modulelist\");\n foreach (string module in Session.ReceiveMultilineResponse())\n {\n var moduleInfo = module.ParseXboxResponseLine();\n var info = new XboxModule();\n info.Name = (string)moduleInfo[\"name\"];\n info.Base = (long)moduleInfo[\"base\"];\n info.Size = (long)moduleInfo[\"size\"];\n modules.Add(info);\n }","prediction_status":"success"} {"language":"csharp","groundtruth":"Ignore]\n public int NoteId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class Note\n {\n [","segments.suffix":" get; set; }\n public string Guid { get; set; } = null!;\n public int? UserMarkId { get; set; }\n public int? LocationId { get; set; }\n public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/JWDal.cs\n\/\/ {\n\/\/ connectionString = $\"Data Source={dbPath}\";\n\/\/ }\n\/\/ public IEnumerable TableList()\n\/\/ {\n\/\/ using (IDbConnection cnn = new SQLiteConnection(connectionString))\n\/\/ {\n\/\/ return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/InputField.cs\n\/\/ using JWLSLMerge.Data.Attributes;\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class InputField\n\/\/ {\n\/\/ public int LocationId { get; set; }\n\/\/ public string TextTag { get; set; } = null!;\n\/\/ public string Value { get; set; } = null!;\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Tag.cs\n\/\/ public int NewTagId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge\/MergeService.cs\n\/\/ private readonly string targetPath = null!;\n\/\/ private readonly string targetDbFile = null!;\n\/\/ private string lastModified = null!;\n\/\/ public MergeService()\n\/\/ {\n\/\/ targetPath = Environment.GetTargetDirectory();\n\/\/ targetDbFile = Environment.GetDbFile();\n\/\/ }\n\/\/ public void Run(string[] jwlibraryFiles)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" {\n connectionString = $\"Data Source={dbPath}\";\n }\n public IEnumerable TableList()\n {\n using (IDbConnection cnn = new SQLiteConnection(connectionString))\n {\n return cnn.Query($\"SELECT * FROM {typeof(T).Name}\");\n }\n }","filename":"JWLSLMerge.Data\/JWDal.cs","score":13.7840150678},{"retrieved_chunk":"using JWLSLMerge.Data.Attributes;\nnamespace JWLSLMerge.Data.Models\n{\n public class InputField\n {\n public int LocationId { get; set; }\n public string TextTag { get; set; } = null!;\n public string Value { get; set; } = null!;\n }\n}","filename":"JWLSLMerge.Data\/Models\/InputField.cs","score":13.0008115476},{"retrieved_chunk":" public int NewTagId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Tag.cs","score":12.8283084644},{"retrieved_chunk":" private readonly string targetPath = null!;\n private readonly string targetDbFile = null!;\n private string lastModified = null!;\n public MergeService()\n {\n targetPath = Environment.GetTargetDirectory();\n targetDbFile = Environment.GetDbFile();\n }\n public void Run(string[] jwlibraryFiles)\n {","filename":"JWLSLMerge\/MergeService.cs","score":12.7793409473},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":12.358601363}],"metadata.task_id":"project_cc_csharp\/51","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/Note.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":6,"metadata.right_context_start_lineno":8,"prediction":"Ignore]\n public int NoteId {","prediction_status":"success"} -{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n {\n throw new Win32Exception();\n }","prediction_status":"success"} -{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public Playlist Playlist {","prediction_status":"success"} +{"language":"csharp","groundtruth":"SafeServiceHandle CreateService(SafeServiceHandle managerHandle, string filePath, ServiceOptions options)\n {","segments.prefix":"using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Threading;\nusing static ServiceSelf.AdvApi32;\n\nnamespace ServiceSelf\n{\n sealed class WindowsService : Service\n {\n private const string WorkingDirArgName = \"WD\";\n\n\n [SupportedOSPlatform(\"windows\")]\n public WindowsService(string name)\n : base(name)\n {\n }\n\n \/\/\/ \n \/\/\/ 应用工作目录\n \/\/\/ <\/summary>\n \/\/\/ 启动参数<\/param>\n \/\/\/ <\/returns>\n public static bool UseWorkingDirectory(string[] args)\n {\n if (Argument.TryGetValue(args, WorkingDirArgName, out var workingDir))\n {\n Environment.CurrentDirectory = workingDir;\n return true;\n }\n return false;\n }\n\n [SupportedOSPlatform(\"windows\")]\n public override void CreateStart(string filePath, ServiceOptions options)\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n filePath = Path.GetFullPath(filePath);\n using var oldServiceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n\n if (oldServiceHandle.IsInvalid)\n {\n using var newServiceHandle = this.CreateService(managerHandle, filePath, options);\n StartService(newServiceHandle);\n }\n else\n {\n var oldFilePath = QueryServiceFilePath(oldServiceHandle);\n if (oldFilePath.Length > 0 && oldFilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase) == false)\n {\n throw new InvalidOperationException(\"系统已存在同名但不同路径的服务\");\n }\n StartService(oldServiceHandle);\n }\n }\n\n private unsafe ","segments.suffix":"\n var arguments = options.Arguments ?? Enumerable.Empty();\n arguments = string.IsNullOrEmpty(options.WorkingDirectory)\n ? arguments.Append(new Argument(WorkingDirArgName, Path.GetDirectoryName(filePath)))\n : arguments.Append(new Argument(WorkingDirArgName, Path.GetFullPath(options.WorkingDirectory)));\n\n var serviceHandle = AdvApi32.CreateService(\n managerHandle,\n this.Name,\n options.Windows.DisplayName,\n ServiceAccess.SERVICE_ALL_ACCESS,\n ServiceType.SERVICE_WIN32_OWN_PROCESS,\n ServiceStartType.SERVICE_AUTO_START,\n ServiceErrorControl.SERVICE_ERROR_NORMAL,\n $@\"\"\"{filePath}\"\" {string.Join(' ', arguments)}\",\n lpLoadOrderGroup: null,\n lpdwTagId: 0,\n lpDependencies: options.Windows.Dependencies,\n lpServiceStartName: options.Windows.ServiceStartName,\n lpPassword: options.Windows.Password);\n\n if (serviceHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n if (string.IsNullOrEmpty(options.Description) == false)\n {\n var desc = new ServiceDescription { lpDescription = options.Description };\n var pDesc = Marshal.AllocHGlobal(Marshal.SizeOf(desc));\n Marshal.StructureToPtr(desc, pDesc, false);\n ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_DESCRIPTION, pDesc.ToPointer());\n Marshal.FreeHGlobal(pDesc);\n }\n\n\n var action = new SC_ACTION\n {\n Type = (SC_ACTION_TYPE)options.Windows.FailureActionType,\n };\n var failureAction = new SERVICE_FAILURE_ACTIONS\n {\n cActions = 1,\n lpsaActions = &action,\n dwResetPeriod = (int)TimeSpan.FromDays(1d).TotalSeconds\n };\n\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n return serviceHandle;\n }\n\n private static ReadOnlySpan QueryServiceFilePath(SafeServiceHandle serviceHandle)\n {\n const int ERROR_INSUFFICIENT_BUFFER = 122;\n if (QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out var bytesNeeded) == false)\n {\n if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)\n {\n throw new Win32Exception();\n }\n }\n\n var buffer = Marshal.AllocHGlobal(bytesNeeded);\n try\n {\n if (QueryServiceConfig(serviceHandle, buffer, bytesNeeded, out _) == false)\n {\n throw new Win32Exception();\n }\n\n var serviceConfig = Marshal.PtrToStructure(buffer);\n var binaryPathName = serviceConfig.lpBinaryPathName.AsSpan();\n if (binaryPathName.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n\n if (binaryPathName[0] == '\"')\n {\n binaryPathName = binaryPathName[1..];\n var index = binaryPathName.IndexOf('\"');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n else\n {\n var index = binaryPathName.IndexOf(' ');\n return index < 0 ? binaryPathName : binaryPathName[..index];\n }\n }\n finally\n {\n Marshal.FreeHGlobal(buffer);\n }\n }\n\n private static void StartService(SafeServiceHandle serviceHandle)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_RUNNING ||\n status.dwCurrentState == ServiceState.SERVICE_START_PENDING)\n {\n return;\n }\n\n if (AdvApi32.StartService(serviceHandle, 0, null) == false)\n {\n throw new Win32Exception();\n }\n }\n\n \/\/\/ \n \/\/\/ 停止并删除服务\n \/\/\/ <\/summary> \n [SupportedOSPlatform(\"windows\")]\n public override void StopDelete()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return;\n }\n\n StopService(serviceHandle, TimeSpan.FromSeconds(30d));\n if (DeleteService(serviceHandle) == false)\n {\n throw new Win32Exception();\n }\n }\n\n private static unsafe void StopService(SafeServiceHandle serviceHandle, TimeSpan maxWaitTime)\n {\n var status = new SERVICE_STATUS();\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING)\n {\n var failureAction = new SERVICE_FAILURE_ACTIONS();\n if (ChangeServiceConfig2(serviceHandle, ServiceInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, &failureAction) == false)\n {\n throw new Win32Exception();\n }\n\n if (ControlService(serviceHandle, ServiceControl.SERVICE_CONTROL_STOP, ref status) == false)\n {\n throw new Win32Exception();\n }\n\n \/\/ 这里不需要恢复SERVICE_CONFIG_FAILURE_ACTIONS,因为下面我们要删除服务\n }\n\n var stopwatch = Stopwatch.StartNew();\n var statusQueryDelay = TimeSpan.FromMilliseconds(100d);\n while (stopwatch.Elapsed < maxWaitTime)\n {\n if (status.dwCurrentState == ServiceState.SERVICE_STOPPED)\n {\n return;\n }\n\n Thread.Sleep(statusQueryDelay);\n if (QueryServiceStatus(serviceHandle, ref status) == false)\n {\n throw new Win32Exception();\n }\n }\n\n throw new TimeoutException($\"等待服务停止超过了{maxWaitTime.TotalSeconds}秒\");\n }\n\n \/\/\/ \n \/\/\/ 尝试获取服务的进程id\n \/\/\/ <\/summary>\n \/\/\/ <\/param>\n \/\/\/ <\/returns>\n protected unsafe override bool TryGetProcessId(out int processId)\n {\n processId = 0;\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }\n\n using var serviceHandle = OpenService(managerHandle, this.Name, ServiceAccess.SERVICE_ALL_ACCESS);\n if (serviceHandle.IsInvalid == true)\n {\n return false;\n }\n\n var status = new SERVICE_STATUS_PROCESS();\n if (QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, &status, sizeof(SERVICE_STATUS_PROCESS), out _) == false)\n {\n return false;\n }\n\n processId = (int)status.dwProcessId;\n return processId > 0;\n }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ }\n\/\/ var linuxOptions = CreateLinuxOptions(filePath, options);\n\/\/ using (var fileStream = File.OpenWrite(unitFilePath))\n\/\/ {\n\/\/ using var wirter = new StreamWriter(fileStream);\n\/\/ linuxOptions.WriteTo(wirter);\n\/\/ }\n\/\/ \/\/ SELinux\n\/\/ Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n\/\/ SystemControl(\"daemon-reload\", showError: true);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ if (filePath.IsEmpty || wantedBy.IsEmpty)\n\/\/ {\n\/\/ return ReadOnlySpan.Empty;\n\/\/ }\n\/\/ var wants = $\"{wantedBy.ToString()}.wants\";\n\/\/ var unitFileName = Path.GetFileName(unitFilePath);\n\/\/ var unitFileDir = Path.GetDirectoryName(unitFilePath);\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ if (geteuid() != 0)\n\/\/ {\n\/\/ throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ line = line[execStartPrefix.Length..];\n\/\/ var index = line.IndexOf(' ');\n\/\/ filePath = index < 0 ? line : line[..index];\n\/\/ }\n\/\/ else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n\/\/ {\n\/\/ wantedBy = line[wantedByPrefix.Length..].Trim();\n\/\/ }\n\/\/ if (filePath.Length > 0 && wantedBy.Length > 0)\n\/\/ {\n\n\/\/ the below code fragment can be found in:\n\/\/ ServiceSelf\/LinuxService.cs\n\/\/ {\n\/\/ execStart = $\"{filePath} {string.Join(' ', args)}\";\n\/\/ }\n\/\/ }\n\/\/ var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n\/\/ ? Path.GetDirectoryName(filePath)\n\/\/ : Path.GetFullPath(options.WorkingDirectory);\n\/\/ var linuxOptions = options.Linux.Clone();\n\/\/ linuxOptions.Unit[\"Description\"] = options.Description;\n\/\/ linuxOptions.Service[\"ExecStart\"] = execStart;\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" }\n var linuxOptions = CreateLinuxOptions(filePath, options);\n using (var fileStream = File.OpenWrite(unitFilePath))\n {\n using var wirter = new StreamWriter(fileStream);\n linuxOptions.WriteTo(wirter);\n }\n \/\/ SELinux\n Shell(\"chcon\", $\"--type=bin_t {filePath}\", showError: false);\n SystemControl(\"daemon-reload\", showError: true);","filename":"ServiceSelf\/LinuxService.cs","score":53.2201877165},{"retrieved_chunk":" break;\n }\n }\n if (filePath.IsEmpty || wantedBy.IsEmpty)\n {\n return ReadOnlySpan.Empty;\n }\n var wants = $\"{wantedBy.ToString()}.wants\";\n var unitFileName = Path.GetFileName(unitFilePath);\n var unitFileDir = Path.GetDirectoryName(unitFilePath);","filename":"ServiceSelf\/LinuxService.cs","score":21.4704854208},{"retrieved_chunk":" if (geteuid() != 0)\n {\n throw new UnauthorizedAccessException(\"无法操作服务:没有root权限\");\n }\n }\n }\n}","filename":"ServiceSelf\/LinuxService.cs","score":12.9341429723},{"retrieved_chunk":" line = line[execStartPrefix.Length..];\n var index = line.IndexOf(' ');\n filePath = index < 0 ? line : line[..index];\n }\n else if (line.StartsWith(wantedByPrefix, StringComparison.OrdinalIgnoreCase))\n {\n wantedBy = line[wantedByPrefix.Length..].Trim();\n }\n if (filePath.Length > 0 && wantedBy.Length > 0)\n {","filename":"ServiceSelf\/LinuxService.cs","score":12.5447254174},{"retrieved_chunk":" {\n execStart = $\"{filePath} {string.Join(' ', args)}\";\n }\n }\n var workingDirectory = string.IsNullOrEmpty(options.WorkingDirectory)\n ? Path.GetDirectoryName(filePath)\n : Path.GetFullPath(options.WorkingDirectory);\n var linuxOptions = options.Linux.Clone();\n linuxOptions.Unit[\"Description\"] = options.Description;\n linuxOptions.Service[\"ExecStart\"] = execStart;","filename":"ServiceSelf\/LinuxService.cs","score":12.51945556}],"metadata.task_id":"project_cc_csharp\/14","metadata.repository":"xljiulang-ServiceSelf-7f8604b","metadata.file":"ServiceSelf\/WindowsService.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":66,"metadata.right_context_start_lineno":68,"prediction":"\n \/\/\/ \n \/\/\/ 启动服务\n \/\/\/ <\/summary>\n [SupportedOSPlatform(\"windows\")]\n public override void Start()\n {\n using var managerHandle = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);\n if (managerHandle.IsInvalid == true)\n {\n throw new Win32Exception();\n }","prediction_status":"success"} +{"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlayListItem\n {\n [Ignore]\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public int StartTrimOffsetTicks { get; set; }\n public int EndTrimOffsetTicks { get; set; }\n public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs\n\/\/ public long DurationTicks { get; set; }\n\/\/ public long EndTransitionDurationTicks { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemMarkerId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/UserMark.cs\n\/\/ public string UserMarkGuid { get; set; } = null!;\n\/\/ public int Version { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewUserMarkId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Location.cs\n\/\/ public int? Track { get; set; }\n\/\/ public int IssueTagNumber { get; set; }\n\/\/ public string? KeySymbol { get; set; }\n\/\/ public int? MepsLanguage { get; set; }\n\/\/ public int Type { get; set; }\n\/\/ public string? Title { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewLocationId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Bookmark.cs\n\/\/ public string Title { get; set; } = null!;\n\/\/ public string? Snippet { get; set; }\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":" public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n [Ignore]\n public int NewPlaylistItemMarkerId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","score":35.2688987605},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":33.5181844877},{"retrieved_chunk":" public string UserMarkGuid { get; set; } = null!;\n public int Version { get; set; }\n [Ignore]\n public int NewUserMarkId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/UserMark.cs","score":32.6484887357},{"retrieved_chunk":" public int? Track { get; set; }\n public int IssueTagNumber { get; set; }\n public string? KeySymbol { get; set; }\n public int? MepsLanguage { get; set; }\n public int Type { get; set; }\n public string? Title { get; set; }\n [Ignore]\n public int NewLocationId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Location.cs","score":31.6249135327},{"retrieved_chunk":" public string Title { get; set; } = null!;\n public string? Snippet { get; set; }\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Bookmark.cs","score":31.1830251893}],"metadata.task_id":"project_cc_csharp\/37","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlayListItem.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":15,"metadata.right_context_start_lineno":17,"prediction":"Ignore]\n public Playlist Playlist { get; set; } = null!;\n public int PlaylistId { get; set; }","prediction_status":"success"} {"language":"csharp","groundtruth":"Ignore]\n public int NewPlaylistItemMarkerId {","segments.prefix":"using JWLSLMerge.Data.Attributes;\n\nnamespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarker\n {\n [Ignore]\n public int PlaylistItemMarkerId { get; set; }\n public int PlaylistItemId { get; set; }\n public string Label { get; set; } = null!;\n public long StartTimeTicks { get; set; }\n public long DurationTicks { get; set; }\n public long EndTransitionDurationTicks { get; set; }\n\n [","segments.suffix":" get; set; }\n }\n}\n","segments.crossfile_context.text":"\/\/ Here are some relevant code fragments from other files of the repo:\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemIndependentMediaMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int IndependentMediaId { get; set; }\n\/\/ public long DurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemLocationMap\n\/\/ {\n\/\/ public int PlaylistItemId { get; set; }\n\/\/ public int LocationId { get; set; }\n\/\/ public int MajorMultimediaType { get; set; }\n\/\/ public long? BaseDurationTicks { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlayListItem.cs\n\/\/ public int Accuracy { get; set; }\n\/\/ public int EndAction { get; set; }\n\/\/ public string ThumbnailFilePath { get; set; } = null!;\n\/\/ [Ignore]\n\/\/ public int NewPlaylistItemId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/Note.cs\n\/\/ public string? Title { get; set; }\n\/\/ public string? Content { get; set; }\n\/\/ public string LastModified { get; set; } = null!;\n\/\/ public string Created { get; set; } = null!;\n\/\/ public int BlockType { get; set; }\n\/\/ public int? BlockIdentifier { get; set; }\n\/\/ [Ignore]\n\/\/ public int NewNoteId { get; set; }\n\/\/ }\n\/\/ }\n\n\/\/ the below code fragment can be found in:\n\/\/ JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs\n\/\/ namespace JWLSLMerge.Data.Models\n\/\/ {\n\/\/ public class PlaylistItemMarkerParagraphMap\n\/\/ {\n\/\/ public int PlaylistItemMarkerId { get; set; }\n\/\/ public int MepsDocumentId { get; set; }\n\/\/ public int ParagraphIndex { get; set; }\n\/\/ public int MarkerIndexWithinParagraph { get; set; }\n\/\/ }\n\/\/ }\n\n","segments.crossfile_context.list":[{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemIndependentMediaMap\n {\n public int PlaylistItemId { get; set; }\n public int IndependentMediaId { get; set; }\n public long DurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemIndependentMediaMap.cs","score":40.1396202216},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemLocationMap\n {\n public int PlaylistItemId { get; set; }\n public int LocationId { get; set; }\n public int MajorMultimediaType { get; set; }\n public long? BaseDurationTicks { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemLocationMap.cs","score":35.276235533},{"retrieved_chunk":" public int Accuracy { get; set; }\n public int EndAction { get; set; }\n public string ThumbnailFilePath { get; set; } = null!;\n [Ignore]\n public int NewPlaylistItemId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlayListItem.cs","score":29.760486252},{"retrieved_chunk":" public string? Title { get; set; }\n public string? Content { get; set; }\n public string LastModified { get; set; } = null!;\n public string Created { get; set; } = null!;\n public int BlockType { get; set; }\n public int? BlockIdentifier { get; set; }\n [Ignore]\n public int NewNoteId { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/Note.cs","score":25.3790812253},{"retrieved_chunk":"namespace JWLSLMerge.Data.Models\n{\n public class PlaylistItemMarkerParagraphMap\n {\n public int PlaylistItemMarkerId { get; set; }\n public int MepsDocumentId { get; set; }\n public int ParagraphIndex { get; set; }\n public int MarkerIndexWithinParagraph { get; set; }\n }\n}","filename":"JWLSLMerge.Data\/Models\/PlaylistItemMarkerParagraphMap.cs","score":25.2581961912}],"metadata.task_id":"project_cc_csharp\/29","metadata.repository":"pliniobrunelli-JWLSLMerge-7fe66dc","metadata.file":"JWLSLMerge.Data\/Models\/PlaylistItemMarker.cs","metadata.context_start_lineno":0,"metadata.groundtruth_start_lineno":14,"metadata.right_context_start_lineno":16,"prediction":"Ignore]\n public PlaylistItem PlaylistItem {","prediction_status":"success"}