id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
150,690
from typing import Optional, Union, Tuple, List, Literal, Sequence, Callable import torch import math import ivy from ivy.func_wrapper import with_unsupported_dtypes, with_supported_dtypes from . import backend_version from ivy.functional.ivy.layers import ( _handle_padding, _get_num_padded_values, _validat...
null
150,691
from typing import Optional, Union, Tuple, List, Literal, Sequence, Callable import torch import math import ivy from ivy.func_wrapper import with_unsupported_dtypes, with_supported_dtypes from . import backend_version from ivy.functional.ivy.layers import ( _handle_padding, _get_num_padded_values, _validat...
null
150,692
def if_else(cond, body_fn, orelse_fn, vars): # back-compatibility if isinstance(cond, bool): v = cond def cond(*_): return v if callable(cond): cond = cond(**vars) else: cond = bool(cond) if cond: return body_fn(**vars) else: return...
null
150,693
def while_loop(test_fn, body_fn, vars): if isinstance(vars, dict): result = list(vars.values()) else: result = list(vars) while test_fn(*result) is True: result = body_fn(*result) if not isinstance(result, tuple): result = (result,) return result
null
150,694
import torch from typing import Tuple, Optional from collections import namedtuple from ivy.func_wrapper import with_unsupported_dtypes from . import backend_version import ivy import ivy from ivy.utils.exceptions import handle_exceptions from ivy.functional.frontends import set_frontend_to_specific_version ...
null
150,695
import torch from typing import Tuple, Optional from collections import namedtuple from ivy.func_wrapper import with_unsupported_dtypes from . import backend_version import ivy def unique_counts(x: torch.Tensor, /) -> Tuple[torch.Tensor, torch.Tensor]: v, c = torch.unique(torch.reshape(x, [-1]), return_counts=True...
null
150,696
import torch from typing import Tuple, Optional from collections import namedtuple from ivy.func_wrapper import with_unsupported_dtypes from . import backend_version import ivy def unique_inverse( x: torch.Tensor, /, *, axis: Optional[int] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: Results = n...
null
150,697
import torch from typing import Tuple, Optional from collections import namedtuple from ivy.func_wrapper import with_unsupported_dtypes from . import backend_version import ivy def unique_values( x: torch.Tensor, /, *, out: Optional[torch.Tensor] = None ) -> torch.Tensor: return torch.unique(x)
null
150,698
from typing import get_type_hints import ivy def fn_array_spec(fn): def add_array_specs(): for k, v in ivy.__dict__.items(): if callable(v) and k[0].islower(): v.array_spec = fn_array_spec(v)
null
150,699
import ivy from importlib import import_module as builtin_import def import_module(name, package=None): if ivy.is_local(): with ivy.utils._importlib.LocalIvyImporter(): return ivy.utils._importlib._import_module(name=name, package=package) return builtin_import(name=name, package=package)
null
150,700
import logging logging_modes = ["DEBUG", "INFO", "WARNING", "ERROR"] logging.basicConfig(level=logging.WARNING) logging_mode_stack = [logging.WARNING] import logging logging.basicConfig(level=logging.WARNING) The provided code snippet includes necessary dependencies for implementing the `set_logging_mode` function. ...
Set the current logging mode for Ivy. Possible modes are 'DEBUG', 'INFO', 'WARNING', 'ERROR'.
150,701
import logging logging.basicConfig(level=logging.WARNING) logging_mode_stack = [logging.WARNING] import logging logging.basicConfig(level=logging.WARNING) The provided code snippet includes necessary dependencies for implementing the `unset_logging_mode` function. Write a Python function `def unset_logging_mode()` t...
Remove the most recently set logging mode, returning to the previous one.
150,702
import itertools from typing import Any, Dict, Iterator, List, Tuple, Union import numpy as np def is_valid_einsum_char(x: str) -> bool: """Check if the character ``x`` is valid for numpy einsum. **Examples:** ```python is_valid_einsum_char("a") #> True is_valid_einsum_char("Ǵ") #> False ```...
Check if ``einsum_str`` contains only valid characters for numpy einsum. **Examples:** ```python has_valid_einsum_chars_only("abAZ") #> True has_valid_einsum_chars_only("Över") #> False ```
150,703
import itertools from typing import Any, Dict, Iterator, List, Tuple, Union import numpy as np TensorShapeType = Tuple[int, ...] The provided code snippet includes necessary dependencies for implementing the `find_output_shape` function. Write a Python function `def find_output_shape( inputs: List[str], shapes: Li...
Find the output shape for given inputs, shapes and output string, taking into account broadcasting. Examples -------- >>> oe.parser.find_output_shape(["ab", "bc"], [(2, 3), (3, 4)], "ac") (2, 4) # Broadcasting is accounted for >>> oe.parser.find_output_shape(["a", "a"], [(4, ), (1, )], "a") (4,)
150,704
import warnings import ivy import functools from typing import Callable import traceback as tb import inspect import os import ast import builtins def _align_source(st, transpile_frame, module_frame, module_st, traced_lineno): from ivy.compiler.utils.VVX import trace_obj from ivy.compiler.utils.IIV import Graph...
null
150,705
import warnings import ivy import functools from typing import Callable import traceback as tb import inspect import os import ast import builtins def _add_native_error(default): """Append the native error to the message if it exists. Parameters ---------- default list containing all the message...
null
150,706
import warnings import ivy import functools from typing import Callable import traceback as tb import inspect import os import ast import builtins def _configure_stack_trace(traceback): """Configure the stack trace to be displayed in the console. Parameters ---------- traceback the traceback obj...
null
150,707
import os import logging import json from packaging import tags from urllib import request from tqdm import tqdm def _get_paths_from_binaries(binaries, root_dir=""): """Get all the paths from the binaries.json into a list.""" paths = [] ext = "pyd" if os.name == "nt" else "so" if isinstance(binaries, st...
null
150,708
import os import logging import json from packaging import tags from urllib import request from tqdm import tqdm def _get_paths_from_binaries(binaries, root_dir=""): """Get all the paths from the binaries.json into a list.""" paths = [] ext = "pyd" if os.name == "nt" else "so" if isinstance(binaries, st...
null
150,709
import ivy def _broadcast_inputs(x1, x2): def check_less(x1, x2, allow_equal=False, message="", as_array=True): def comp_fn(x1, x2): return ivy.any(x1 > x2), ivy.any(x1 >= x2) if not as_array: def iter_comp_fn(x1_, x2_): return any(x1 > x2 for x1, x2 in zip(x1_, x2_)), any( ...
null
150,710
import ivy def _broadcast_inputs(x1, x2): x1_, x2_ = x1, x2 iterables = (list, tuple, ivy.Shape) if not isinstance(x1_, iterables): x1_, x2_ = x2, x1 if not isinstance(x1_, iterables): return [x1], [x2] if not isinstance(x2_, iterables): x1 = [x1] * len(x2) return x1, x2 ...
null
150,711
import ivy def check_isinstance(x, allowed_types, message=""): if not isinstance(x, allowed_types): raise ivy.utils.exceptions.IvyException( f"type of x: {type(x)} must be one of the allowed types: {allowed_types}" if message == "" else message )
null
150,712
import ivy def check_exists(x, inverse=False, message=""): # not_exists if inverse and ivy.exists(x): raise ivy.utils.exceptions.IvyException( "arg must be None" if message == "" else message ) # exists elif not inverse and not ivy.exists(x): raise ivy.utils.exceptio...
null
150,713
import ivy def check_true(expression, message="expression must be True"): if not expression: raise ivy.utils.exceptions.IvyException(message)
null
150,714
import ivy def check_false(expression, message="expression must be False"): if expression: raise ivy.utils.exceptions.IvyException(message)
null
150,715
import ivy def check_any(results, message="all of the args are False", as_array=True): if (as_array and not ivy.any(results)) or (not as_array and not any(results)): raise ivy.utils.exceptions.IvyException(message)
null
150,716
import ivy def check_all(results, message="one of the args is False", as_array=True): def check_all_or_any_fn( *args, fn, type="all", limit=(0,), message="args must exist according to type and limit given", as_array=True, ): if type == "all": check_all([fn(arg) for arg in args], mes...
null
150,717
import ivy def check_shape(x1, x2, message=""): message = ( message if message != "" else ( f"{x1} and {x2} must have the same shape ({ivy.shape(x1)} vs" f" {ivy.shape(x2)})" ) ) if ivy.shape(x1)[:] != ivy.shape(x2)[:]: raise ivy.utils.excepti...
null
150,718
import ivy def check_same_dtype(x1, x2, message=""): if ivy.dtype(x1) != ivy.dtype(x2): message = ( message if message != "" else ( f"{x1} and {x2} must have the same dtype ({ivy.dtype(x1)} vs" f" {ivy.dtype(x2)})" ) ) ...
null
150,719
import ivy def check_unsorted_segment_valid_params(data, segment_ids, num_segments): if not isinstance(num_segments, int): raise TypeError("num_segments must be of integer type") valid_dtypes = [ ivy.int32, ivy.int64, ] if ivy.backend == "torch": import torch ...
null
150,720
import ivy def check_gather_input_valid(params, indices, axis, batch_dims): if batch_dims > axis: raise ivy.utils.exceptions.IvyException( f"batch_dims ({batch_dims}) must be less than or equal to axis ({axis})." ) if params.shape[0:batch_dims] != indices.shape[0:batch_dims]: ...
null
150,721
import ivy def check_gather_nd_input_valid(params, indices, batch_dims): if batch_dims >= len(params.shape): raise ivy.utils.exceptions.IvyException( f"batch_dims = {batch_dims} must be less than rank(`params`) =" f" {len(params.shape)}." ) if batch_dims >= len(indices.s...
null
150,722
import ivy def check_one_way_broadcastable(x1, x2): def check_inplace_sizes_valid(var, data): if not check_one_way_broadcastable(data.shape, var.shape): raise ivy.utils.exceptions.IvyException( f"Could not output values of shape {var.shape} into array with shape" f" {data.shape}." ...
null
150,723
import ivy def check_one_way_broadcastable(x1, x2): if len(x1) > len(x2): return False for a, b in zip(x1[::-1], x2[::-1]): if a in (1, b): pass else: return False return True def check_shapes_broadcastable(var, data): if not check_one_way_broadcastable(v...
null
150,724
import ivy def check_dimensions(x): if len(x.shape) <= 1: raise ivy.utils.exceptions.IvyException( f"input must have greater than one dimension; {x} has" f" {len(x.shape)} dimensions" )
null
150,725
import ivy def check_kernel_padding_size(kernel_size, padding_size): for i in range(len(kernel_size)): if ( padding_size[i][0] > kernel_size[i] // 2 or padding_size[i][1] > kernel_size[i] // 2 ): raise ValueError( "Padding size should be less than...
null
150,726
import ivy def check_dev_correct_formatting(device): assert device[0:3] in ["gpu", "tpu", "cpu"] if device != "cpu": assert device[3] == ":" assert device[4:].isnumeric()
null
150,727
import ivy def check_elem_in_list(elem, list, inverse=False, message=""): if inverse and elem in list: raise ivy.utils.exceptions.IvyException( message if message != "" else f"{elem} must not be one of {list}" ) elif not inverse and elem not in list: raise ivy.utils.exception...
null
150,728
import ivy import sys from importlib.util import resolve_name, module_from_spec from ivy.utils.backend import ast_helpers def _import_module(name, package=None): global import_cache absolute_name = resolve_name(name, package) try: return import_cache[absolute_name] except KeyError: pass ...
Handle absolute and relative from_import statement.
150,729
import ivy import sys from importlib.util import resolve_name, module_from_spec from ivy.utils.backend import ast_helpers import_cache = {} def _import_module(name, package=None): global import_cache absolute_name = resolve_name(name, package) try: return import_cache[absolute_name] except KeyEr...
Handle absolute import statement :param name: :return:
150,730
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder def _retrive_local_modules(): ret = ["ivy"] # TODO temporary hacky solution for finder # Get Ivy package root ...
null
150,731
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder importlib_from_import_fn = "_from_import" local_modules = _retrive_local_modules() def _create_list(elements): _elts ...
null
150,732
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder importlib_from_import_fn = "_from_import" def _create_list(elements): _elts = [ast.Constant(value=element, kind=None)...
null
150,733
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder def _create_assign_to_variable(target, value): return ast.Assign( targets=[ast.Name(id=target, ctx=ast.Store...
null
150,734
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder importlib_from_import_fn = "_from_import" def _create_fromimport_call(name): return ast.Call( func=ast.Name(...
null
150,735
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder importlib_abs_import_fn = "_absolute_import" local_modules = _retrive_local_modules() def _parse_import(node: ast.Import...
null
150,736
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder def _create_attrs_from_node(node, attrs=()): # Attrs must be in order last_node = node for attr in attrs: ...
null
150,737
import ast import os import sys import traceback from ast import parse from string import Template from importlib.util import spec_from_file_location from importlib.abc import Loader, MetaPathFinder The provided code snippet includes necessary dependencies for implementing the `_create_node` function. Write a Python f...
Create an AST node from a given statement. Parameters ---------- stmnt The statement to be parsed and represented as an AST node. Returns ------- The resulting AST node representing the given statement.
150,738
import os import re from types import ModuleType, FunctionType import logging import importlib import ivy from ivy.func_wrapper import _wrap_function from ivy.utils.exceptions import IvyException _sub_backend_dict = {} original_backend_dict = None def _unset_sub_backend_from_ivy( original: dict, target: ModuleType,...
null
150,739
import os import re from types import ModuleType, FunctionType import logging import importlib import ivy from ivy.func_wrapper import _wrap_function from ivy.utils.exceptions import IvyException original_backend_dict = None def clear_sub_backends(): if ivy.current_sub_backends: ivy.__dict__.update(origina...
null
150,740
import os import re from types import ModuleType, FunctionType import logging import importlib import ivy from ivy.func_wrapper import _wrap_function from ivy.utils.exceptions import IvyException def find_available_sub_backends(sub_backends_loc): available_sub_backends = [] for sub_backend in os.listdir(sub_ba...
null
150,741
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
null
150,742
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Return the current backend. Priorities: global_backend > argument's backend. Parameters ---------- *args/**kwargs the arguments from which to try to infer the backend, when there is no globally set backend. Returns ------- ret Ivy's current backend. Examples -------- If no global backend is set, then the backend is inf...
150,743
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Set NumPy to be the global backend. equivalent to `ivy.set_backend("numpy")`.
150,744
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Set JAX to be the global backend. equivalent to `ivy.set_backend("jax")`.
150,745
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Set TensorFlow to be the global backend. equivalent to `ivy.set_backend("tensorflow")`.
150,746
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Set torch to be the global backend. equivalent to `ivy.set_backend("torch")`.
150,747
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Set paddle to be the global backend. equivalent to `ivy.set_backend("paddle")`.
150,748
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
Set MXNet to be the global backend. equivalent to `ivy.set_backend("mx")`.
150,749
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
null
150,750
import os import copy import types import ivy import importlib import functools import numpy as np import gc from ivy.utils import _importlib, verbosity from ivy.func_wrapper import _wrap_function from ivy.utils.backend.sub_backend_handler import ( _clear_current_sub_backends, fn_name_from_version_specific_fn_n...
null
150,751
import cProfile import pstats import subprocess import logging from tempfile import NamedTemporaryFile from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `tensorflow_profile_start` function. Write a Python function `def tensorflow_profile_start( logd...
Initialize and start the profiler. Parameters ---------- logdir: str Directory where the profile data will be saved to. host_tracer_level: int Adjust CPU tracing level. Values are: 1 - critical info only, 2 - info, 3 - verbose. [default value is 2] python_tracer_level: int Toggle tracing of Python function calls. Value...
150,752
import cProfile import pstats import subprocess import logging from tempfile import NamedTemporaryFile from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `tensorflow_profile_stop` function. Write a Python function `def tensorflow_profile_stop()` to solve...
Stop the profiler.
150,753
import cProfile import pstats import subprocess import logging from tempfile import NamedTemporaryFile from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `torch_profiler_init` function. Write a Python function `def torch_profiler_init( logdir=None, ...
Initialize and returns a Torch profiler instance. Parameters ---------- logdir : str Directory where the profile data will be saved to. activities : iterable list of activity groups (CPU, CUDA) to use in profiling, supported values: ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``. Defa...
150,754
import cProfile import pstats import subprocess import logging from tempfile import NamedTemporaryFile from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `torch_profiler_start` function. Write a Python function `def torch_profiler_start(profiler)` to sol...
Start the profiler. Parameters ---------- profiler : torch.profiler.profile Torch profiler instance. Returns ------- None
150,755
import cProfile import pstats import subprocess import logging from tempfile import NamedTemporaryFile from importlib.util import find_spec The provided code snippet includes necessary dependencies for implementing the `torch_profiler_stop` function. Write a Python function `def torch_profiler_stop(profiler)` to solve...
Start the profiler. Parameters ---------- profiler : torch.profiler.profile Torch profiler instance. Returns ------- None
150,756
import os import subprocess import sys import json def install_pkg(path, pkg, base="fw/"): if pkg.split("==")[0] if "==" in pkg else pkg == "torch": subprocess.run( f"pip3 install --upgrade {pkg} --target {path} --default-timeout=100" " --extra-index-url https://download.pytorch.org/...
null
150,757
import os import subprocess import sys import json def install_deps(pkgs, path_to_json, base="/opt/fw/"): for fw in pkgs: fw, ver = fw.split("/") path = base + fw + "/" + ver # check to see if this pkg has specific version dependencies with open(path_to_json, "r") as file: ...
null
150,758
import os import subprocess import sys import requests def install_pkg(path, pkg, base="fw/"): def directory_generator(req, base="/opt/fw/"): for versions in req: if "/" in versions: pkg, ver = versions.split("/") path = base + pkg + "/" + ver if not os.path.exists(path)...
null
150,759
import sys from pymongo import MongoClient action_url = "https://github.com/unifyai/ivy/actions/runs/" test_configs = { "test-array-api": ["array_api", 0], "test-core-ivy": ["ivy_core", 1], "test-nn-ivy": ["ivy_nn", 2], "test-stateful-ivy": ["ivy_stateful", 3], "test-frontend-tensorflow-push": ["tf_...
null
150,760
import astunparse import ast import json import sys import subprocess import os import logging from shared import BackendNativeObject _backend_reference = "tensorflow" _target_backend = "" _config = None class InitFileTransformer(ast.NodeTransformer): def __init__(self, variables_to_update: dict): self.vari...
null
150,761
import sys import subprocess import pprint import inspect import json from colorama import Fore, Style, init from importlib import import_module from importlib.util import find_spec from tree_generation import generate as generate_backend from shared import BackendNativeObject from dataclasses import asdict _imported_b...
null
150,762
import sys import subprocess import pprint import inspect import json from colorama import Fore, Style, init from importlib import import_module from importlib.util import find_spec from tree_generation import generate as generate_backend from shared import BackendNativeObject from dataclasses import asdict _imported_b...
null
150,763
import sys import subprocess import pprint import inspect import json from colorama import Fore, Style, init from importlib import import_module from importlib.util import find_spec from tree_generation import generate as generate_backend from shared import BackendNativeObject from dataclasses import asdict config_flag...
null
150,764
import sys import subprocess import pprint import inspect import json from colorama import Fore, Style, init from importlib import import_module from importlib.util import find_spec from tree_generation import generate as generate_backend from shared import BackendNativeObject from dataclasses import asdict config_vali...
null
150,765
import sys import subprocess import pprint import inspect import json from colorama import Fore, Style, init from importlib import import_module from importlib.util import find_spec from tree_generation import generate as generate_backend from shared import BackendNativeObject from dataclasses import asdict def _call_...
null
150,766
import importlib import os import sys import glob def get_all_functions_from_directory(root_dir, startswith="test"): if not os.path.exists(root_dir): print("Invalid directory") sys.exit(1) functions_names = [] for filename in glob.iglob(f"{root_dir}/**/*.py", recursive=True): if len(...
null
150,767
from typing import Any, Callable, Dict, List, Optional, Tuple, Union import functools import time import os import copy import importlib import warnings import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import ivy LINE_UP = "\033[1A" LINE_CLEAR = "\x1b[2K" class _AvoidGPUPreal...
Benchmark the function or module passed in input on the required backends and devices. Parameters ---------- obj The function or module to be benchmarked with and without graph compilation. In case of a function from ivy's functional API, this parameter would receive a string which is the function name, along with func...
150,768
from typing import Any, Callable, Dict, List, Optional, Tuple, Union import functools import time import os import copy import importlib import warnings import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import ivy The provided code snippet includes necessary dependencies for ...
Visualize the speed up results stored in the csv. Parameters ---------- file_path The path of the csv file where the results are stored. output_path The path to the png file to store the graphs in. devices A filter for the devices for which graphs should be generated. backends A filter for the backends for which graphs...
150,769
import base64 import json import os from io import BytesIO import openai from dotenv import load_dotenv from PIL import Image openai.api_key = os.getenv("OPENAI_API_KEY") def encode_and_resize(image): def get_actions(screenshot, objective): encoded_screenshot = encode_and_resize(screenshot) response = openai.c...
null
150,770
import argparse import time from whisper_mic import WhisperMic import vision from vimbot import Vimbot def main(voice_mode): print("Initializing the Vimbot driver...") driver = Vimbot() print("Navigating to Google...") driver.navigate("https://www.google.com") if voice_mode: print("Voice mod...
null
150,771
import re import sys import random from typing import List, Tuple import requests from requests.models import Response def find_links_in_text(text: str) -> List[str]: """Find links in a text and return a list of URLs.""" link_pattern = re.compile(r'((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s(...
Find links in a file and return a list of URLs from text file.
150,772
import re import sys import random from typing import List, Tuple import requests from requests.models import Response def check_duplicate_links(links: List[str]) -> Tuple[bool, List]: """Check for duplicated links. Returns a tuple with True or False and duplicate list. """ seen = {} duplicates = []...
null
150,773
import re import sys import random from typing import List, Tuple import requests from requests.models import Response def check_if_list_of_links_are_working(list_of_links: List[str]) -> List[str]: error_messages = [] for link in list_of_links: has_error, error_message = check_if_link_is_working(link) ...
null
150,774
import re import sys from string import punctuation from typing import List, Tuple, Dict anchor = '###' num_segments = 5 min_entries_per_category = 3 anchor_re = re.compile(anchor + '\s(.+)') category_title_in_index_re = re.compile('\*\s\[(.*)\]') def error_message(line_number: int, message: str) -> str: line = lin...
null
150,775
import glob import os import setuptools import sys import torch.utils.cpp_extension sys.path.append(os.path.dirname(__file__)) import versioneer EXTENSIONS = [] CMD_CLASS = {} CMD_CLASS = versioneer.get_cmdclass(CMD_CLASS) def add_cpp_extension(): extra_compile_args = [ '-std=c++17' if not sys.platform.sta...
null
150,776
import argparse import copy import datetime import logging import os import socket import torch from . import datasets, encoder, logger, network, optimize, plugin, show, visualizer from . import __version__ LOG = logging.getLogger(__name__) def default_output_file(args): base_name = args.basenet if not base_nam...
null
150,777
import argparse import logging import shutil import torch import openpifpaf try: import onnx except ImportError: onnx = None def image_size_warning(basenet_stride, input_w, input_h): if input_w % basenet_stride != 1: LOG.warning( 'input width (%d) should be a multiple of basenet ' ...
null
150,778
import argparse import logging import shutil import torch import openpifpaf try: import onnx except ImportError: onnx = None def check(modelfile): model = onnx.load(modelfile) onnx.checker.check_model(model)
null
150,779
import argparse import logging import shutil import torch import openpifpaf try: import onnx except ImportError: onnx = None try: import onnxsim except ImportError: onnxsim = None def simplify(infile, outfile=None, input_w=129, input_h=97): if outfile is None: assert infile.endswith('.onnx'...
null
150,782
import errno import os import re import subprocess import sys from typing import Callable, Dict import functools def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variab...
Get version information or return default if unable to do so.
150,783
import functools import math import numpy as np def create_sink(side): if side == 1: return np.zeros((2, 1, 1)) sink1d = np.linspace((side - 1.0) / 2.0, -(side - 1.0) / 2.0, num=side, dtype=np.float32) sink = np.stack(( sink1d.reshape(1, -1).repeat(side, axis=0), sink1d.reshape(-1,...
null
150,784
import functools import math import numpy as np The provided code snippet includes necessary dependencies for implementing the `mask_valid_area` function. Write a Python function `def mask_valid_area(intensities, valid_area, *, fill_value=0)` to solve the following problem: Mask area. Intensities is either a feature m...
Mask area. Intensities is either a feature map or an image.
150,785
import sys import importlib import pkgutil REGISTERED = {} def register(): from . import plugins # pylint: disable=import-outside-toplevel,cyclic-import plugin_names = [ 'openpifpaf.plugins.{}'.format(name) for finder, name, is_pkg in pkgutil.iter_modules(plugins.__path__) ] + [ n...
null
150,786
from collections import defaultdict import logging from typing import Optional from .cifcaf import CifCaf, CifCafDense from .cifdet import CifDet from .decoder import Decoder from .multi import Multi from .pose_similarity import PoseSimilarity from .track_base import TrackBase from .tracking_pose import TrackingPose fr...
null
150,787
from collections import defaultdict import logging from typing import Optional from .cifcaf import CifCaf, CifCafDense from .cifdet import CifDet from .decoder import Decoder from .multi import Multi from .pose_similarity import PoseSimilarity from .track_base import TrackBase from .tracking_pose import TrackingPose fr...
null
150,788
import argparse import logging import torch import openpifpaf from .export_onnx import image_size_warning class DecoderModule(torch.nn.Module): def __init__(self, cif_meta, caf_meta): super().__init__() self.cpp_decoder = torch.classes.openpifpaf_decoder.CifCaf( len(cif_meta.keypoints), ...
null
150,789
from .base import Base def cli(parser): group = parser.add_argument_group('visualizer') group.add_argument('--debug-indices', default=[], nargs='+', help=('Indices of fields to create debug plots for ' 'of the form headname:fieldindex, e.g. cif:5. ' ...
null
150,790
from .base import Base class Base: all_indices = [] common_ax = None processed_image_intensity_spread = 2.0 _image = None _processed_image = None _image_meta = None _ground_truth: t.Optional[t.List[annotation.Base]] = None def __init__(self, head_name): self.head_name = head_n...
null
150,791
from contextlib import contextmanager import logging import typing as t import numpy as np from .. import annotation, show def itemsetter(list_, index, value): list_[index] = value return list_
null