response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Create an L{IWorker} that does nothing but defer work, to be performed
later.
@return: a worker that will enqueue work to perform later, and a callable
that will perform one element of that work.
@rtype: 2-L{tuple} of (L{IWorker}, L{callable}) | def createMemoryWorker():
"""
Create an L{IWorker} that does nothing but defer work, to be performed
later.
@return: a worker that will enqueue work to perform later, and a callable
that will perform one element of that work.
@rtype: 2-L{tuple} of (L{IWorker}, L{callable})
"""
def ... |
Construct a L{Team} that spawns threads as a thread pool, with the given
limiting function.
@note: Future maintainers: while the public API for the eventual move to
twisted.threads should look I{something} like this, and while this
function is necessary to implement the API described by
L{twisted.python.th... | def pool(
currentLimit: Callable[[], int], threadFactory: _ThreadFactory = Thread
) -> Team:
"""
Construct a L{Team} that spawns threads as a thread pool, with the given
limiting function.
@note: Future maintainers: while the public API for the eventual move to
twisted.threads should look I... |
Find package information from pip freeze output.
Match project name somewhat fuzzily (case sensitive; '-' matches '_', and
vice versa).
Return (normalized project name, installed version) if successful. | def get_installed_package_info(project: str) -> tuple[str, str] | None:
"""Find package information from pip freeze output.
Match project name somewhat fuzzily (case sensitive; '-' matches '_', and
vice versa).
Return (normalized project name, installed version) if successful.
"""
r = subproce... |
Create a METADATA.toml file. | def create_metadata(project: str, stub_dir: str, version: str) -> None:
"""Create a METADATA.toml file."""
match = re.match(r"[0-9]+.[0-9]+", version)
if match is None:
sys.exit(f"Error: Cannot parse version number: {version}")
filename = os.path.join(stub_dir, "METADATA.toml")
version = mat... |
Exclude stub_dir from strict pyright checks. | def add_pyright_exclusion(stub_dir: str) -> None:
"""Exclude stub_dir from strict pyright checks."""
with open(PYRIGHT_CONFIG, encoding="UTF-8") as f:
lines = f.readlines()
i = 0
while i < len(lines) and not lines[i].strip().startswith('"exclude": ['):
i += 1
assert i < len(lines), f... |
Given the old specifier and an updated version, returns an updated specifier that has the
specificity of the old specifier, but matches the updated version.
For example:
spec="1", version="1.2.3" -> "1.2.3"
spec="1.0.1", version="1.2.3" -> "1.2.3"
spec="1.*", version="1.2.3" -> "1.*"
spec="1.*", version="2.3.4" -> "2.... | def get_updated_version_spec(spec: str, version: packaging.version.Version) -> str:
"""
Given the old specifier and an updated version, returns an updated specifier that has the
specificity of the old specifier, but matches the updated version.
For example:
spec="1", version="1.2.3" -> "1.2.3"
... |
Check that given directory contains only valid Python files of a certain kind. | def assert_consistent_filetypes(
directory: Path, *, kind: str, allowed: set[str], allow_nonidentifier_filenames: bool = False
) -> None:
"""Check that given directory contains only valid Python files of a certain kind."""
allowed_paths = {Path(f) for f in allowed}
contents = list(directory.iterdir())
... |
Check that the stdlib directory contains only the correct files. | def check_stdlib() -> None:
"""Check that the stdlib directory contains only the correct files."""
assert_consistent_filetypes(Path("stdlib"), kind=".pyi", allowed={"_typeshed/README.md", "VERSIONS"}) |
Check that the stubs directory contains only the correct files. | def check_stubs() -> None:
"""Check that the stubs directory contains only the correct files."""
gitignore_spec = get_gitignore_spec()
for dist in Path("stubs").iterdir():
if spec_matches_path(gitignore_spec, dist):
continue
assert dist.is_dir(), f"Only directories allowed in st... |
Check whether all setuptools._distutils files are re-exported from distutils. | def check_distutils() -> None:
"""Check whether all setuptools._distutils files are re-exported from distutils."""
def all_relative_paths_in_directory(path: Path) -> set[Path]:
return {pyi.relative_to(path) for pyi in path.rglob("*.pyi")}
all_setuptools_files = all_relative_paths_in_directory(Path... |
Check that the test_cases directory contains only the correct files. | def check_test_cases() -> None:
"""Check that the test_cases directory contains only the correct files."""
for _, testcase_dir in get_all_testcase_directories():
assert_consistent_filetypes(testcase_dir, kind=".py", allowed={"README.md"}, allow_nonidentifier_filenames=True)
bad_test_case_filenam... |
Check that there are no symlinks in the typeshed repository. | def check_no_symlinks() -> None:
"""Check that there are no symlinks in the typeshed repository."""
files = [os.path.join(root, file) for root, _, files in os.walk(".") for file in files]
no_symlink = "You cannot use symlinks in typeshed, please copy {} to its link."
for file in files:
_, ext = ... |
Check that the stdlib/VERSIONS file has the correct format. | def check_versions_file() -> None:
"""Check that the stdlib/VERSIONS file has the correct format."""
versions = set[str]()
with open("stdlib/VERSIONS", encoding="UTF-8") as f:
data = f.read().splitlines()
for line in data:
line = strip_comments(line)
if line == "":
c... |
Check that all METADATA.toml files are valid. | def check_metadata() -> None:
"""Check that all METADATA.toml files are valid."""
for distribution in os.listdir("stubs"):
# This function does various sanity checks for METADATA.toml files
read_metadata(distribution) |
Check that type checkers and linters are pinned to an exact version. | def check_requirement_pins() -> None:
"""Check that type checkers and linters are pinned to an exact version."""
requirements = parse_requirements()
for package in linters:
assert package in requirements, f"type checker/linter '{package}' not found in {REQS_FILE}"
spec = requirements[package... |
Helper function for argument-parsing | def valid_path(cmd_arg: str) -> Path:
"""Helper function for argument-parsing"""
path = Path(cmd_arg)
if not path.exists():
raise argparse.ArgumentTypeError(f'"{path}" does not exist in typeshed!')
if not (path in DIRECTORIES_TO_TEST or any(directory in path.parents for directory in DIRECTORIES... |
Helper function for argument-parsing | def remove_dev_suffix(version: str) -> str:
"""Helper function for argument-parsing"""
if version.endswith("-dev"):
return version[: -len("-dev")]
return version |
Add all files in package or module represented by 'name' located in 'root'. | def add_files(files: list[Path], module: Path, args: TestConfig) -> None:
"""Add all files in package or module represented by 'name' located in 'root'."""
if module.is_file() and module.suffix == ".pyi":
if match(module, args):
files.append(module)
else:
files.extend(sorted(f... |
Test the stubs of a third-party distribution.
Return a tuple, where the first element indicates mypy's return code
and the second element is the number of checked files. | def test_third_party_distribution(
distribution: str, args: TestConfig, venv_dir: Path | None, *, non_types_dependencies: bool
) -> TestResult:
"""Test the stubs of a third-party distribution.
Return a tuple, where the first element indicates mypy's return code
and the second element is the number of c... |
Logic necessary for testing stubs with non-types dependencies in isolated environments. | def setup_virtual_environments(distributions: dict[str, PackageDependencies], args: TestConfig, tempdir: Path) -> None:
"""Logic necessary for testing stubs with non-types dependencies in isolated environments."""
if not distributions:
return # hooray! Nothing to do
# STAGE 1: Determine which (if ... |
Return an object describing the stubtest settings for a single stubs distribution. | def read_stubtest_settings(distribution: str) -> StubtestSettings:
"""Return an object describing the stubtest settings for a single stubs distribution."""
with Path("stubs", distribution, "METADATA.toml").open("rb") as f:
data: dict[str, object] = tomli.load(f).get("tool", {}).get("stubtest", {})
... |
Return an object describing the metadata of a stub as given in the METADATA.toml file.
This function does some basic validation,
but does no parsing, transforming or normalization of the metadata.
Use `read_dependencies` if you need to parse the dependencies
given in the `requires` field, for example. | def read_metadata(distribution: str) -> StubMetadata:
"""Return an object describing the metadata of a stub as given in the METADATA.toml file.
This function does some basic validation,
but does no parsing, transforming or normalization of the metadata.
Use `read_dependencies` if you need to parse the ... |
Read the dependencies listed in a METADATA.toml file for a stubs package.
Once the dependencies have been read,
determine which dependencies are typeshed-internal dependencies,
and which dependencies are external (non-types) dependencies.
For typeshed dependencies, translate the "dependency name" into the "package nam... | def read_dependencies(distribution: str) -> PackageDependencies:
"""Read the dependencies listed in a METADATA.toml file for a stubs package.
Once the dependencies have been read,
determine which dependencies are typeshed-internal dependencies,
and which dependencies are external (non-types) dependenci... |
Recursively gather dependencies for a single stubs package.
For example, if the stubs for `caldav`
declare a dependency on typeshed's stubs for `requests`,
and the stubs for requests declare a dependency on typeshed's stubs for `urllib3`,
`get_recursive_requirements("caldav")` will determine that the stubs for `caldav... | def get_recursive_requirements(package_name: str) -> PackageDependencies:
"""Recursively gather dependencies for a single stubs package.
For example, if the stubs for `caldav`
declare a dependency on typeshed's stubs for `requests`,
and the stubs for requests declare a dependency on typeshed's stubs fo... |
Runs pytype, returning the stderr if any. | def run_pytype(*, filename: str, python_version: str, missing_modules: Iterable[str]) -> str | None:
"""Runs pytype, returning the stderr if any."""
if python_version not in _LOADERS:
options = pytype_config.Options.create("", parse_pyi=True, python_version=python_version)
# For simplicity, pret... |
Converts a filename {subdir}/m.n/module/foo to module.foo. | def _get_module_name(filename: str) -> str:
"""Converts a filename {subdir}/m.n/module/foo to module.foo."""
parts = _get_relative(filename).split(os.path.sep)
if parts[0] == "stdlib":
module_parts = parts[1:]
else:
assert parts[0] == "stubs"
module_parts = parts[2:]
return ... |
Determine all files to test, checking if it's in the exclude list and which Python versions to use.
Returns a list of pairs of the file path and Python version as an int. | def determine_files_to_test(*, paths: Sequence[str]) -> list[str]:
"""Determine all files to test, checking if it's in the exclude list and which Python versions to use.
Returns a list of pairs of the file path and Python version as an int."""
filenames = find_stubs_in_paths(paths)
ts = typeshed.Typesh... |
Get names of modules that should be treated as missing.
Some typeshed stubs depend on dependencies outside of typeshed. Since pytype
isn't able to read such dependencies, we instead declare them as "missing"
modules, so that no errors are reported for them.
Similarly, pytype cannot parse files on its exclude list, so... | def get_missing_modules(files_to_test: Sequence[str]) -> Iterable[str]:
"""Get names of modules that should be treated as missing.
Some typeshed stubs depend on dependencies outside of typeshed. Since pytype
isn't able to read such dependencies, we instead declare them as "missing"
modules, so that no ... |
Helper function for argument-parsing | def package_with_test_cases(package_name: str) -> PackageInfo:
"""Helper function for argument-parsing"""
if package_name == "stdlib":
return PackageInfo("stdlib", Path(TEST_CASES))
test_case_dir = testcase_dir_from_package_name(package_name)
if test_case_dir.is_dir():
if not os.listdi... |
Use wrapper scripts to run stubtest inside gdb.
The wrapper script is used to pass the arguments to the gdb script. | def setup_gdb_stubtest_command(venv_dir: Path, stubtest_cmd: list[str]) -> bool:
"""
Use wrapper scripts to run stubtest inside gdb.
The wrapper script is used to pass the arguments to the gdb script.
"""
if sys.platform == "win32":
print_error("gdb is not supported on Windows")
retu... |
Perform some black magic in order to run stubtest inside uWSGI.
We have to write the exit code from stubtest to a surrogate file
because uwsgi --pyrun does not exit with the exitcode from the
python script. We have a second wrapper script that passed the
arguments along to the uWSGI script and retrieves the exit code
... | def setup_uwsgi_stubtest_command(dist: Path, venv_dir: Path, stubtest_cmd: list[str]) -> bool:
"""Perform some black magic in order to run stubtest inside uWSGI.
We have to write the exit code from stubtest to a surrogate file
because uwsgi --pyrun does not exit with the exitcode from the
python script... |
Print a row of * symbols across the screen.
This can be useful to divide terminal output into separate sections. | def print_divider() -> None:
"""Print a row of * symbols across the screen.
This can be useful to divide terminal output into separate sections.
"""
print()
print("*" * 70)
print() |
Return a dictionary of requirements from the requirements file. | def parse_requirements() -> Mapping[str, Requirement]:
"""Return a dictionary of requirements from the requirements file."""
with open(REQS_FILE, encoding="UTF-8") as requirements_file:
stripped_lines = map(strip_comments, requirements_file)
requirements = map(Requirement, filter(None, stripped... |
See issue #9591 | def check_search_with_AnyStr(pattern: re.Pattern[t.AnyStr], string: t.AnyStr) -> re.Match[t.AnyStr]:
"""See issue #9591"""
match = pattern.search(string)
if match is None:
raise ValueError(f"'{string!r}' does not match {pattern!r}")
return match |
Return first n items of the iterable as a list | def take(n: int, iterable: Iterable[_T]) -> list[_T]:
"Return first n items of the iterable as a list"
return list(islice(iterable, n)) |
Prepend a single value in front of an iterator | def prepend(value: _T1, iterator: Iterable[_T2]) -> Iterator[_T1 | _T2]:
"Prepend a single value in front of an iterator"
# prepend(1, [2, 3, 4]) --> 1 2 3 4
return chain([value], iterator) |
Return function(0), function(1), ... | def tabulate(function: Callable[[int], _T], start: int = 0) -> Iterator[_T]:
"Return function(0), function(1), ..."
return map(function, count(start)) |
Repeat calls to func with specified arguments.
Example: repeatfunc(random.random) | def repeatfunc(func: Callable[[Unpack[_Ts]], _T], times: int | None = None, *args: Unpack[_Ts]) -> Iterator[_T]:
"""Repeat calls to func with specified arguments.
Example: repeatfunc(random.random)
"""
if times is None:
return starmap(func, repeat(args))
return starmap(func, repeat(args, t... |
Flatten one level of nesting | def flatten(list_of_lists: Iterable[Iterable[_T]]) -> Iterator[_T]:
"Flatten one level of nesting"
return chain.from_iterable(list_of_lists) |
Returns the sequence elements n times | def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]:
"Returns the sequence elements n times"
return chain.from_iterable(repeat(tuple(iterable), n)) |
Return an iterator over the last n items | def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]:
"Return an iterator over the last n items"
# tail(3, 'ABCDEFG') --> E F G
return iter(collections.deque(iterable, maxlen=n)) |
Advance the iterator n-steps ahead. If n is None, consume entirely. | def consume(iterator: Iterator[object], n: int | None = None) -> None:
"Advance the iterator n-steps ahead. If n is None, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen... |
Returns the nth item or a default value | def nth(iterable: Iterable[object], n: int, default: object = None) -> object:
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default) |
Given a predicate that returns True or False, count the True results. | def quantify(iterable: Iterable[object], pred: Callable[[Any], bool] = bool) -> int:
"Given a predicate that returns True or False, count the True results."
return sum(map(pred, iterable)) |
Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true. | def first_true(iterable: Iterable[object], default: object = False, pred: Callable[[Any], bool] | None = None) -> object:
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
... |
Call a function repeatedly until an exception is raised.
Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Examples:
iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator
... | def iter_except(
func: Callable[[], object], exception: _ExceptionOrExceptionTuple, first: Callable[[], object] | None = None
) -> Iterator[object]:
"""Call a function repeatedly until an exception is raised.
Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, se... |
roundrobin('ABC', 'D', 'EF') --> A D E B F C | def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]:
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts: Iterator[Callable[[], _T]] = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for nex... |
Partition entries into false entries and true entries.
If *pred* is slow, consider wrapping it with functools.lru_cache(). | def partition(pred: Callable[[_T], bool], iterable: Iterable[_T]) -> tuple[Iterator[_T], Iterator[_T]]:
"""Partition entries into false entries and true entries.
If *pred* is slow, consider wrapping it with functools.lru_cache().
"""
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, ... |
Return all contiguous non-empty subslices of a sequence | def subslices(seq: Sequence[_T]) -> Iterator[Sequence[_T]]:
"Return all contiguous non-empty subslices of a sequence"
# subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D
slices = starmap(slice, combinations(range(len(seq) + 1), 2))
return map(operator.getitem, repeat(seq), slices) |
Variant of takewhile() that allows complete
access to the remainder of the iterator.
>>> it = iter('ABCdEfGhI')
>>> all_upper, remainder = before_and_after(str.isupper, it)
>>> ''.join(all_upper)
'ABC'
>>> ''.join(remainder) # takewhile() would lose the 'd'
'dEfGhI'
Note that the first iterator must be fully
consum... | def before_and_after(predicate: Callable[[_T], bool], it: Iterable[_T]) -> tuple[Iterator[_T], Iterator[_T]]:
"""Variant of takewhile() that allows complete
access to the remainder of the iterator.
>>> it = iter('ABCdEfGhI')
>>> all_upper, remainder = before_and_after(str.isupper, it)
>>> ''.join(al... |
List unique elements, preserving order. Remember all elements ever seen. | def unique_everseen(iterable: Iterable[_T], key: Callable[[_T], Hashable] | None = None) -> Iterator[_T]:
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBcCAD', str.lower) --> A B c D
seen: set[Hashable] = ... |
List unique elements, preserving order. Remember only the element just seen. | def unique_justseen(iterable: Iterable[_T], key: Callable[[_T], bool] | None = None) -> Iterator[_T]:
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBcCAD', str.lower) --> A B c A D
g: groupby[_T | ... |
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) | def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]:
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) |
Compute the first derivative of a polynomial.
f(x) = x³ -4x² -17x + 60
f'(x) = 3x² -8x -17 | def polynomial_derivative(coefficients: Sequence[float]) -> list[float]:
"""Compute the first derivative of a polynomial.
f(x) = x³ -4x² -17x + 60
f'(x) = 3x² -8x -17
"""
# polynomial_derivative([1, -4, -17, 60]) -> [3, -8, -17]
n = len(coefficients)
powers = reversed(range(1, n))
ret... |
Equivalent to list(combinations(iterable, r))[index] | def nth_combination(iterable: Iterable[_T], r: int, index: int) -> tuple[_T, ...]:
"Equivalent to list(combinations(iterable, r))[index]"
pool = tuple(iterable)
n = len(pool)
c = math.comb(n, r)
if index < 0:
index += c
if index < 0 or index >= c:
raise IndexError
result: li... |
Create an indexer for the given application.
:param app: The name of the application to create an indexer for.
:param docs: The help documents dir for the application.
:param format: The format of the help documents.
:param incremental: Whether to enable incremental updates.
:param save_path: The path to save the index... | def create_indexer(app: str, docs: str, format: str, incremental: bool, save_path: str):
"""
Create an indexer for the given application.
:param app: The name of the application to create an indexer for.
:param docs: The help documents dir for the application.
:param format: The format of the help d... |
Main function. | def main():
"""
Main function.
"""
indexer.create_indexer(parsed_args.app, parsed_args.docs, parsed_args.format, parsed_args.incremental, parsed_args.save_path) |
Print text with specified color using ANSI escape codes from Colorama library.
:param text: The text to print.
:param color: The color of the text (options: red, green, yellow, blue, magenta, cyan, white, black). | def print_with_color(text: str, color: str = ""):
"""
Print text with specified color using ANSI escape codes from Colorama library.
:param text: The text to print.
:param color: The color of the text (options: red, green, yellow, blue, magenta, cyan, white, black).
"""
color_mapping = {
... |
Find files with the given extension in the given directory.
:param directory: The directory to search.
:param extension: The extension to search for.
:return: The list of matching files. | def find_files_with_extension(directory, extension):
"""
Find files with the given extension in the given directory.
:param directory: The directory to search.
:param extension: The extension to search for.
:return: The list of matching files.
"""
matching_files = []
for root, _, fi... |
Find files with the given extensions in the given directory.
:param directory: The directory to search.
:param extensions: The list of extensions to search for.
:return: The list of matching files. | def find_files_with_extension_list(directory, extensions):
"""
Find files with the given extensions in the given directory.
:param directory: The directory to search.
:param extensions: The list of extensions to search for.
:return: The list of matching files.
"""
matching_files = []
... |
Load a JSON file.
:param file_path: The path to the file to load.
:return: The loaded JSON data. | def load_json_file(file_path):
"""
Load a JSON file.
:param file_path: The path to the file to load.
:return: The loaded JSON data.
"""
with open(file_path, 'r') as file:
data = json.load(file)
return data |
Save a JSON file.
:param file_path: The path to the file to save. | def save_json_file(file_path, data):
"""
Save a JSON file.
:param file_path: The path to the file to save.
"""
with open(file_path, 'w') as file:
json.dump(data, file, indent=4) |
Main function. | def main():
"""
Main function.
"""
session = flow.Session(parsed_args.task)
step = 0
status = session.get_status()
round = session.get_round()
# Start the task
while status.upper() not in ["ALLFINISH", "ERROR", "MAX_STEP_REACHED"]:
round = session.get_round()
... |
Load the configuration from a YAML file and environment variables.
:param config_path: The path to the YAML config file. Defaults to "./config.yaml".
:return: Merged configuration from environment variables and YAML file. | def load_config(config_path="ufo/config/"):
"""
Load the configuration from a YAML file and environment variables.
:param config_path: The path to the YAML config file. Defaults to "./config.yaml".
:return: Merged configuration from environment variables and YAML file.
"""
# Copy environment va... |
Get the list of offline indexers obtained from the learner.
:return: The list of offline indexers. | def get_offline_learner_indexer_config():
"""
Get the list of offline indexers obtained from the learner.
:return: The list of offline indexers.
"""
# The fixed path of the offline indexer config file.
file_path = "learner/records.json"
if os.path.exists(file_path):
with open(file_p... |
Get completion for the given messages.
Args:
messages (list): List of messages to be used for completion.
agent (str, optional): Type of agent. Possible values are 'APP', 'ACTION' or 'BACKUP'.
use_backup_engine (bool, optional): Flag indicating whether to use the backup engine or not.
Returns:
tuple: ... | def get_completion(messages, agent: str='APP', use_backup_engine: bool=True):
"""
Get completion for the given messages.
Args:
messages (list): List of messages to be used for completion.
agent (str, optional): Type of agent. Possible values are 'APP', 'ACTION' or 'BACKUP'.
use_back... |
Get titles and control types of all the apps on the desktop.
:param remove_empty: Whether to remove empty titles.
:return: The titles and control types of all the apps on the desktop. | def get_desktop_app_info(remove_empty:bool=True) -> Tuple[dict, List[dict]]:
"""
Get titles and control types of all the apps on the desktop.
:param remove_empty: Whether to remove empty titles.
:return: The titles and control types of all the apps on the desktop.
"""
app_list = Desktop(backend=... |
Get titles and control types of all the apps on the desktop.
:param remove_empty: Whether to remove empty titles.
:return: The titles and control types of all the apps on the desktop. | def get_desktop_app_info_dict(remove_empty:bool=True, field_list:List[str]=["control_text", "control_type"]) -> Tuple[dict, List[dict]]:
"""
Get titles and control types of all the apps on the desktop.
:param remove_empty: Whether to remove empty titles.
:return: The titles and control types of all the ... |
Find control elements in descendants of the window.
:param window: The window to find control elements.
:param control_type_list: The control types to find.
:param class_name_list: The class names to find.
:param title_list: The titles to find.
:param is_visible: Whether the control elements are visible.
:param is_enab... | def find_control_elements_in_descendants(window, control_type_list:List[str]=[], class_name_list:List[str]=[], title_list:List[str]=[], is_visible:bool=True, is_enabled:bool=True, depth:int=0) -> List:
"""
Find control elements in descendants of the window.
:param window: The window to find control elements... |
Get control info of the window.
:param window: The window to get control info.
:param field_list: The fields to get.
return: The control info of the window. | def get_control_info(window, field_list:List[str]=[]) -> dict:
"""
Get control info of the window.
:param window: The window to get control info.
:param field_list: The fields to get.
return: The control info of the window.
"""
control_info = {}
try:
control_info["control_type"] ... |
Get control info of the window.
:param window: The list of windows to get control info.
:param field_list: The fields to get.
return: The list of control info of the window. | def get_control_info_batch(window_list:List, field_list:List[str]=[]) -> List:
"""
Get control info of the window.
:param window: The list of windows to get control info.
:param field_list: The fields to get.
return: The list of control info of the window.
"""
control_info_list = []
for ... |
Get control info of the window.
:param window: The list of windows to get control info.
:param field_list: The fields to get.
return: The list of control info of the window. | def get_control_info_dict(window_dict:dict, field_list:List[str]=[]) -> List[dict]:
"""
Get control info of the window.
:param window: The list of windows to get control info.
:param field_list: The fields to get.
return: The list of control info of the window.
"""
control_info_list = []
... |
Replace
with \n.
:param input_str: The string to replace.
:return: The replaced string.
| def replace_newline(input_str : str) -> str:
"""
Replace \n with \\n.
:param input_str: The string to replace.
:return: The replaced string.
"""
# Replace \n with \\n
result_str = input_str.replace('\n', '\\n')
# Check if there are already \\n in the string
if '\\\\n' in result_str:... |
Get the application name of the window.
:param window: The window to get the application name.
:return: The application name of the window. Empty string ("") if failed to get the name. | def get_application_name(window) -> str:
"""
Get the application name of the window.
:param window: The window to get the application name.
:return: The application name of the window. Empty string ("") if failed to get the name.
"""
if window == None:
return ""
process_id = window.p... |
Capture a screenshot of the window.
:param window_title: The title of the window.
:param save_path: The path to save the screenshot.
:param is_save: Whether to save the screenshot.
:return: The screenshot. | def capture_screenshot(window_title:str, save_path:str, is_save:bool=True):
"""
Capture a screenshot of the window.
:param window_title: The title of the window.
:param save_path: The path to save the screenshot.
:param is_save: Whether to save the screenshot.
:return: The screenshot.
"""
... |
Capture a screenshot of the window.
:param window_title: The title of the window.
:param save_path: The path to save the screenshot.
:param is_save: Whether to save the screenshot.
:return: The screenshot. | def capture_screenshot(window_title:str, save_path:str, is_save:bool=True):
"""
Capture a screenshot of the window.
:param window_title: The title of the window.
:param save_path: The path to save the screenshot.
:param is_save: Whether to save the screenshot.
:return: The screenshot.
"""
... |
Capture a screenshot of the multi-screen. | def capture_screenshot_multiscreen(save_path:str):
"""
Capture a screenshot of the multi-screen.
"""
screenshot = ImageGrab.grab(all_screens=True)
screenshot.save(save_path)
return screenshot |
Draw a rectangle on the image.
:param image: The image to draw on.
:param coordinate: The coordinate of the rectangle.
:param color: The color of the rectangle.
:param width: The width of the rectangle.
:return: The image with the rectangle. | def draw_rectangles(image, coordinate:tuple, color="red", width=3):
"""
Draw a rectangle on the image.
:param image: The image to draw on.
:param coordinate: The coordinate of the rectangle.
:param color: The color of the rectangle.
:param width: The width of the rectangle.
:return: The imag... |
Capture a screenshot with rectangles around the controls.
:param top_window: The top window.
:param control_list: The list of the controls to annotate.
:param save_path: The path to save the screenshot.
:param color: The color of the rectangle.
:param is_save: Whether to save the screenshot.
:return: The screenshot wit... | def capture_screenshot_controls(top_window, control_list: List, save_path:str, color="red", is_save:bool=True):
"""
Capture a screenshot with rectangles around the controls.
:param top_window: The top window.
:param control_list: The list of the controls to annotate.
:param save_path: The path to sa... |
Adjust the coordinates of the control rectangle to the window rectangle.
:param window_rect: The window rectangle.
:param control_rect: The control rectangle.
:return: The adjusted control rectangle. | def coordinate_adjusted(window_rect:RECT, control_rect:RECT):
"""
Adjust the coordinates of the control rectangle to the window rectangle.
:param window_rect: The window rectangle.
:param control_rect: The control rectangle.
:return: The adjusted control rectangle.
"""
# (left, top, right, b... |
Draw a rectangle around the control and label it.
:param image: The image to draw on.
:param save_path: The path to save the screenshot.
:param coordinate: The coordinate of the control.
:param label_text: The text label of the control.
:param botton_margin: The margin of the button.
:param border_width: The width of t... | def draw_rectangles_controls(image, coordinate:tuple, label_text:str, botton_margin:int=5, border_width:int=2, font_size:int=25,
font_color:str="#000000", border_color:str="#FF0000", button_color:str="#FFF68F"):
"""
Draw a rectangle around the control and label it.
:param image... |
Annotate the controls of the window.
:param window_title: The title of the window.
:param screenshot_save_path: The path to save the screenshot.
:param annotated_screenshot_save_path: The path to save the annotated screenshot.
:param control_list: The list of the controls to annotate.
:param anntation_type: The type of... | def control_annotations(window:str, screenshot_save_path:str, annotated_screenshot_save_path:str, control_list:List, anntation_type:str="number",
color_diff:bool=True, color_default:str="#FFF68F", is_save:bool=True):
"""
Annotate the controls of the window.
:param window_title: The... |
Concatenate two images horizontally.
:param image1_path: The path of the first image.
:param image2_path: The path of the second image.
:param output_path: The path to save the concatenated image.
:return: The concatenated image. | def concat_images_left_right(image1_path, image2_path, output_path):
"""
Concatenate two images horizontally.
:param image1_path: The path of the first image.
:param image2_path: The path of the second image.
:param output_path: The path to save the concatenated image.
:return: The concatenated ... |
Print text with specified color using ANSI escape codes from Colorama library.
:param text: The text to print.
:param color: The color of the text (options: red, green, yellow, blue, magenta, cyan, white, black). | def print_with_color(text: str, color: str = ""):
"""
Print text with specified color using ANSI escape codes from Colorama library.
:param text: The text to print.
:param color: The color of the text (options: red, green, yellow, blue, magenta, cyan, white, black).
"""
color_mapping = {
... |
Convert image to base64 string.
:param image: The image to convert.
:return: The base64 string. | def image_to_base64(image: Image):
"""
Convert image to base64 string.
:param image: The image to convert.
:return: The base64 string.
"""
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8") |
Encode an image file to base64 string.
:param image_path: The path of the image file.
:param mime_type: The mime type of the image.
:return: The base64 string. | def encode_image_from_path(image_path: str, mime_type: Optional[str] = None) -> str:
"""
Encode an image file to base64 string.
:param image_path: The path of the image file.
:param mime_type: The mime type of the image.
:return: The base64 string.
"""
import mimetypes
file_name = os.pat... |
Create a folder if it doesn't exist.
:param folder_path: The path of the folder to create. | def create_folder(folder_path: str):
"""
Create a folder if it doesn't exist.
:param folder_path: The path of the folder to create.
"""
if not os.path.exists(folder_path):
os.makedirs(folder_path) |
Convert number to letter.
:param n: The number to convert.
:return: The letter converted from the number. | def number_to_letter(n:int):
"""
Convert number to letter.
:param n: The number to convert.
:return: The letter converted from the number.
"""
if n < 0:
return "Invalid input"
result = ""
while n >= 0:
remainder = n % 26
result = chr(65 + remainder) + result ... |
Check if the string can be correctly parse by json.
:param string: The string to check.
:return: True if the string can be correctly parse by json, False otherwise. | def check_json_format(string:str):
"""
Check if the string can be correctly parse by json.
:param string: The string to check.
:return: True if the string can be correctly parse by json, False otherwise.
"""
import json
try:
json.loads(string)
except ValueError:
return Fa... |
Ask for user input until the user enters either Y or N.
:return: The user input. | def yes_or_no():
"""
Ask for user input until the user enters either Y or N.
:return: The user input.
"""
while True:
user_input = input().upper()
if user_input == 'Y':
return True
elif user_input == 'N':
return False
else:
print(... |
Parse json string to json object.
:param json_string: The json string to parse.
:return: The json object. | def json_parser(json_string:str):
"""
Parse json string to json object.
:param json_string: The json string to parse.
:return: The json object.
"""
# Remove the ```json and ``` at the beginning and end of the string if exists.
if json_string.startswith("```json"):
json_string = json... |
Generate a function call string.
:param func: The function name.
:param args: The arguments as a dictionary.
:return: The function call string. | def generate_function_call(func, args):
"""
Generate a function call string.
:param func: The function name.
:param args: The arguments as a dictionary.
:return: The function call string.
"""
# Format the arguments
args_str = ', '.join(f'{k}={v!r}' for k, v in args.items())
# Return... |
Replace '\n' with '
' in the arguments.
:param args: The arguments.
:return: The arguments with \n replaced with
.
| def revise_line_breaks(args: dict):
"""
Replace '\\n' with '\n' in the arguments.
:param args: The arguments.
:return: The arguments with \\n replaced with \n.
"""
# Replace \\n with \\n
for key in args.keys():
if isinstance(args[key], str):
args[key] = args[key].replace... |
Add time in milliseconds to global ringbuffer.
Locates the event device (/dev/input/*) in the dict of ringbuffers and adds
the KEY_DOWN time in milliseconds to it. Then calls the check_for_attack
function on the event device and the usb core device.
Args:
event_device_path: The path to the event device (/dev/input/... | def add_to_ring_buffer(event_device_path: Text, key_down_time: int,
keystroke: Text, device: usb.core.Device):
"""Add time in milliseconds to global ringbuffer.
Locates the event device (/dev/input/*) in the dict of ringbuffers and adds
the KEY_DOWN time in milliseconds to it. Then calls t... |
Check local (user-based) allowlist for specifically allowed devices.
UKIP users are able to specify USB devices they want to allow in a local
file. This allowlist is checked, when a device is found attacking (timing
threshold is exceeded) and whether that device is listed in here. If so, only
the characters listed in ... | def check_local_allowlist(product_id: Text,
vendor_id: Text) -> AllowlistConfigReturn:
"""Check local (user-based) allowlist for specifically allowed devices.
UKIP users are able to specify USB devices they want to allow in a local
file. This allowlist is checked, when a device is found... |
Check a ringbuffer of KEY_DOWN timings for attacks.
Locates the event device (/dev/input/*) in the dict of ringbuffers and checks
the correct ringbuffer for attacks (keystroke injection attack). In case of
an attack, two actions can be taken, depending on the mode UKIP is running in.
Those modes are specified in the U... | def check_for_attack(event_device_path: Text, device: usb.core.Device) -> bool:
"""Check a ringbuffer of KEY_DOWN timings for attacks.
Locates the event device (/dev/input/*) in the dict of ringbuffers and checks
the correct ringbuffer for attacks (keystroke injection attack). In case of
an attack, two actions... |
Enforce the MONITOR mode on a given device.
Information about devices, that would have been blocked in HARDENING mode
is logged to /dev/log.
Args:
device: A USB device (usb.core.Device).
event_device_path: The path to the event device (/dev/input/*). | def enforce_monitor_mode(device: usb.core.Device, event_device_path: Text):
"""Enforce the MONITOR mode on a given device.
Information about devices, that would have been blocked in HARDENING mode
is logged to /dev/log.
Args:
device: A USB device (usb.core.Device).
event_device_path: The path to the e... |
Enforce the HARDENING mode on a given device.
When enforcing the HARDENING mode, a device gets removed from the operating
system when the keystrokes exceed the typing speed threshold
(ABNORMAL_TYPING). This is done by unbinding the drivers from every device
interface. Before the device is removed, the allowlist is che... | def enforce_hardening_mode(device: usb.core.Device, event_device_path: Text):
"""Enforce the HARDENING mode on a given device.
When enforcing the HARDENING mode, a device gets removed from the operating
system when the keystrokes exceed the typing speed threshold
(ABNORMAL_TYPING). This is done by unbinding th... |
Helper function to load the keycodes file into memory.
Returns:
The lowcodes and capscodes as dicts in a KeycodesReturn attribute.
Raises:
KeycodesFileError: If there is a problem with the keycodes file. | def load_keycodes_from_file() -> KeycodesReturn:
"""Helper function to load the keycodes file into memory.
Returns:
The lowcodes and capscodes as dicts in a KeycodesReturn attribute.
Raises:
KeycodesFileError: If there is a problem with the keycodes file.
"""
lowcodes = {}
capscodes = {}
try:
... |
Monitor a given USB device for occurring KEY_DOWN events.
Creates a passive reading loop over a given event device and waits for
KEY_DOWN events to occour. Then extracts the time in milliseconds of the event
and adds it to the ringbuffer.
Args:
device: The event device in (/dev/input/*).
vendor_id: The vendor ID ... | def monitor_device_thread(device: pyudev.Device, vendor_id: int,
product_id: int) -> None:
"""Monitor a given USB device for occurring KEY_DOWN events.
Creates a passive reading loop over a given event device and waits for
KEY_DOWN events to occour. Then extracts the time in millisecond... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.