id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
151,684 | import dataclasses
import functools
import inspect
import itertools
import json
import os
import os.path
import typing
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union
from absl import logging
from flax.core import frozen_dict
import flax.traverse_util
import jax
from jax.ex... | Returns a function to tokenize and featurize inputs for decoder only models. Args: output_features: Mapping from 'inputs' and 'targets' to seqio.Feature. task_feature_lengths: Mapping from 'inputs' and 'targets' to sequence lengths. tokenized_inputs: specifies whether the input is expected to be pre-tokenized. If so, t... |
151,685 | import dataclasses
import functools
import inspect
import itertools
import json
import os
import os.path
import typing
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union
from absl import logging
from flax.core import frozen_dict
import flax.traverse_util
import jax
from jax.ex... | Feature description from element spec. |
151,686 | import dataclasses
import functools
import inspect
import itertools
import json
import os
import os.path
import typing
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union
from absl import logging
from flax.core import frozen_dict
import flax.traverse_util
import jax
from jax.ex... | Create a preprocessor based on a seqio task. |
151,687 | import dataclasses
import functools
import inspect
import itertools
import json
import os
import os.path
import typing
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union
from absl import logging
from flax.core import frozen_dict
import flax.traverse_util
import jax
from jax.ex... | Creates a preprocessor and adds decoder params as inputs. Args: batch_size: See `save`. output_features: See `save`. task_feature_lengths: See `save`. tokenized_inputs: See `save`. create_preprocessor_fn: A function that creates a preprocessor to be wrapped. decoder_params_spec: A sequence of `(name, dtype, per_example... |
151,688 | import dataclasses
import functools
import inspect
import itertools
import json
import os
import os.path
import typing
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union
from absl import logging
from flax.core import frozen_dict
import flax.traverse_util
import jax
from jax.ex... | Creates synthetic sequences of specified sizes by repeating a single token. Args: sequence_lengths: The sequence lengths to generate examples for. single_token_example: An example such that `N*ex` is always `N` tokens long. This is used to build sequences of a specified size. Defaults to `'Q'`, which satisfies this pro... |
151,689 | import functools
from typing import Any, Mapping, Optional, Sequence, Tuple, Union
import flax
from flax import serialization
from flax import struct
from flax import traverse_util
from flax.core import frozen_dict
from flax.serialization import from_state_dict
from flax.serialization import to_state_dict
import jax
im... | Converts optax optimizer constructor to a wrapped T5X-compatible optimizer. Args: optax_optimizer: an optax optimizer creation function that returns an optax GradientTransformation. Returns: A function that takes the same arguments as the original optax creation function but instead returns a wrapped OptimizerDef-compa... |
151,690 | import functools
from typing import Any, Mapping, Optional, Sequence, Tuple, Union
import flax
from flax import serialization
from flax import struct
from flax import traverse_util
from flax.core import frozen_dict
from flax.serialization import from_state_dict
from flax.serialization import to_state_dict
import jax
im... | null |
151,691 | import functools
from typing import Any, Mapping, Optional, Sequence, Tuple, Union
import flax
from flax import serialization
from flax import struct
from flax import traverse_util
from flax.core import frozen_dict
from flax.serialization import from_state_dict
from flax.serialization import to_state_dict
import jax
im... | Creates a (frozen) tree subset given a traversal. |
151,692 | import functools
from typing import Any, Mapping, Optional, Sequence, Tuple, Union
import flax
from flax import serialization
from flax import struct
from flax import traverse_util
from flax.core import frozen_dict
from flax.serialization import from_state_dict
from flax.serialization import to_state_dict
import jax
im... | Updates a (frozen) tree's subset given a traversal and update subtree. |
151,693 | import builtins
import contextlib
import gc
import os
def gc_disabled_import(*args, **kwargs):
with disabled_gc():
return _original_importlib_import(*args, **kwargs)
def try_disable_gc_during_import():
if os.environ.get('EXPERIMENTAL_DISABLE_GC_DURING_IMPORT'):
builtins.__import__ = gc_disabled_import | null |
151,694 | import functools
import os
import re
from typing import Callable, Collection, Mapping, Optional, Sequence, Set, Tuple, Type
from absl import logging
from clu import metric_writers
import jax
import seqio
from t5x import checkpoints
from t5x import gin_utils
from t5x import models
from t5x import partitioning
from t5x i... | True main function. |
151,695 | import concurrent.futures
import functools
import hashlib
import json
import os
import re
import shutil
import time
from typing import Any, Callable, Iterator, List, Mapping, Optional, Sequence, Tuple, Type
from absl import logging
from clu import metric_writers
import jax
import jax.numpy as jnp
import numpy as np
imp... | Registers ad-hoc Task for file-based dataset of TFExamples. Args: paths: Input file paths; all files should have type `file_type` and contain binary-serialized TFExample protos. file_type: Input file type; e.g., 'tfrecord', 'recordio', 'sstable'. For keyed formats like 'sstable', we ignore the keys and use only the val... |
151,696 | import concurrent.futures
import functools
import hashlib
import json
import os
import re
import shutil
import time
from typing import Any, Callable, Iterator, List, Mapping, Optional, Sequence, Tuple, Type
from absl import logging
from clu import metric_writers
import jax
import jax.numpy as jnp
import numpy as np
imp... | True main function. |
151,697 | from typing import Any, Mapping, MutableMapping, Optional, Tuple
from flax import traverse_util
import flax.core
from flax.core import scope as flax_scope
from flax.linen import partitioning as flax_partitioning
import flax.serialization
import flax.struct
import jax.numpy as jnp
from t5x import optimizers
import typin... | Splits `variables_and_axes` into two separate dicts with the same keys. |
151,698 | import collections
import os
import shutil
import sys
import tempfile
from typing import Any, Dict
from absl import app
from absl import flags
from xmanager import xm
from xmanager import xm_local
from xmanager.contrib import copybara
The provided code snippet includes necessary dependencies for implementing the `_spl... | Separates absl and gin args into separate lists. |
151,699 | import jax
import jax.numpy as jnp
from t5x import checkpoints
from t5x import models
from t5x import partitioning
from t5x import train_state as train_state_lib
The provided code snippet includes necessary dependencies for implementing the `convert_checkpoint` function. Write a Python function `def convert_checkpoint... | Converts a TensorFlow checkpoint to a P5X checkpoint. Args: model: tf_checkpoint_path: Path to a TensorFlow checkpoint to convert. output_dir: Path to a directory to write the converted checkpoint. save_dtype: What dtype to store the target parameters as. concurrent_gb: Number of gigabtes of parameters to convert in pa... |
151,700 | import dataclasses
from typing import MutableMapping, Optional, Union
from clu import metrics as clu_metrics
import flax
import jax
import jax.numpy as jnp
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `_check_param` function. Write a Python function `def _check_par... | Raises a `ValueError` if `value` does not match ndim/dtype. Args: value: Value to be tested. ndim: Expected dimensions. dtype: Expected dtype. Raises: A `ValueError` if `value` does not match `ndim` or `dtype`, or if `value` is not an instance of `jnp.ndarray`. |
151,701 | import dataclasses
from typing import MutableMapping, Optional, Union
from clu import metrics as clu_metrics
import flax
import jax
import jax.numpy as jnp
import numpy as np
class Time(clu_metrics.Metric):
"""Computes the sum of a float-valued metric over a period of time.
Duration (the denominator) must be set m... | null |
151,702 | import dataclasses
from typing import MutableMapping, Optional, Union
from clu import metrics as clu_metrics
import flax
import jax
import jax.numpy as jnp
import numpy as np
class Time(clu_metrics.Metric):
"""Computes the sum of a float-valued metric over a period of time.
Duration (the denominator) must be set m... | Sets duration for TimeRate objects in metrics pytree. |
151,703 | import dataclasses
from typing import MutableMapping, Optional, Union
from clu import metrics as clu_metrics
import flax
import jax
import jax.numpy as jnp
import numpy as np
class Step(clu_metrics.Metric):
"""Abstract class representing a per-step or step-per metric.
Tracks number of steps. Must be set manually u... | Sets steps for Step objects in metrics pytree. |
151,704 | import argparse
import logging
import os
import re
import subprocess
import sys
from contextlib import contextmanager
BLACKLIST_PATH = '/etc/modprobe.d/blacklist-nvidia.conf'
BLACKLIST_CONTENT = '''# Automatically generated by EnvyControl
blacklist nouveau
blacklist nvidia
blacklist nvidia_drm
blacklist nvidia_uvm
blac... | null |
151,705 | import argparse
import logging
import os
import re
import subprocess
import sys
from contextlib import contextmanager
def assert_root():
if os.geteuid() != 0:
logging.error("This operation requires root privileges")
sys.exit(1) | null |
151,706 | import argparse
import logging
import os
import re
import subprocess
import sys
from contextlib import contextmanager
BLACKLIST_PATH = '/etc/modprobe.d/blacklist-nvidia.conf'
UDEV_INTEGRATED_PATH = '/lib/udev/rules.d/50-remove-nvidia.rules'
XORG_PATH = '/etc/X11/xorg.conf'
MODESET_PATH = '/etc/modprobe.d/nvidia.conf'
... | null |
151,707 | import logging
import mistune
import re
from prompt_toolkit.formatted_text import to_formatted_text, HTML
logger = logging.getLogger(__name__)
markdown_render = mistune.Markdown(renderer)
def replace_to_markdown_title(original):
replaced = redisdoc_title_re.sub(r"## \g<1>", original)
return replaced
def render... | null |
151,708 | from typing import Callable, Hashable
from prompt_toolkit.contrib.regular_languages.lexer import GrammarLexer
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text.base import StyleAndTextTuples
from prompt_toolkit.lexers import Lexer, PygmentsLexer, SimpleLexer
from pygments.lexers.scripting ... | Input command render color with lexer mapping below This converts token to styles in style.py |
151,709 | import re
import sys
import time
import logging
from collections import namedtuple
from urllib.parse import parse_qs, unquote, urlparse
from prompt_toolkit.formatted_text import FormattedText
from iredis.exceptions import InvalidArguments
def nativestr(x):
return x if isinstance(x, str) else x.decode("utf-8", "rep... | null |
151,710 | import re
import sys
import time
import logging
from collections import namedtuple
from urllib.parse import parse_qs, unquote, urlparse
from prompt_toolkit.formatted_text import FormattedText
from iredis.exceptions import InvalidArguments
def literal_bytes(b):
if isinstance(b, bytes):
return str(b)[2:-1]
... | null |
151,711 | import re
import sys
import time
import logging
from collections import namedtuple
from urllib.parse import parse_qs, unquote, urlparse
from prompt_toolkit.formatted_text import FormattedText
from iredis.exceptions import InvalidArguments
The provided code snippet includes necessary dependencies for implementing the `... | Display String like redis-cli. escape inner double quotes. add outer double quotes. :param unquoted: list, or str |
151,712 | import re
import csv
import json
import logging
import functools
from importlib.resources import read_text, open_text
from .utils import timer, strip_quote_args
from .exceptions import InvalidArguments, AmbiguousCommand
from . import data as project_data
commands_summary = _load_command_summary()
commands_summary.updat... | null |
151,713 | import re
import csv
import json
import logging
import functools
from importlib.resources import read_text, open_text
from .utils import timer, strip_quote_args
from .exceptions import InvalidArguments, AmbiguousCommand
from . import data as project_data
command2callback, command2syntax, groups = _load_command()
The p... | load command information from file. :returns: - original_commans: dict, command name : Command - command_group: dict, group_name: command_names |
151,714 | import re
import csv
import json
import logging
import functools
from importlib.resources import read_text, open_text
from .utils import timer, strip_quote_args
from .exceptions import InvalidArguments, AmbiguousCommand
from . import data as project_data
The provided code snippet includes necessary dependencies for im... | Load dangerous commands from csv file. |
151,715 | import re
import csv
import json
import logging
import functools
from importlib.resources import read_text, open_text
from .utils import timer, strip_quote_args
from .exceptions import InvalidArguments, AmbiguousCommand
from . import data as project_data
all_commands = sorted(
list(command2callback.keys()) + ["HELP... | Split Redis command text into command and args. :param command: redis command string, with args |
151,716 | import re
import csv
import json
import logging
import functools
from importlib.resources import read_text, open_text
from .utils import timer, strip_quote_args
from .exceptions import InvalidArguments, AmbiguousCommand
from . import data as project_data
def strip_quote_args(s):
"""
Given string s, split it in... | Split user's input into command and args. |
151,717 | import logging
from functools import lru_cache
from prompt_toolkit.contrib.regular_languages.compiler import compile
from .commands import command2syntax
CONST = {
"failoverchoice": "TAKEOVER FORCE",
"withscores": "WITHSCORES",
"withvalues_const": "WITHVALUES",
"limit": "LIMIT",
"expiration": "EX PX... | null |
151,718 | import logging
from functools import lru_cache
from prompt_toolkit.contrib.regular_languages.compiler import compile
from .commands import command2syntax
logger = logging.getLogger(__name__)
command_grammar = compile(COMMAND)
GRAMMAR = {
"command_key": rf"\s+ {KEY} \s*",
"command_pattern": rf"\s+ {PATTERN} \s*"... | :param command: command name in upper case. This command must be raw user input, otherwise can't match in lexer, cause this command to be invalid; |
151,719 | import logging
from prompt_toolkit.filters import completion_is_selected
from prompt_toolkit.key_binding import KeyBindings
logger = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `_` function. Write a Python function `def _(event)` to solve the following pro... | Makes the enter key work as the tab key only when showing the menu. In other words, don't execute query when enter is pressed in the completion dropdown menu, instead close the dropdown menu (accept current selection). |
151,720 | import logging
import time
from packaging.version import parse as version_parse
from prompt_toolkit.formatted_text import FormattedText
from .commands import command2callback
from .config import config
from .utils import double_quotes, ensure_str, nativestr
def _render_raw_list(bytes_items):
flatten_items = []
... | null |
151,721 | import logging
import time
from packaging.version import parse as version_parse
from prompt_toolkit.formatted_text import FormattedText
from .commands import command2callback
from .config import config
from .utils import double_quotes, ensure_str, nativestr
NEWLINE_TUPLE = ("", "\n")
NIL_TUPLE = ("class:type", "(nil)")... | Complute the newline/number-width/lineno, render list to FormattedText |
151,722 | import logging
import time
from packaging.version import parse as version_parse
from prompt_toolkit.formatted_text import FormattedText
from .commands import command2callback
from .config import config
from .utils import double_quotes, ensure_str, nativestr
def _render_scan(render_response, response):
cursor, resp... | null |
151,723 | import logging
import time
from packaging.version import parse as version_parse
from prompt_toolkit.formatted_text import FormattedText
from .commands import command2callback
from .config import config
from .utils import double_quotes, ensure_str, nativestr
NEWLINE_TUPLE = ("", "\n")
def ensure_str(origin, decode=None... | null |
151,724 | import sys
import click
from .commands import dangerous_commands
BOOLEAN_TYPE = ConfirmBoolParamType()
def is_dangerous(command):
"""
:return : return True, reason str if command is dangerous;
return False, None otherwise.
"""
reason = dangerous_commands.get(command)
return reason is not Non... | Check if the query is destructive and prompts the user to confirm. Returns: * None if the query is non-destructive or we can't prompt the user. * True if the query is destructive and the user wants to proceed. * False if the query is destructive and the user doesn't want to proceed. |
151,725 | import os
import logging
import sys
import time
from pathlib import Path
import platform
import click
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit import print_formatted_text
from prompt_toolkit... | null |
151,726 | import os
import logging
import sys
import time
from pathlib import Path
import platform
import click
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit import print_formatted_text
from prompt_toolkit... | null |
151,727 | import os
import logging
import sys
import time
from pathlib import Path
import platform
import click
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit import print_formatted_text
from prompt_toolkit... | null |
151,728 | import os
import logging
import sys
import time
from pathlib import Path
import platform
import click
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit import print_formatted_text
from prompt_toolkit... | IRedis: Interactive Redis When no command is given, IRedis starts in interactive mode. \b Examples: - iredis - iredis -d dsn - iredis -h 127.0.0.1 -p 6379 - iredis -h 127.0.0.1 -p 6379 -a <password> - iredis --url redis://localhost:7890/3 Type "help" in interactive mode for information on available commands and setting... |
151,729 | import os
import logging
import sys
import time
from pathlib import Path
import platform
import click
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit import print_formatted_text
from prompt_toolkit... | Different from the prompt-toolkit default, we want to have a choice not to execute a query after editing, hence validate_and_handle=False. |
151,730 | import os
import logging
import sys
import time
from pathlib import Path
import platform
import click
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit import print_formatted_text
from prompt_toolkit... | Create a Client. :param params: commandline params. |
151,731 | import sys
import csv
from lxml import etree
import requests
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs) | null |
151,732 | import io
from datetime import datetime
from enum import Enum
from types import GeneratorType
from typing import Any, Callable
from pydantic import BaseModel
from .types import Path
The provided code snippet includes necessary dependencies for implementing the `make_encodeable` function. Write a Python function `def m... | Returns a pickle-compatible version of the object. It will encode any Pydantic models and custom types. It is almost JSON-compatible. Files must be done in a separate step with upload_files(). Somewhat based on FastAPI's jsonable_encoder(). |
151,733 | import logging
import os
import structlog
from structlog.typing import EventDict
def replace_level_with_severity(
_: logging.Logger, __: str, event_dict: EventDict
) -> EventDict:
"""
Replace the level field with a severity field as understood by Stackdriver
logs.
"""
if "level" in event_dict:
... | Configure stdlib logger to use structlog processors and formatters so that uvicorn and application logs are consistent. |
151,734 | import io
import mimetypes
import os
import pathlib
import shutil
import tempfile
import urllib.parse
import urllib.request
from typing import Any, Dict, Iterator, List, Optional, TypeVar, Union
import requests
from pydantic import Field
FILENAME_ILLEGAL_CHARS = set("\u0000/")
FILENAME_MAX_LENGTH = 200
def _len_bytes(s... | null |
151,735 | import ast
import json
import sys
import types
import typing
from pathlib import Path
def extract_info(code: str) -> "JSONDict":
"""Parse the schemas from a file with a predict function"""
tree = ast.parse(code)
properties: "JSONDict" = {}
inputs: "JSONDict" = {"title": "Input", "type": "object", "prope... | null |
151,736 | import os
import sys
from contextlib import contextmanager
from typing import Iterator
def suppress_output() -> Iterator[None]:
null_out = open(os.devnull, "w")
null_err = open(os.devnull, "w")
out_fd = sys.stdout.fileno()
err_fd = sys.stderr.fileno()
out_dup_fd = os.dup(out_fd)
err_dup_fd = os... | null |
151,737 | import importlib.util
import os
import os.path
import sys
import typing as t
from datetime import datetime
from enum import Enum
from types import ModuleType
import pydantic
BUNDLED_SCHEMA_PATH = ".cog/schema.py"
def create_schema_module() -> t.Optional[ModuleType]:
if not os.path.exists(BUNDLED_SCHEMA_PATH):
... | null |
151,738 | import enum
import importlib.util
import inspect
import io
import os.path
import sys
import types
from abc import ABC, abstractmethod
from collections.abc import Iterator
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
cast,
)
from unittest... | null |
151,739 | import enum
import importlib.util
import inspect
import io
import os.path
import sys
import types
from abc import ABC, abstractmethod
from collections.abc import Iterator
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
cast,
)
from unittest... | Run the predictor on the inputs, and append resulting paths to cleanup functions for removal. |
151,740 | import enum
import importlib.util
import inspect
import io
import os.path
import sys
import types
from abc import ABC, abstractmethod
from collections.abc import Iterator
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
cast,
)
from unittest... | Reads cog.yaml and returns it as a dict. |
151,741 | import enum
import importlib.util
import inspect
import io
import os.path
import sys
import types
from abc import ABC, abstractmethod
from collections.abc import Iterator
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
cast,
)
from unittest... | Constructs an instance of the user-defined Predictor class from a config. |
151,742 | import io
import sys
import threading
import traceback
import typing
from datetime import datetime, timezone
from multiprocessing.pool import AsyncResult, ThreadPool
from typing import Any, Callable, Optional, Tuple, Union, cast
import requests
import structlog
from attrs import define
from fastapi.encoders import jso... | null |
151,743 | import argparse
import asyncio
import functools
import logging
import os
import signal
import socket
import sys
import textwrap
import threading
import traceback
from datetime import datetime, timezone
from enum import Enum, auto, unique
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
... | null |
151,744 | import argparse
import asyncio
import functools
import logging
import os
import signal
import socket
import sys
import textwrap
import threading
import traceback
from datetime import datetime, timezone
from enum import Enum, auto, unique
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
... | null |
151,745 | import argparse
import asyncio
import functools
import logging
import os
import signal
import socket
import sys
import textwrap
import threading
import traceback
from datetime import datetime, timezone
from enum import Enum, auto, unique
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
... | null |
151,746 | import argparse
import asyncio
import functools
import logging
import os
import signal
import socket
import sys
import textwrap
import threading
import traceback
from datetime import datetime, timezone
from enum import Enum, auto, unique
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
... | null |
151,747 | import argparse
import asyncio
import functools
import logging
import os
import signal
import socket
import sys
import textwrap
import threading
import traceback
from datetime import datetime, timezone
from enum import Enum, auto, unique
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
... | null |
151,748 | import os
from typing import Any, Callable, Set
import requests
import structlog
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from ..schema import Status, WebhookEvent
from .response_throttler import ResponseThrottler
def _get_version() -> str:
try:
try:... | null |
151,749 | import numpy as np
import itertools
from sklearn.metrics.pairwise import cosine_similarity
from typing import List, Tuple
The provided code snippet includes necessary dependencies for implementing the `max_sum_distance` function. Write a Python function `def max_sum_distance( doc_embedding: np.ndarray, word_em... | Calculate Max Sum Distance for extraction of keywords We take the 2 x top_n most similar words/phrases to the document. Then, we take all top_n combinations from the 2 x top_n words and extract the combination that are the least similar to each other by cosine similarity. This is O(n^2) and therefore not advised if you... |
151,750 | import numpy as np
from operator import itemgetter
from typing import List, Tuple
from sklearn.metrics.pairwise import cosine_similarity
The provided code snippet includes necessary dependencies for implementing the `mmr` function. Write a Python function `def mmr( doc_embedding: np.ndarray, word_embeddings: n... | Calculate Maximal Marginal Relevance (MMR) between candidate keywords and the document. MMR considers the similarity of keywords/keyphrases with the document, along with the similarity of already selected keywords and keyphrases. This results in a selection of keywords that maximize their within diversity with respect ... |
151,751 | from typing import Tuple, List
from rich.console import Console
from rich.highlighter import RegexHighlighter
from sklearn.feature_extraction.text import CountVectorizer
class NullHighlighter(RegexHighlighter):
"""Basic highlighter."""
base_style = ""
highlights = [r""]
def _highlight_one_gram(
doc: str... | Highlight keywords in a document Arguments: doc: The document for which to extract keywords/keyphrases. keywords: The top n keywords for a document with their respective distances to the input document. vectorizer: The vectorizer used for tokenizing the document. Returns: highlighted_text: The document with additional ... |
151,752 | import random
import time
The provided code snippet includes necessary dependencies for implementing the `process_candidate_keywords` function. Write a Python function `def process_candidate_keywords(documents, candidate_keywords)` to solve the following problem:
Create a common format for candidate keywords.
Here is... | Create a common format for candidate keywords. |
151,753 | import time
import openai
from tqdm import tqdm
from typing import Mapping, Any, List
from keybert.llm._base import BaseLLM
from keybert.llm._utils import retry_with_exponential_backoff, process_candidate_keywords
def retry_with_exponential_backoff(
func,
initial_delay: float = 1,
exponential_base: float =... | null |
151,754 | import time
import openai
from tqdm import tqdm
from typing import Mapping, Any, List
from keybert.llm._base import BaseLLM
from keybert.llm._utils import retry_with_exponential_backoff, process_candidate_keywords
def retry_with_exponential_backoff(
func,
initial_delay: float = 1,
exponential_base: float =... | null |
151,755 | from ._base import BaseEmbedder
class BaseEmbedder:
"""The Base Embedder used for creating embedding models
Arguments:
embedding_model: The main embedding model to be used for extracting
document and word embedding
word_embedding_model: The embedding model used for ext... | Select an embedding model based on language or a specific sentence transformer models. When selecting a language, we choose `all-MiniLM-L6-v2` for English and `paraphrase-multilingual-MiniLM-L12-v2` for all other languages as it support 100+ languages. Returns: model: Either a Sentence-Transformer or Flair model |
151,756 | import torch
from PIL import Image
import struct
import numpy as np
from comfy.cli_args import args, LatentPreviewMethod
from comfy.taesd.taesd import TAESD
import folder_paths
import comfy.utils
import logging
def get_previewer(device, latent_format):
previewer = None
method = args.preview_method
if method... | null |
151,757 | import sys
import copy
import logging
import threading
import heapq
import traceback
import inspect
from typing import List, Literal, NamedTuple, Optional
import torch
import nodes
import comfy.model_management
def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}):
valid_inputs = cl... | null |
151,758 | import sys
import copy
import logging
import threading
import heapq
import traceback
import inspect
from typing import List, Literal, NamedTuple, Optional
import torch
import nodes
import comfy.model_management
def recursive_will_execute(prompt, outputs, current_item, memo={}):
unique_id = current_item
if uni... | null |
151,759 | import sys
import copy
import logging
import threading
import heapq
import traceback
import inspect
from typing import List, Literal, NamedTuple, Optional
import torch
import nodes
import comfy.model_management
def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}):
valid_inputs = cl... | null |
151,760 | import sys
import copy
import logging
import threading
import heapq
import traceback
import inspect
from typing import List, Literal, NamedTuple, Optional
import torch
import nodes
import comfy.model_management
def validate_inputs(prompt, item, validated):
unique_id = item
if unique_id in validated:
ret... | null |
151,761 | import comfy.options
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
if os.name == "nt":
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available'... | null |
151,762 | import comfy.options
comfy.options.enable_args_parsing()
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
def cuda_malloc_warning():
device = comfy.model_management.get_torch_devic... | null |
151,763 | import comfy.options
comfy.options.enable_args_parsing()
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
def prompt_worker(q, server):
e = execution.PromptExecutor(server)
las... | null |
151,764 | import comfy.options
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
async def run(server, address='', port=8188, verbose=True, call_on_start=None):
await asyncio.gather(server.st... | null |
151,765 | import comfy.options
comfy.options.enable_args_parsing()
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
class BinaryEventTypes:
PREVIEW_IMAGE = 1
UNENCODED_PREVIEW_IMAGE = 2
... | null |
151,766 | import comfy.options
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
if os.name == "nt":
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available'... | null |
151,767 | import comfy.options
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
if os.name == "nt":
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available'... | null |
151,768 | import comfy.options
import os
import importlib.util
import folder_paths
import time
import asyncio
import itertools
import shutil
import threading
import gc
from comfy.cli_args import args
import logging
if os.name == "nt":
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available'... | null |
151,769 | import os
import shutil
base_path = os.path.dirname(os.path.realpath(__file__))
def update_windows_updater():
top_path = os.path.dirname(base_path)
updater_path = os.path.join(base_path, ".ci/update_windows/update.py")
bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat")
dest_up... | null |
151,770 | import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
import math
import comfy.utils
def gaussian_kernel(kernel_size: int, sigma: float, device=None):
x, y = torch.meshgrid(torch.linspace(-1, 1, kernel_size, device=device), torch.linspace(-1, 1, kernel_size, device=device), indexing... | null |
151,771 | import numpy as np
import scipy.ndimage
import torch
import comfy.utils
from nodes import MAX_RESOLUTION
def composite(destination, source, x, y, mask = None, multiplier = 8, resize_source = False):
source = source.to(destination.device)
if resize_source:
source = torch.nn.functional.interpolate(source... | null |
151,773 | import torch
import logging
def Fourier_filter(x, threshold, scale):
# FFT
x_freq = torch.fft.fftn(x.float(), dim=(-2, -1))
x_freq = torch.fft.fftshift(x_freq, dim=(-2, -1))
B, C, H, W = x_freq.shape
mask = torch.ones((B, C, H, W), device=x.device)
crow, ccol = H // 2, W //2
mask[..., cro... | null |
151,774 | import comfy.utils
import folder_paths
import torch
import logging
def load_hypernetwork_patch(path, strength):
sd = comfy.utils.load_torch_file(path, safe_load=True)
activation_func = sd.get('activation_func', 'linear')
is_layer_norm = sd.get('is_layer_norm', False)
use_dropout = sd.get('use_dropout',... | null |
151,815 | import folder_paths
import comfy.sd
import comfy.model_sampling
import comfy.latent_formats
import torch
def rescale_zero_terminal_snr_sigmas(sigmas):
alphas_cumprod = 1 / ((sigmas * sigmas) + 1)
alphas_bar_sqrt = alphas_cumprod.sqrt()
# Store old values.
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()... | null |
151,816 | import torch
from torch import einsum
import torch.nn.functional as F
import math
from einops import rearrange, repeat
import os
from comfy.ldm.modules.attention import optimized_attention, _ATTN_PRECISION
import comfy.samplers
def attention_basic_with_sim(q, k, v, heads, mask=None):
b, _, dim_head = q.shape
d... | null |
151,817 | import torch
from torch import einsum
import torch.nn.functional as F
import math
from einops import rearrange, repeat
import os
from comfy.ldm.modules.attention import optimized_attention, _ATTN_PRECISION
import comfy.samplers
def gaussian_blur_2d(img, kernel_size, sigma):
def create_blur_map(x0, attn, sigma=3.0, thr... | null |
151,818 | import numpy as np
import torch
import comfy.utils
from enum import Enum
def resize_mask(mask, shape):
return torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(shape[0], shape[1]), mode="bilinear").squeeze(1) | null |
151,819 | import numpy as np
import torch
import comfy.utils
from enum import Enum
class PorterDuffMode(Enum):
ADD = 0
CLEAR = 1
DARKEN = 2
DST = 3
DST_ATOP = 4
DST_IN = 5
DST_OUT = 6
DST_OVER = 7
LIGHTEN = 8
MULTIPLY = 9
OVERLAY = 10
SCREEN = 11
SRC = 12
SRC_ATOP = 13
... | null |
151,820 | import comfy.utils
import torch
def reshape_latent_to(target_shape, latent):
if latent.shape[1:] != target_shape[1:]:
latent = comfy.utils.common_upscale(latent, target_shape[3], target_shape[2], "bilinear", "center")
return comfy.utils.repeat_to_batch_size(latent, target_shape[0]) | null |
151,821 | import torch
import nodes
import comfy.utils
def camera_embeddings(elevation, azimuth):
elevation = torch.as_tensor([elevation])
azimuth = torch.as_tensor([azimuth])
embeddings = torch.stack(
[
torch.deg2rad(
(90 - elevation) - (90)
), # Zero123 ... | null |
151,823 | import comfy.sd
import comfy.utils
import comfy.model_base
import comfy.model_management
import folder_paths
import json
import os
from comfy.cli_args import args
if args.windows_standalone_build:
args.auto_launch = True
if args.disable_auto_launch:
args.auto_launch = False
if args.verbose:
logging_level... | null |
151,824 | import os
import time
output_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output")
def set_output_directory(output_dir):
global output_directory
output_directory = output_dir | null |
151,825 | import os
import time
temp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp")
def set_temp_directory(temp_dir):
global temp_directory
temp_directory = temp_dir | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.