code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def cookie_to_har(cookie): """ Convert a Cookie instance to a dict in HAR cookie format. """ c = { 'name': cookie.name, 'value': cookie.value, 'secure': cookie.secure, } if cookie.path_specified: c['path'] = cookie.path if cookie.domain_specified: c['...
Convert a Cookie instance to a dict in HAR cookie format.
cookie_to_har
python
scrapy-plugins/scrapy-splash
scrapy_splash/cookies.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/cookies.py
BSD-3-Clause
def request_fingerprint( request, include_headers=None, keep_fragments=False, ): """ Return the request fingerprint as an hexadecimal string. The request fingerprint is a hash that uniquely identifies the resource the request points to. For example, take the following two urls: http://...
Return the request fingerprint as an hexadecimal string. The request fingerprint is a hash that uniquely identifies the resource the request points to. For example, take the following two urls: http://www.example.com/query?id=111&cat=222 http://www.example.com/query?cat=222&id=111 Even thoug...
request_fingerprint
python
scrapy-plugins/scrapy-splash
scrapy_splash/dupefilter.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/dupefilter.py
BSD-3-Clause
def splash_request_fingerprint(request, include_headers=None): """ Request fingerprint which takes 'splash' meta key into account """ warn( ( "scrapy_splash.splash_request_fingerprint is deprecated. Set " "the REQUEST_FINGERPRINTER_CLASS Scrapy setting to " "\"scrapy_...
Request fingerprint which takes 'splash' meta key into account
splash_request_fingerprint
python
scrapy-plugins/scrapy-splash
scrapy_splash/dupefilter.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/dupefilter.py
BSD-3-Clause
def process_request(self, request, spider): """ For Splash requests add 'cookies' key with current cookies to ``request.meta['splash']['args']`` and remove cookie headers sent to Splash itself. """ if 'splash' not in request.meta: return if request.me...
For Splash requests add 'cookies' key with current cookies to ``request.meta['splash']['args']`` and remove cookie headers sent to Splash itself.
process_request
python
scrapy-plugins/scrapy-splash
scrapy_splash/middleware.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/middleware.py
BSD-3-Clause
def process_response(self, request, response, spider): """ For Splash JSON responses add all cookies from 'cookies' in a response to the cookiejar. """ from scrapy_splash import SplashJsonResponse if not isinstance(response, SplashJsonResponse): return respons...
For Splash JSON responses add all cookies from 'cookies' in a response to the cookiejar.
process_response
python
scrapy-plugins/scrapy-splash
scrapy_splash/middleware.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/middleware.py
BSD-3-Clause
def _process_request(self, request, spider): """ Replace requested meta['splash']['args'] values with their fingerprints. This allows to store values only once in request queue, which helps with disk queue size. Downloader middleware should restore the values from fingerprints. ...
Replace requested meta['splash']['args'] values with their fingerprints. This allows to store values only once in request queue, which helps with disk queue size. Downloader middleware should restore the values from fingerprints.
_process_request
python
scrapy-plugins/scrapy-splash
scrapy_splash/middleware.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/middleware.py
BSD-3-Clause
def _process_x_splash_saved_arguments(self, request, response): """ Keep track of arguments saved by Splash. """ saved_args = get_splash_headers(response).get(b'X-Splash-Saved-Arguments') if not saved_args: return saved_args = parse_x_splash_saved_arguments_header(saved_args)...
Keep track of arguments saved by Splash.
_process_x_splash_saved_arguments
python
scrapy-plugins/scrapy-splash
scrapy_splash/middleware.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/middleware.py
BSD-3-Clause
def _498_retry_request(self, request, response): """ Return a retry request for HTTP 498 responses. HTTP 498 means load_args are not present on server; client should retry the request with full argument values instead of their hashes. """ meta = copy.deepcopy(request.meta...
Return a retry request for HTTP 498 responses. HTTP 498 means load_args are not present on server; client should retry the request with full argument values instead of their hashes.
_498_retry_request
python
scrapy-plugins/scrapy-splash
scrapy_splash/middleware.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/middleware.py
BSD-3-Clause
def replace_downloader_middleware(crawler, old_cls, new_cls): """ Replace downloader middleware with another one """ try: new_mw = new_cls.from_crawler(crawler) except NotConfigured: return mw_manager = crawler.engine.downloader.middleware mw_manager.middlewares = tuple([ mw...
Replace downloader middleware with another one
replace_downloader_middleware
python
scrapy-plugins/scrapy-splash
scrapy_splash/middleware.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/middleware.py
BSD-3-Clause
def replace(self, *args, **kwargs): """Create a new Response with the same attributes except for those given new values. """ for x in ['url', 'status', 'headers', 'body', 'request', 'flags', 'real_url', 'splash_response_status', 'splash_response_header...
Create a new Response with the same attributes except for those given new values.
replace
python
scrapy-plugins/scrapy-splash
scrapy_splash/response.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/response.py
BSD-3-Clause
def _load_from_json(self): """ Fill response attributes from JSON results """ # response.status if 'http_status' in self.data: self.status = int(self.data['http_status']) elif self._splash_options().get('http_status_from_error_code', False): if 'error' in self.da...
Fill response attributes from JSON results
_load_from_json
python
scrapy-plugins/scrapy-splash
scrapy_splash/response.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/response.py
BSD-3-Clause
def from_args(self, headers=None, url=None, filename=None, body=None): """Guess the most appropriate Response class based on the given arguments.""" cls = super(SplashResponseTypes, self).from_args( headers=headers, url=url, filename=filename, body...
Guess the most appropriate Response class based on the given arguments.
from_args
python
scrapy-plugins/scrapy-splash
scrapy_splash/responsetypes.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/responsetypes.py
BSD-3-Clause
def dict_hash(obj, start=''): """ Return a hash for a dict, based on its contents """ h = hashlib.sha1(to_bytes(start)) h.update(to_bytes(obj.__class__.__name__)) if isinstance(obj, dict): for key, value in sorted(obj.items()): h.update(to_bytes(key)) h.update(to_bytes(di...
Return a hash for a dict, based on its contents
dict_hash
python
scrapy-plugins/scrapy-splash
scrapy_splash/utils.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/utils.py
BSD-3-Clause
def json_based_hash(value): """ Return a hash for any JSON-serializable value. >>> json_based_hash({"foo": "bar", "baz": [1, 2]}) '0570066939bea46c610bfdc35b20f37ef09d05ed' """ fp = _fast_hash(value) if fp not in _hash_cache: _hash_cache[fp] = _json_based_hash(_process(value, sha=Tr...
Return a hash for any JSON-serializable value. >>> json_based_hash({"foo": "bar", "baz": [1, 2]}) '0570066939bea46c610bfdc35b20f37ef09d05ed'
json_based_hash
python
scrapy-plugins/scrapy-splash
scrapy_splash/utils.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/utils.py
BSD-3-Clause
def headers_to_scrapy(headers): """ Return scrapy.http.Headers instance from headers data. 3 data formats are supported: * {name: value, ...} dict; * [(name, value), ...] list; * [{'name': name, 'value': value'}, ...] list (HAR headers format). """ if isinstance(headers or {}, dict): ...
Return scrapy.http.Headers instance from headers data. 3 data formats are supported: * {name: value, ...} dict; * [(name, value), ...] list; * [{'name': name, 'value': value'}, ...] list (HAR headers format).
headers_to_scrapy
python
scrapy-plugins/scrapy-splash
scrapy_splash/utils.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/utils.py
BSD-3-Clause
def scrapy_headers_to_unicode_dict(headers): """ Convert scrapy.http.Headers instance to a dictionary suitable for JSON encoding. """ return { to_unicode(key): to_unicode(b','.join(value)) for key, value in headers.items() }
Convert scrapy.http.Headers instance to a dictionary suitable for JSON encoding.
scrapy_headers_to_unicode_dict
python
scrapy-plugins/scrapy-splash
scrapy_splash/utils.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/utils.py
BSD-3-Clause
def parse_x_splash_saved_arguments_header(value): """ Parse X-Splash-Saved-Arguments header value. >>> value = u"name1=9a6747fc6259aa374ab4e1bb03074b6ec672cf99;name2=ba001160ef96fe2a3f938fea9e6762e204a562b3" >>> dct = parse_x_splash_saved_arguments_header(value) >>> sorted(list(dct.keys())) ['n...
Parse X-Splash-Saved-Arguments header value. >>> value = u"name1=9a6747fc6259aa374ab4e1bb03074b6ec672cf99;name2=ba001160ef96fe2a3f938fea9e6762e204a562b3" >>> dct = parse_x_splash_saved_arguments_header(value) >>> sorted(list(dct.keys())) ['name1', 'name2'] >>> dct['name1'] '9a6747fc6259aa3...
parse_x_splash_saved_arguments_header
python
scrapy-plugins/scrapy-splash
scrapy_splash/utils.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/scrapy_splash/utils.py
BSD-3-Clause
def crawl_items( spider_cls, resource_cls, settings, spider_kwargs=None, url_path="", ): """ Use spider_cls to crawl resource_cls. URL of the resource is passed to the spider as ``url`` argument. Return ``(items, resource_url, crawler)`` tuple. """ spider_kwargs = {} if spider_kw...
Use spider_cls to crawl resource_cls. URL of the resource is passed to the spider as ``url`` argument. Return ``(items, resource_url, crawler)`` tuple.
crawl_items
python
scrapy-plugins/scrapy-splash
tests/utils.py
https://github.com/scrapy-plugins/scrapy-splash/blob/master/tests/utils.py
BSD-3-Clause
def build_file_documents_simple( clazzes: list, functions: list, file_name: str, file_content: str ) -> list[Document]: """ Really simple file document format, where we put all content of a single file into a single document """ documents = [] meta_data = construct_file_meta_data(file_name, cla...
Really simple file document format, where we put all content of a single file into a single document
build_file_documents_simple
python
OpenAutoCoder/Agentless
agentless/fl/Index.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/fl/Index.py
MIT
def construct_topn_file_context( file_to_locs, pred_files, file_contents, structure, context_window: int, loc_interval: bool = True, fine_grain_loc_only: bool = False, add_space: bool = False, sticky_scroll: bool = False, no_line_number: bool = True, ): """Concatenate provide...
Concatenate provided locations to form a context. loc: {"file_name_1": ["loc_str_1"], ...}
construct_topn_file_context
python
OpenAutoCoder/Agentless
agentless/repair/repair.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/repair/repair.py
MIT
def get_all_patches_num(instance_id, num_samples, deduplicate) -> list[str]: """Returns all unique patches with number.""" # print(f"{len(execution_results)}") patches = [execution_results[instance_id][i]["patch"] for i in range(num_samples)] if deduplicate: patch_keys = [ execution_...
Returns all unique patches with number.
get_all_patches_num
python
OpenAutoCoder/Agentless
agentless/repair/rerank.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/repair/rerank.py
MIT
def txt_file_contains_string(path_to_txt, expected_output, other_patterns=[]): """ Check if the given text file contains the specified string. :param path_to_txt: Path to the text file. :param expected_output: The string to search for in the text file. :return: True if the string is found in the tex...
Check if the given text file contains the specified string. :param path_to_txt: Path to the text file. :param expected_output: The string to search for in the text file. :return: True if the string is found in the text file, otherwise False.
txt_file_contains_string
python
OpenAutoCoder/Agentless
agentless/test/run_tests.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/test/run_tests.py
MIT
def _from_json_or_obj(key: str) -> Any: """If key points to string, load with json""" if isinstance(instance[key], str): return json.loads(instance[key]) return instance[key]
If key points to string, load with json
_from_json_or_obj
python
OpenAutoCoder/Agentless
agentless/test/run_tests.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/test/run_tests.py
MIT
def make_reproduction_script_list( instance, specs, env_name, repo_directory, base_commit, reproduce_patch ): """ Applies new production tests and run tests """ # Reset test files to the state they should be in before the patch. reset_tests_command = f"git checkout {base_commit}" HEREDOC_DE...
Applies new production tests and run tests
make_reproduction_script_list
python
OpenAutoCoder/Agentless
agentless/test/run_tests.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/test/run_tests.py
MIT
def make_regression_script_list(instance, specs, env_name, repo_directory, base_commit): """ Applies the test patch and runs the tests. """ # Reset test files to the state they should be in before the patch. reset_tests_command = f"git checkout {base_commit}" HEREDOC_DELIMITER = "EOF_1143293249...
Applies the test patch and runs the tests.
make_regression_script_list
python
OpenAutoCoder/Agentless
agentless/test/run_tests.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/test/run_tests.py
MIT
def rearrange_patches(test_specs): """ rearrange the patches such that slower instance_ids are evaluated first this way pipelining will be faster. """ slow_instance_ids = ["sympy__sympy-11870"] slow_specs = [ test_spec for test_spec in test_specs if test_spec.instance_i...
rearrange the patches such that slower instance_ids are evaluated first this way pipelining will be faster.
rearrange_patches
python
OpenAutoCoder/Agentless
agentless/test/run_tests.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/test/run_tests.py
MIT
def num_tokens_from_messages(message, model="gpt-3.5-turbo-0301"): """Returns the number of tokens used by a list of messages.""" try: encoding = tiktoken.encoding_for_model(model) except KeyError: encoding = tiktoken.get_encoding("cl100k_base") if isinstance(message, list): # us...
Returns the number of tokens used by a list of messages.
num_tokens_from_messages
python
OpenAutoCoder/Agentless
agentless/util/api_requests.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/api_requests.py
MIT
def fake_git_repo(repo_playground, file_pathes, old_contents, new_contents) -> str: """create a fake git repo to obtain git diff format""" if not isinstance(file_pathes, list): # for backwards compatibility file_pathes = [file_pathes] old_contents = [old_contents] new_contents =...
create a fake git repo to obtain git diff format
fake_git_repo
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def fake_git_apply(repo_playground, file_path, old_content, patch) -> str: """create a fake git repo to obtain new file content""" # Generate a temperary folder and add uuid to avoid collision repo_playground = os.path.join(repo_playground, str(uuid.uuid4())) # assert playground doesn't exist asse...
create a fake git repo to obtain new file content
fake_git_apply
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def fake_git_apply_multiple(repo_playground, file_path_contents, patch) -> dict: """create a fake git repo to obtain new file contents (multiple)""" # Generate a temperary folder and add uuid to avoid collision repo_playground = os.path.join(repo_playground, str(uuid.uuid4())) # assert playground does...
create a fake git repo to obtain new file contents (multiple)
fake_git_apply_multiple
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def get_functions(tree): """Get a set of function and method names from the AST tree.""" functions = {} class FunctionVisitor(ast.NodeVisitor): def __init__(self): self.parents = [] def visit(self, node): self.parents.append(node) super().visit(node) ...
Get a set of function and method names from the AST tree.
get_functions
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def normalize_patch( instance_id, patch: str, original_file_content: list, new_file_content: list, edited_files: list, ) -> str: "Remove edits to trailing spaces and comments in the patch." if not patch.strip(): return "" normalized_diff = "" for o_file_content, n_file_cont...
Remove edits to trailing spaces and comments in the patch.
normalize_patch
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def split_edit_multifile_commands( commands, diff_format=False, str_replace_format=False ) -> dict[str, str]: """Split commands based on edited files.""" file_to_commands = OrderedDict() if str_replace_format: for command in commands: file_name = None for json_message in ...
Split commands based on edited files.
split_edit_multifile_commands
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def parse_str_replace_edit_commands( commands, content, file_loc_intervals: list[tuple[int, int]] ): """ Original implementation: https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/computer_use_demo/tools/edit.py """ # let's first make sure the intervals are sorted f...
Original implementation: https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/computer_use_demo/tools/edit.py
parse_str_replace_edit_commands
python
OpenAutoCoder/Agentless
agentless/util/postprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/postprocess_data.py
MIT
def line_wrap_content( content: str, context_intervals=None, add_space=False, no_line_number=False, sticky_scroll=False, ): """add n| to each line, where n increases""" def is_scope(line): # TODO: this might not be precise, can improve with syntax parsing return line.startsw...
add n| to each line, where n increases
line_wrap_content
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def check_contains_valid_loc(file_to_locs, structure): """checks if the llm generated locations have at least one location valid""" file_contents = get_repo_files(structure, list(file_to_locs.keys())) for pred_file, locs in file_to_locs.items(): line_locs, _ = transfer_arb_locs_to_locs( ...
checks if the llm generated locations have at least one location valid
check_contains_valid_loc
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def compile_gt_locations(gt_location: dict) -> tuple[list, set, set, set]: """mostly serves a way to check what are the gt locations in gt patch""" edits = gt_location["edits"] lines, classes, methods, functions = [], set(), set(), set() adds = set() for edit in edits: for clazz in edit["...
mostly serves a way to check what are the gt locations in gt patch
compile_gt_locations
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def filter_out_test_files(structure): """filter out test files from the project structure""" for key, value in list(structure.items()): if key.startswith("test"): del structure[key] elif isinstance(value, dict): filter_out_test_files(value)
filter out test files from the project structure
filter_out_test_files
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def filter_proposed_files(proposed_files, repo_structure): """ Filter proposed files against a given repository structure. Arguments: proposed_files -- list of proposed files with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of dictionaries...
Filter proposed files against a given repository structure. Arguments: proposed_files -- list of proposed files with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of dictionaries with instance IDs and valid files matching the repository structu...
filter_proposed_files
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def filter_proposed_classes(proposed_classes, repo_structure): """ Filter proposed classes against a given repository structure. Arguments: proposed_classes -- list of proposed classes with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of di...
Filter proposed classes against a given repository structure. Arguments: proposed_classes -- list of proposed classes with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of dictionaries with instance IDs and valid classes matching the repository...
filter_proposed_classes
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def filter_proposed_methods(proposed_methods, repo_structure): """ Filter proposed methods against a given repository structure. Arguments: proposed_methods -- list of proposed methods with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of di...
Filter proposed methods against a given repository structure. Arguments: proposed_methods -- list of proposed methods with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of dictionaries with instance IDs and valid methods matching the repository...
filter_proposed_methods
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def filter_proposed_functions(proposed_functions, repo_structure): """ Filter proposed functions against a given repository structure. Arguments: proposed_functions -- list of proposed functions with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A ...
Filter proposed functions against a given repository structure. Arguments: proposed_functions -- list of proposed functions with instance IDs repo_structure -- list of repository structures with instance IDs Returns: A list of dictionaries with instance IDs and valid functions matching the re...
filter_proposed_functions
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def get_full_file_paths_and_classes_and_functions(structure, current_path=""): """ Recursively retrieve all file paths, classes, and functions within a directory structure. Arguments: structure -- a dictionary representing the directory structure current_path -- the path accumulated so far, used du...
Recursively retrieve all file paths, classes, and functions within a directory structure. Arguments: structure -- a dictionary representing the directory structure current_path -- the path accumulated so far, used during recursion (default="") Returns: A tuple containing: - files: list of...
get_full_file_paths_and_classes_and_functions
python
OpenAutoCoder/Agentless
agentless/util/preprocess_data.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/preprocess_data.py
MIT
def load_jsonl(filepath): """ Load a JSONL file from the given filepath. Arguments: filepath -- the path to the JSONL file to load Returns: A list of dictionaries representing the data in each line of the JSONL file. """ with open(filepath, "r") as file: return [json.loads(line...
Load a JSONL file from the given filepath. Arguments: filepath -- the path to the JSONL file to load Returns: A list of dictionaries representing the data in each line of the JSONL file.
load_jsonl
python
OpenAutoCoder/Agentless
agentless/util/utils.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/utils.py
MIT
def write_jsonl(data, filepath): """ Write data to a JSONL file at the given filepath. Arguments: data -- a list of dictionaries to write to the JSONL file filepath -- the path to the JSONL file to write """ with open(filepath, "w") as file: for entry in data: file.write...
Write data to a JSONL file at the given filepath. Arguments: data -- a list of dictionaries to write to the JSONL file filepath -- the path to the JSONL file to write
write_jsonl
python
OpenAutoCoder/Agentless
agentless/util/utils.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/utils.py
MIT
def combine_by_instance_id(data): """ Combine data entries by their instance ID. Arguments: data -- a list of dictionaries with instance IDs and other information Returns: A list of combined dictionaries by instance ID with all associated data. """ combined_data = defaultdict(lambda: d...
Combine data entries by their instance ID. Arguments: data -- a list of dictionaries with instance IDs and other information Returns: A list of combined dictionaries by instance ID with all associated data.
combine_by_instance_id
python
OpenAutoCoder/Agentless
agentless/util/utils.py
https://github.com/OpenAutoCoder/Agentless/blob/master/agentless/util/utils.py
MIT
def parse_patch(patch): """ Parse a git patch into a structured format. Parameters: patch (str): The git patch as a string. Returns: list: A list of dictionaries representing the file changes and hunks. """ file_changes = [] current_file = None current_hunk = None d...
Parse a git patch into a structured format. Parameters: patch (str): The git patch as a string. Returns: list: A list of dictionaries representing the file changes and hunks.
parse_patch
python
OpenAutoCoder/Agentless
get_repo_structure/get_patch_info.py
https://github.com/OpenAutoCoder/Agentless/blob/master/get_repo_structure/get_patch_info.py
MIT
def parse_python_file(file_path, file_content=None): """Parse a Python file to extract class and function definitions with their line numbers. :param file_path: Path to the Python file. :return: Class names, function names, and file contents """ if file_content is None: try: with...
Parse a Python file to extract class and function definitions with their line numbers. :param file_path: Path to the Python file. :return: Class names, function names, and file contents
parse_python_file
python
OpenAutoCoder/Agentless
get_repo_structure/get_repo_structure.py
https://github.com/OpenAutoCoder/Agentless/blob/master/get_repo_structure/get_repo_structure.py
MIT
def create_structure(directory_path): """Create the structure of the repository directory by parsing Python files. :param directory_path: Path to the repository directory. :return: A dictionary representing the structure. """ structure = {} for root, _, files in os.walk(directory_path): ...
Create the structure of the repository directory by parsing Python files. :param directory_path: Path to the repository directory. :return: A dictionary representing the structure.
create_structure
python
OpenAutoCoder/Agentless
get_repo_structure/get_repo_structure.py
https://github.com/OpenAutoCoder/Agentless/blob/master/get_repo_structure/get_repo_structure.py
MIT
def read_json_file(file_path: str | TextIO, encoding: str = "utf-8") -> dict: """ Reads a JSON file and returns its contents as a dictionary. Args: file_path (str): The path to the JSON file. Returns: dict: The contents of the JSON file as a dictionary. ...
Reads a JSON file and returns its contents as a dictionary. Args: file_path (str): The path to the JSON file. Returns: dict: The contents of the JSON file as a dictionary. Raises: FileNotFoundError: If the file is not found, it lists all JSON files...
read_json_file
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def write_code_to_file(file_path: str | TextIO, code: str) -> None: """Write the specified code to a Python file. Args: file_path (str): The path to the Python file. code (str): The code to write to the file. Returns: None """ if isinstance(f...
Write the specified code to a Python file. Args: file_path (str): The path to the Python file. code (str): The code to write to the file. Returns: None
write_code_to_file
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def __init__(self, data: Dict, node_class_mappings: Dict): """Initialize the LoadOrderDeterminer with the given data and node class mappings. Args: data (Dict): The dictionary for which to determine the load order. node_class_mappings (Dict): Mappings of node classes. ""...
Initialize the LoadOrderDeterminer with the given data and node class mappings. Args: data (Dict): The dictionary for which to determine the load order. node_class_mappings (Dict): Mappings of node classes.
__init__
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def determine_load_order(self) -> List[Tuple[str, Dict, bool]]: """Determine the load order for the given data. Returns: List[Tuple[str, Dict, bool]]: A list of tuples representing the load order. """ self._load_special_functions_first() self.is_special_function = Fa...
Determine the load order for the given data. Returns: List[Tuple[str, Dict, bool]]: A list of tuples representing the load order.
determine_load_order
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def _dfs(self, key: str) -> None: """Depth-First Search function to determine the load order. Args: key (str): The key from which to start the DFS. Returns: None """ # Mark the node as visited. self.visited[key] = True inputs = self.data[...
Depth-First Search function to determine the load order. Args: key (str): The key from which to start the DFS. Returns: None
_dfs
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def _load_special_functions_first(self) -> None: """Load functions without dependencies, loaderes, and encoders first. Returns: None """ # Iterate over each key in the data to check for loader keys. for key in self.data: class_def = self.node_class_mappin...
Load functions without dependencies, loaderes, and encoders first. Returns: None
_load_special_functions_first
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def __init__(self, node_class_mappings: Dict, base_node_class_mappings: Dict): """Initialize the CodeGenerator with given node class mappings. Args: node_class_mappings (Dict): Mappings of node classes. base_node_class_mappings (Dict): Base mappings of node classes. """ ...
Initialize the CodeGenerator with given node class mappings. Args: node_class_mappings (Dict): Mappings of node classes. base_node_class_mappings (Dict): Base mappings of node classes.
__init__
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def generate_workflow( self, load_order: List, queue_size: int = 10, ) -> str: """Generate the execution code based on the load order. Args: load_order (List): A list of tuples representing the load order. queue_size (int): The number of photos that w...
Generate the execution code based on the load order. Args: load_order (List): A list of tuples representing the load order. queue_size (int): The number of photos that will be created by the script. Returns: str: Generated execution code as a string.
generate_workflow
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def create_function_call_code( self, obj_name: str, func: str, variable_name: str, is_special_function: bool, **kwargs, ) -> str: """Generate Python code for a function call. Args: obj_name (str): The name of the initialized object. ...
Generate Python code for a function call. Args: obj_name (str): The name of the initialized object. func (str): The function to be called. variable_name (str): The name of the variable that the function result should be assigned to. is_special_function (bool): De...
create_function_call_code
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def format_arg(self, key: str, value: any) -> str: """Formats arguments based on key and value. Args: key (str): Argument key. value (any): Argument value. Returns: str: Formatted argument as a string. """ if key == "noise_seed" or key == "se...
Formats arguments based on key and value. Args: key (str): Argument key. value (any): Argument value. Returns: str: Formatted argument as a string.
format_arg
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def assemble_python_code( self, import_statements: set, speical_functions_code: List[str], code: List[str], queue_size: int, custom_nodes=False, ) -> str: """Generates the final code string. Args: import_statements (set): A set of unique i...
Generates the final code string. Args: import_statements (set): A set of unique import statements. speical_functions_code (List[str]): A list of special functions code strings. code (List[str]): A list of code strings. queue_size (int): Number of photos that will...
assemble_python_code
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def get_class_info(self, class_type: str) -> Tuple[str, str, str]: """Generates and returns necessary information about class type. Args: class_type (str): Class type. Returns: Tuple[str, str, str]: Updated class type, import statement string, class initialization code....
Generates and returns necessary information about class type. Args: class_type (str): Class type. Returns: Tuple[str, str, str]: Updated class type, import statement string, class initialization code.
get_class_info
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def clean_variable_name(class_type: str) -> str: """ Remove any characters from variable name that could cause errors running the Python script. Args: class_type (str): Class type. Returns: str: Cleaned variable name with no special characters or spaces ...
Remove any characters from variable name that could cause errors running the Python script. Args: class_type (str): Class type. Returns: str: Cleaned variable name with no special characters or spaces
clean_variable_name
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def get_function_parameters(self, func: Callable) -> List: """Get the names of a function's parameters. Args: func (Callable): The function whose parameters we want to inspect. Returns: List: A list containing the names of the function's parameters. """ ...
Get the names of a function's parameters. Args: func (Callable): The function whose parameters we want to inspect. Returns: List: A list containing the names of the function's parameters.
get_function_parameters
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def update_inputs(self, inputs: Dict, executed_variables: Dict) -> Dict: """Update inputs based on the executed variables. Args: inputs (Dict): Inputs dictionary to update. executed_variables (Dict): Dictionary storing executed variable names. Returns: Dict:...
Update inputs based on the executed variables. Args: inputs (Dict): Inputs dictionary to update. executed_variables (Dict): Dictionary storing executed variable names. Returns: Dict: Updated inputs dictionary.
update_inputs
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def __init__( self, workflow: str = "", input_file: str = "", output_file: str | TextIO = "", queue_size: int = 1, node_class_mappings: Dict = NODE_CLASS_MAPPINGS, needs_init_custom_nodes: bool = False, ): """Initialize the ComfyUItoPython class with t...
Initialize the ComfyUItoPython class with the given parameters. Exactly one of workflow or input_file must be specified. Args: workflow (str): The workflow's JSON. input_file (str): Path to the input JSON file. output_file (str | TextIO): Path to the output file or a file-lik...
__init__
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def execute(self): """Execute the main workflow to generate Python code. Returns: None """ # Step 1: Import all custom nodes if we need to if self.needs_init_custom_nodes: import_custom_nodes() else: # If they're already imported, we d...
Execute the main workflow to generate Python code. Returns: None
execute
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def run( input_file: str = DEFAULT_INPUT_FILE, output_file: str = DEFAULT_OUTPUT_FILE, queue_size: int = DEFAULT_QUEUE_SIZE, ) -> None: """Generate Python code from a ComfyUI workflow_api.json file. Args: input_file (str): Path to the input JSON file. Defaults to "workflow_api.json". ...
Generate Python code from a ComfyUI workflow_api.json file. Args: input_file (str): Path to the input JSON file. Defaults to "workflow_api.json". output_file (str): Path to the output Python file. Defaults to "workflow_api.py". queue_size (int): The number of times a workflow wi...
run
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def main() -> None: """Main function to generate Python code from a ComfyUI workflow_api.json file.""" parser = ArgumentParser( description="Generate Python code from a ComfyUI workflow_api.json file." ) parser.add_argument( "-f", "--input_file", type=str, help...
Main function to generate Python code from a ComfyUI workflow_api.json file.
main
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python.py
MIT
def import_custom_nodes() -> None: """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS This function sets up a new asyncio event loop, initializes the PromptServer, creates a PromptQueue, and initializes the custom nodes. """ import asyncio impo...
Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS This function sets up a new asyncio event loop, initializes the PromptServer, creates a PromptQueue, and initializes the custom nodes.
import_custom_nodes
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python_utils.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python_utils.py
MIT
def find_path(name: str, path: str = None) -> str: """ Recursively looks at parent folders starting from the given path until it finds the given name. Returns the path as a Path object if found, or None otherwise. """ # If no path is given, use the current working directory if path is None: ...
Recursively looks at parent folders starting from the given path until it finds the given name. Returns the path as a Path object if found, or None otherwise.
find_path
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python_utils.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python_utils.py
MIT
def add_comfyui_directory_to_sys_path() -> None: """ Add 'ComfyUI' to the sys.path """ comfyui_path = find_path("ComfyUI") if comfyui_path is not None and os.path.isdir(comfyui_path): sys.path.append(comfyui_path) print(f"'{comfyui_path}' added to sys.path")
Add 'ComfyUI' to the sys.path
add_comfyui_directory_to_sys_path
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python_utils.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python_utils.py
MIT
def add_extra_model_paths() -> None: """ Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path. """ try: from main import load_extra_path_config except ImportError: print( "Could not import load_extra_path_config from main.py. Looking in ...
Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
add_extra_model_paths
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python_utils.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python_utils.py
MIT
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any: """Returns the value at the given index of a sequence or mapping. If the object is a sequence (like list or string), returns the value at the given index. If the object is a mapping (like a dictionary), returns the value at the index...
Returns the value at the given index of a sequence or mapping. If the object is a sequence (like list or string), returns the value at the given index. If the object is a mapping (like a dictionary), returns the value at the index-th key. Some return a dictionary, in these cases, we look for the "results"...
get_value_at_index
python
pydn/ComfyUI-to-Python-Extension
comfyui_to_python_utils.py
https://github.com/pydn/ComfyUI-to-Python-Extension/blob/master/comfyui_to_python_utils.py
MIT
def build_lr_scheduler(optimizer, optimizer_config, total_step): """Create lr scheduler based on config. note that lr_scheduler must accept a optimizer that has been restored. Args: optimizer_config: A Optimizer proto message. Returns: An optimizer and a list of variables for summary. ...
Create lr scheduler based on config. note that lr_scheduler must accept a optimizer that has been restored. Args: optimizer_config: A Optimizer proto message. Returns: An optimizer and a list of variables for summary. Raises: ValueError: when using an unsupported input data ty...
build_lr_scheduler
python
tianweiy/CenterPoint
det3d/builder.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/builder.py
MIT
def _create_learning_rate_scheduler(optimizer, learning_rate_config, total_step): """Create optimizer learning rate scheduler based on config. Args: learning_rate_config: A LearningRate proto message. Returns: A learning rate. Raises: ValueError: when using an unsupported inpu...
Create optimizer learning rate scheduler based on config. Args: learning_rate_config: A LearningRate proto message. Returns: A learning rate. Raises: ValueError: when using an unsupported input data type.
_create_learning_rate_scheduler
python
tianweiy/CenterPoint
det3d/builder.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/builder.py
MIT
def corners_nd(dims, origin=0.5): """generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. Returns: float array, shape=[N...
generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. Returns: float array, shape=[N, 2 ** ndim, ndim]: returned corners. ...
corners_nd
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def rotation_2d(points, angles): """rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angles (float array, shape=[N]): rotation angle. Returns: float array: same shape as points ""...
rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angles (float array, shape=[N]): rotation angle. Returns: float array: same shape as points
rotation_2d
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def rotation_box(box_corners, angle): """rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angle (float): rotation angle. Returns: float array: same shape as points """ rot_sin...
rotation 2d points based on origin point clockwise when angle positive. Args: points (float array, shape=[N, point_size, 2]): points to be rotated. angle (float): rotation angle. Returns: float array: same shape as points
rotation_box
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def center_to_corner_box3d(centers, dims, angles=None, origin=(0.5, 0.5, 0.5), axis=2): """convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 3]): locations in kitti label file. dims (float array, shape=[N, 3]): dimensions in kitti label file. ...
convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 3]): locations in kitti label file. dims (float array, shape=[N, 3]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in kitti label file. origin (list or arra...
center_to_corner_box3d
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5): """convert kitti locations, dimensions and angles to corners. format: center(xy), dims(xy), angles(clockwise when positive) Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=...
convert kitti locations, dimensions and angles to corners. format: center(xy), dims(xy), angles(clockwise when positive) Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float array, shape...
center_to_corner_box2d
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def iou_jit(boxes, query_boxes, eps=1.0): """calculate box iou. note that jit version runs 2x faster than cython in my machine! Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes ...
calculate box iou. note that jit version runs 2x faster than cython in my machine! Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
iou_jit
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def iou_3d_jit(boxes, query_boxes, add1=True): """calculate box iou3d, ---------- boxes: (N, 6) ndarray of float query_boxes: (K, 6) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ N = boxes.shape[0] K = query_boxes.shape[0] ...
calculate box iou3d, ---------- boxes: (N, 6) ndarray of float query_boxes: (K, 6) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
iou_3d_jit
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def iou_nd_jit(boxes, query_boxes, add1=True): """calculate box iou nd, 2x slower than iou_jit. ---------- boxes: (N, ndim * 2) ndarray of float query_boxes: (K, ndim * 2) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ N = boxes...
calculate box iou nd, 2x slower than iou_jit. ---------- boxes: (N, ndim * 2) ndarray of float query_boxes: (K, ndim * 2) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
iou_nd_jit
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def corner_to_surfaces_3d(corners): """convert 3d box corners from corner function above to surfaces that normal vectors all direct to internal. Args: corners (float array, [N, 8, 3]): 3d box corners. Returns: surfaces (float array, [N, 6, 4, 3]): """ # box_corners: [N, 8, 3], m...
convert 3d box corners from corner function above to surfaces that normal vectors all direct to internal. Args: corners (float array, [N, 8, 3]): 3d box corners. Returns: surfaces (float array, [N, 6, 4, 3]):
corner_to_surfaces_3d
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def assign_label_to_voxel(gt_boxes, coors, voxel_size, coors_range): """assign a 0/1 label to each voxel based on whether the center of voxel is in gt_box. LIDAR. """ voxel_size = np.array(voxel_size, dtype=gt_boxes.dtype) coors_range = np.array(coors_range, dtype=gt_boxes.dtype) shift = coors_r...
assign a 0/1 label to each voxel based on whether the center of voxel is in gt_box. LIDAR.
assign_label_to_voxel
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def image_box_region_area(img_cumsum, bbox): """check a 2d voxel is contained by a box. used to filter empty anchors. Summed-area table algorithm: ==> W ------------------ | | | |------A---------B | | | | | | |----- C---------D Iabcd = I...
check a 2d voxel is contained by a box. used to filter empty anchors. Summed-area table algorithm: ==> W ------------------ | | | |------A---------B | | | | | | |----- C---------D Iabcd = ID-IB-IC+IA Args: img_cumsum: [M, H, W](y...
image_box_region_area
python
tianweiy/CenterPoint
det3d/core/bbox/box_np_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_np_ops.py
MIT
def corners_nd(dims, origin=0.5): """generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. dtype (output dtype, optional): Def...
generate relative box corners based on length per dim and origin point. Args: dims (float array, shape=[N, ndim]): array of length per dim origin (list or array or float): origin point relate to smallest point. dtype (output dtype, optional): Defaults to np.float32 Returns: ...
corners_nd
python
tianweiy/CenterPoint
det3d/core/bbox/box_torch_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_torch_ops.py
MIT
def rotate_points_along_z(points, angle): """ Args: points: (B, N, 3 + C) angle: (B), angle along z-axis, angle increases x ==> y Returns: """ cosa = torch.cos(angle) sina = torch.sin(angle) zeros = angle.new_zeros(points.shape[0]) ones = angle.new_ones(points.shape[0]) ...
Args: points: (B, N, 3 + C) angle: (B), angle along z-axis, angle increases x ==> y Returns:
rotate_points_along_z
python
tianweiy/CenterPoint
det3d/core/bbox/box_torch_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_torch_ops.py
MIT
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5): """convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float arra...
convert kitti locations, dimensions and angles to corners Args: centers (float array, shape=[N, 2]): locations in kitti label file. dims (float array, shape=[N, 2]): dimensions in kitti label file. angles (float array, shape=[N]): rotation_y in kitti label file. Returns: [type]...
center_to_corner_box2d
python
tianweiy/CenterPoint
det3d/core/bbox/box_torch_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_torch_ops.py
MIT
def rotate_nms_pcdet(boxes, scores, thresh, pre_maxsize=None, post_max_size=None): """ :param boxes: (N, 5) [x, y, z, l, w, h, theta] :param scores: (N) :param thresh: :return: """ # transform back to pcdet's coordinate boxes = boxes[:, [0, 1, 2, 4, 3, 5, -1]] boxes[:, -1] = -boxes[:...
:param boxes: (N, 5) [x, y, z, l, w, h, theta] :param scores: (N) :param thresh: :return:
rotate_nms_pcdet
python
tianweiy/CenterPoint
det3d/core/bbox/box_torch_ops.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/box_torch_ops.py
MIT
def _points_count_convex_polygon_3d_jit( points, polygon_surfaces, normal_vec, d, num_surfaces=None ): """count points in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. al...
count points in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. all surfaces' normal vector must direct to internal. max_num_points_of_surface must at least 3. ...
_points_count_convex_polygon_3d_jit
python
tianweiy/CenterPoint
det3d/core/bbox/geometry.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/geometry.py
MIT
def points_count_convex_polygon_3d_jit(points, polygon_surfaces, num_surfaces=None): """check points is in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. all surfaces' normal ...
check points is in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. all surfaces' normal vector must direct to internal. max_num_points_of_surface must at least 3. ...
points_count_convex_polygon_3d_jit
python
tianweiy/CenterPoint
det3d/core/bbox/geometry.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/geometry.py
MIT
def is_line_segment_intersection_jit(lines1, lines2): """check if line segments1 and line segments2 have cross point Args: lines1 (float, [N, 2, 2]): [description] lines2 (float, [M, 2, 2]): [description] Returns: [type]: [description] """ # Return true if line segments AB...
check if line segments1 and line segments2 have cross point Args: lines1 (float, [N, 2, 2]): [description] lines2 (float, [M, 2, 2]): [description] Returns: [type]: [description]
is_line_segment_intersection_jit
python
tianweiy/CenterPoint
det3d/core/bbox/geometry.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/geometry.py
MIT
def points_in_convex_polygon_3d_jit_v1(points, polygon_surfaces, num_surfaces=None): """check points is in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. all surfaces' normal ...
check points is in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. all surfaces' normal vector must direct to internal. max_num_points_of_surface must at least 3. ...
points_in_convex_polygon_3d_jit_v1
python
tianweiy/CenterPoint
det3d/core/bbox/geometry.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/bbox/geometry.py
MIT
def noise_per_object_v3_( gt_boxes, points=None, valid_mask=None, rotation_perturb=np.pi / 4, center_noise_std=1.0, global_random_rot_range=np.pi / 4, num_try=5, group_ids=None, ): """random rotate or remove each groundtrutn independently. use kitti viewer to test this function p...
random rotate or remove each groundtrutn independently. use kitti viewer to test this function points_transform_ Args: gt_boxes: [N, 7], gt box in lidar.points_transform_ points: [M, 4], point cloud in lidar.
noise_per_object_v3_
python
tianweiy/CenterPoint
det3d/core/sampler/preprocess.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/sampler/preprocess.py
MIT
def unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) """ if data.dim() == 1: ret = data.new_full((count,), fill) ret[inds] = data else: new_size = (count,) + data.size()[1:] ret = data.new_full(new_size,...
Unmap a subset of item (data) back to the original set of items (of size count)
unmap
python
tianweiy/CenterPoint
det3d/core/utils/misc.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/core/utils/misc.py
MIT
def _set_group_flag(self): """Set flag according to image aspect ratio. Images with aspect ratio greater than 1 will be set as group 1, otherwise group 0. """ self.flag = np.ones(len(self), dtype=np.uint8) # self.flag = np.zeros(len(self), dtype=np.uint8) # for i ...
Set flag according to image aspect ratio. Images with aspect ratio greater than 1 will be set as group 1, otherwise group 0.
_set_group_flag
python
tianweiy/CenterPoint
det3d/datasets/custom.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/custom.py
MIT
def get_sample_data( nusc, sample_data_token: str, selected_anntokens: List[str] = None ): """ Returns the data path as well as all annotations related to that sample_data. Note that the boxes are transformed into the current sensor's coordinate frame. :param sample_data_token: Sample_data token. ...
Returns the data path as well as all annotations related to that sample_data. Note that the boxes are transformed into the current sensor's coordinate frame. :param sample_data_token: Sample_data token. :param selected_anntokens: If provided only return the selected annotation. :return: (data_path,...
get_sample_data
python
tianweiy/CenterPoint
det3d/datasets/nuscenes/nusc_common.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/nuscenes/nusc_common.py
MIT
def quaternion_yaw(q: Quaternion) -> float: """ Calculate the yaw angle from a quaternion. Note that this only works for a quaternion that represents a box in lidar or global coordinate frame. It does not work for a box in the camera frame. :param q: Quaternion of interest. :return: Yaw angle in...
Calculate the yaw angle from a quaternion. Note that this only works for a quaternion that represents a box in lidar or global coordinate frame. It does not work for a box in the camera frame. :param q: Quaternion of interest. :return: Yaw angle in radians.
quaternion_yaw
python
tianweiy/CenterPoint
det3d/datasets/nuscenes/nusc_common.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/nuscenes/nusc_common.py
MIT
def remove_close(points, radius: float) -> None: """ Removes point too close within a certain radius from origin. :param radius: Radius below which points are removed. """ x_filt = np.abs(points[0, :]) < radius y_filt = np.abs(points[1, :]) < radius not_close = np.logical_not(np.logical_and(...
Removes point too close within a certain radius from origin. :param radius: Radius below which points are removed.
remove_close
python
tianweiy/CenterPoint
det3d/datasets/pipelines/loading.py
https://github.com/tianweiy/CenterPoint/blob/master/det3d/datasets/pipelines/loading.py
MIT