code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace,...
567
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Optional[Any] = { "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig...
567
1
'''simple docstring''' import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup __UpperCAmelCase = logging.get_logger(__name_...
220
'''simple docstring''' import numpy as np def SCREAMING_SNAKE_CASE_ ( snake_case_ : np.array ) -> np.array: return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE_ ( snake_case_ : np.array ) -> np.array: return vector * sigmoid(1.7...
220
1
'''simple docstring''' from PIL import Image def _A ( A__ , A__ ): """simple docstring""" __lowercase = (259 * (level + 255)) / (255 * (259 - level)) def contrast(A__ ) -> int: return int(128 + factor * (c - 128) ) return img.point(A__ ) if __name__ == "__main__...
41
"""simple docstring""" __A : Union[str, Any] = {str(digit): digit**5 for digit in range(10)} def lowercase ( UpperCamelCase : int ): """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(UpperCamelCase ) ) def lowercase ( ): ...
656
0
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokeniza...
713
'''simple docstring''' import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() __A : Any...
398
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __A = logging.get_logger(__name__) class UpperCAmelCase (__A ): """simple docstring""" def __init__( self , *_UpperCAmelCase , ...
586
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { ...
94
0
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, ...
707
'''simple docstring''' import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence ...
419
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, Timeste...
8
'''simple docstring''' import argparse import os import re lowercase__ : Optional[int] = '''src/diffusers''' # Pattern that looks at the indentation in a line. lowercase__ : Dict = re.compile(r'''^(\s*)\S''') # Pattern that matches `"key":" and pu...
8
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class a_ ( _UpperCAmelCase ): a ...
19
"""simple docstring""" import argparse import os import re import packaging.version a : str = '''examples/''' a : List[str] = { '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(r'''^__...
19
1
"""simple docstring""" import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils i...
543
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def a__ ( snake_case__ ) -> list[list[float]]: lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementati...
543
1
'''simple docstring''' def lowerCamelCase_ ( A_ , A_ ): assert x is not None assert y is not None __lowerCamelCase = len(A_ ) __lowerCamelCase = len(A_ ) # declaring the array for storing the dp values __lowerCamelCase = [[0] * (n + 1) for _...
575
'''simple docstring''' import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC _UpperCamelCase : Any =parse(importlib.metadata.version("torch")) def lowerCamelCase_ ( A_ , A_ , ...
575
1
def _lowercase ( __UpperCamelCase : int = 50 ): snake_case__ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ...
214
from math import ceil def _lowercase ( __UpperCamelCase : int = 1001 ): snake_case__ = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): snake_case__ = 2 * i + 1 snake_case__ = 2 * i snake_case__ = tot...
214
1
'''simple docstring''' def lowerCamelCase__ ( _A = 50 ): a : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ...
195
'''simple docstring''' def lowerCamelCase__ ( _A = 6008_5147_5143 ): try: a : Optional[int] = int(_A ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater ...
195
1
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncod...
269
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, ...
269
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : int = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_...
714
import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( __magic_name__ ): '''simple docstring''' def __init__( self , ...
516
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'dist...
94
"""simple docstring""" import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class ...
554
0
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class __A( __lowerCamelCase , __lowerCamelCase ): """simple docstring""" @register_to_config de...
86
import os from datetime import datetime as dt from github import Github lowerCamelCase_ = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''', ] def __magic_name__ ( ...
86
1
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, ...
19
import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import UNCONDITIONA...
285
0
"""simple docstring""" import math from numpy import inf from scipy.integrate import quad def _A ( __lowercase ): """simple docstring""" if num <= 0: raise ValueError("""math domain error""" ) return quad(__lowercase , 0 , __l...
718
"""simple docstring""" # using dfs for finding eulerian path traversal def _A ( __lowercase , __lowercase , __lowercase , __lowercase=None ): """simple docstring""" lowerCamelCase__ = (path or []) + [u] for v in graph[u]: ...
258
0
import os def SCREAMING_SNAKE_CASE_ ( ) -> List[str]: with open(os.path.dirname(UpperCAmelCase_ ) + '''/p022_names.txt''' ) as file: SCREAMING_SNAKE_CASE_ : Any =str(file.readlines()[0] ) SCREAMING_SNAKE_CASE_ : List[Any] =names.rep...
443
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowercase_ ( A ): __lowerCamelCase = (DDIMParallelScheduler,) __lowerCamelCase = (("eta", 0.0), ("num_inference_steps", 5_0)) ...
443
1
'''simple docstring''' import math from collections.abc import Callable def lowerCamelCase__ ( __lowerCamelCase : Callable[[float], float] , __lowerCamelCase : float , __lowerCamelCase : float ): '''simple docstring''' _UpperCAmelCase : float ...
331
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase =logging.get_logger(__name__) lowercase ={ 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/confi...
331
1
import string import numpy def __UpperCamelCase ( lowercase__ : int , lowercase__ : int ) -> int: '''simple docstring''' return b if a == 0 else greatest_common_divisor(b % a , lowercase__ ) class __a : __snake_case : int = s...
600
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("""socket.socket""" ) @patch("""builtins.open""" ) def __UpperCamelCase ( lowercase__ : List[Any] , lowercase__ : str ) -> str: '''simple docstring''' lowerC...
600
1
"""simple docstring""" from __future__ import annotations def __lowercase ( a : list[int] ) -> list[int]: # This function is recursive __snake_case : str =len(a ) # If the array contains only one element, we return it (it's the stop condition of # recu...
497
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ : Optional[int] = logging.get_logger(__name__) UpperCamelCase_ : Union[str, Any] = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} cla...
497
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = {} class __lowercase ( _A ): lowercase = 'llama' lowercase = ['past_key_values'] def __init__( self ...
604
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...tes...
604
1
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake lowerCAmelCase_ = numpy.array([0, 0]) lowerCAmelCase_ = numpy.array([0.5, 0.8_66_02_54]) lowerCAmelCase_ = numpy.array([1, 0]) lowerCAmelCase_ = [VE...
470
def __lowerCAmelCase ( UpperCamelCase ) -> bool: if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(UpperCamelCase ) == 0: raise ValueError('''Input list must be a non empty lis...
470
1
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class lowercase__ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[int] ): ...
195
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is...
195
1
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_availa...
245
'''simple docstring''' from collections.abc import Callable def UpperCamelCase ( a , a , a ) -> float: '''simple docstring''' __magic_name__ = a __magic_name__ = b if function(a ) == 0: # one of the a or b is a root for the function ...
245
1
from sklearn.metrics import matthews_corrcoef import datasets _lowerCAmelCase = "\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false...
10
'''simple docstring''' # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.confi...
131
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
246
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowerCamelCase_ : Dict = logging.get_logger(__name__) class a__ ( __snake_case ): def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> None: w...
246
1
from math import factorial def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase = 100 ) -> int: '''simple docstring''' return sum(int(A__ ) for x in str(factorial(A__ ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
343
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class __lowercase( lowercase__ ): '''simple docstring''' __a : int = (DDPMParallelScheduler,) def snake_case_ ( self , **__a...
594
0
"""simple docstring""" import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) ...
716
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar SCREAMING_SNAKE_CASE = TypeVar("""T""") class __a ( Generic[T] ): def __init__( self : List[Any] , UpperCAmelCase_ : T )-> None: ...
556
0
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING...
62
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, i...
151
0
'''simple docstring''' import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_availa...
415
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version ...
415
1
from __future__ import annotations class A : def __init__( self , lowercase_ ) -> Union[str, Any]: '''simple docstring''' _snake_case : Optional[int] = TypeError( '''Matrices must be formed from a list of zero or more l...
326
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import Aut...
326
1
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokeniz...
703
'''simple docstring''' import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging UpperCAmelCase_ : Optional[int] = '\\n\n' UpperCAmelCase_ : Tuple = '\nPerplexity ...
540
0
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequ...
97
from __future__ import annotations def a ( snake_case__: Optional[int] , snake_case__: Optional[int] , snake_case__: Any , snake_case__: Optional[int] ): # noqa: E741 '''simple docstring''' while r - l > 1: lowercase_ = (l + r) // 2 if v[m] >=...
97
1
from __future__ import annotations import os from collections.abc import Mapping lowercase : Union[str, Any] = tuple[int, int] class A__ : """simple docstring""" def __init__( self , lowercase , lowercase) -> None: '''simple docstri...
705
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : List[str] = logging.get_logger(__name__) lowercase : Any = { """huggingface/time-series-transformer-tourism-monthly""": ( """https://hugging...
392
0
from typing import Tuple, Union from ...modeling_outputs import BackboneOutput from ...modeling_utils import PreTrainedModel from ...utils import is_timm_available, is_torch_available, requires_backends from ...utils.backbone_utils import BackboneMixin from .configuration_timm_backbone import TimmBackboneConfig ...
53
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def a_ ( ): __lowerCAmelCase = ArgumentParser( description=( 'PyTorch TPU distributed training launch ' ...
53
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_...
702
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Any ,*_a ...
319
0
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Dict ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = int(snake_case_ ) ...
78
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from ...
442
0
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function UpperCAmelCase_ = 1.054571817E-34 # unit of ℏ : J * s UpperCAmelCase_ = 3E8 # unit of c : m * s^-1 def UpperCAmelCase__ ( ...
704
# Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
664
0
from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import...
544
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' @staticmethod @abstractmethod def _snake_case ( snake_case__ : ArgumentParser ) -> Tuple: ...
544
1
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate ...
710
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files" , [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_info...
132
0
def __magic_name__ ( lowercase_ ) -> int: '''simple docstring''' UpperCamelCase = hex_num.strip() if not hex_num: raise ValueError("No value was passed to the function" ) UpperCamelCase = hex_num[0] == "-" if is_negati...
606
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer __a : Tuple = logging.getLogger(__name__) def __magic_name__ ( ) -> Optional[Any]: '''simple docstring''' UpperCamelCase ...
606
1
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_=1024 , lowercase_=1024 , lowercase_=False , ...
675
import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch lowerCAmelCase = """sshleifer/bart-tiny-random""" lowerCAme...
675
1
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' ...
447
'''simple docstring''' from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord i...
447
1
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class A (SCREAMING_SNAKE_CASE ): '''simple docstring...
713
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets A : Dict = datasets.logging.get_logger(__name__) A : Optional[Any] = '''\ @InProceedings{moosavi2019...
247
0
'''simple docstring''' def lowerCamelCase__ ( a , a , a , a , a ): if index == number_of_items: return 0 __snake_case = 0 __snake_case = 0 __snake_case = knapsack(snake_case__ , snake_case__ , snake_case__ , snake_c...
356
import os import pytest from attr import dataclass __UpperCAmelCase = '''us-east-1''' # defaults region @dataclass class lowerCAmelCase_ : UpperCAmelCase__ : str UpperCAmelCase__ : Tuple = "arn:aws:iam::558105141721:role/sagemaker_execution_role" Up...
40
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling...
713
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def ...
540
0
'''simple docstring''' from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''KEY''') lowerCAmelCase__ = TypeVar('''VAL''') @dataclass(frozen=lowerCamelCase__ , slots=lowerCamelCase...
41
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes...
216
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCAmelCase = logging.get_logger(__nam...
711
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging _lowerCAmelCase = logging.get_logger(__name__) def UpperCamelCase ( a=None , a=None ) -> Union[str, ...
245
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ : Tuple = {'configuration_fnet': [...
527
'''simple docstring''' from math import pow def UpperCAmelCase ( A : int , A : int , A : int , A : int , A : int , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a so...
527
1
# Function to print upper half of diamond (pyramid) def lowercase ( __A : List[str] ) -> Any: '''simple docstring''' for i in range(0 , __A ): for _ in range(0 , n - i - 1 ): # printing spaces print(""" """ , end="""""" ) ...
710
from math import factorial def lowercase ( __A : int = 20 ) -> int: '''simple docstring''' snake_case : str = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case : str = n // 2 return...
315
0
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): ...
553
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load...
553
1
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np __SCREAMING_SNAKE_CASE : List[Any] = re.compile(R'''\b(a|an|the)\b''', re.UNICODE) __SCREAMING_SNAKE_CASE : Optional[Any] = None def ...
623
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) class lowerCamelCase_( A__ ): '''simple docstring''' def __init__( self , lowerCamelCase__...
623
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
346
"""simple docstring""" import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def ...
346
1
UpperCamelCase_ = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" Up...
376
from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): ...
376
1
'''simple docstring''' from collections.abc import Callable class A_ : '''simple docstring''' def __init__( self , A_ = None ): _UpperCamelCase = [] # Stores indexes of each item for supporting updates and deletion. _UpperCamelCase = {} ...
138
"""simple docstring""" import baseaa def lowerCamelCase ( _UpperCamelCase : str ) -> bytes: '''simple docstring''' return baseaa.baaencode(string.encode("""utf-8""" ) ) def lowerCamelCase ( _UpperCamelCase : bytes ) -> str: '''simple docstring...
139
0
'''simple docstring''' import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCamelCase ( __lowercase ): '''simple docstring''' lowerCAmelCase__ = (EulerDiscreteScheduler,) lo...
713
'''simple docstring''' from __future__ import annotations from typing import TypedDict class lowerCamelCase ( lowerCamelCase ): '''simple docstring''' lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 def __lowerCamelCase ( _UpperCamelCase : str ): ...
43
0
"""simple docstring""" def lowercase__ ( lowerCAmelCase : str ) -> bool: """simple docstring""" UpperCAmelCase = [int(lowerCAmelCase ) for i in ip_va_address.split('.' ) if i.isdigit()] return len(lowerCAmelCase ) == 4 and all(0 ...
373
"""simple docstring""" import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers impo...
373
1
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import...
702
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class lowerCAmelC...
202
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ ...
645
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCamelCase : Dict ={"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} t...
316
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : Optional[Any] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex an...
75
import webbrowser from sys import argv from urllib.parse import parse_qs, quote import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": __A : int = '%20'.join(argv[1:]) if len(argv) > 1 else quote(str(input('Search: '))) print('Googling.....') __A...
75
1
from statistics import mean import numpy as np def _a ( lowercase__ : list , lowercase__ : list , lowercase__ : list , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # Number of processes finished...
85
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( cen...
206
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase : Union[str, Any] ={ 'configuration_roformer': ['ROFO...
693
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True lowerCAmelCase : List[Any] = 4 lowerCAme...
693
1
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers lowercase__ = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def __magic_name__ ( ): __a : List[str] = os.path.dirname(os.path.realpath(_lowerCamelCase ) ) ...
581
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING lowercase__ = logging.get_logg...
581
1
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def _snake_case ( ) -> str: '''simple docstring''' import os as original_os from os import path as original_path from os import rename as original_rename ...
455
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) __lo...
455
1
from collections.abc import Iterable from typing import Any class UpperCamelCase : def __init__( self : int ,_lowerCAmelCase : int | None = None ): """simple docstring""" __snake_case = value __snake_case = None # Added in ord...
524
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-tes...
524
1
'''simple docstring''' import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from dat...
700
'''simple docstring''' from jiwer import compute_measures import datasets lowerCamelCase :int = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER...
686
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) snake_case = { """configuration_roberta_prelayernorm""": [ """ROBERTA_PRELAYERNORM_PRETRAI...
378
'''simple docstring''' from cva import destroyAllWindows, imread, imshow, waitKey def UpperCAmelCase_ ( lowerCamelCase_ ): """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ : Tuple = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in...
378
1
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def lowerCamelCase__ ( A__ : Tuple , A__ : str , A__ : List[str] ): '''simple docstring''' __lowerCamelCase = ("""dense.weigh...
703
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ = get_tests_dir('fixtures/test_sentencepiece...
80
0
"""simple docstring""" from collections import namedtuple import requests from lxml import html # type: ignore __lowerCamelCase = namedtuple('covid_data', 'cases deaths recovered') def a ( __UpperCAmelCase : str = "https://www.worldometers.info/coronavirus...
96
from ...configuration_utils import PretrainedConfig class snake_case__ ( _UpperCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = "bert-generation" def __init__( self : Optional[int] , A__ : List[Any]=5_03_58 , A__ : Any=10_24 , ...
666
0
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE...
713
import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version ...
212
0
"""simple docstring""" import comet # From: unbabel-comet import torch import datasets _A = datasets.logging.get_logger(__name__) _A = """\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel's...
299
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar _A = TypeVar("""T""") _A = TypeVar("""U""") class _lowerCamelCase ( Generic[T, U] ): def __init__( self : List[Any] , Uppe...
299
1
import numpy as np import datasets SCREAMING_SNAKE_CASE__ = ''' Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was in...
702
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_e...
577
0
'''simple docstring''' import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=No...
517
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE_ = "" SCREAMING_SNAKE_CASE_ = "" SCREAMING_SNAKE_CASE_ = "" SCREAMING_SNAKE_CASE_ = 1 # (0 is vertical, 1 is horizontal) def lowerCamelCase__ ( ) -> ...
517
1
from math import loga def a__ ( _UpperCamelCase : int ): if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(_UpperCamelCase ,_UpperCamelCase ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a ==...
622
import torch from diffusers import StableDiffusionPipeline a_ = """path-to-your-trained-model""" a_ = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("""cuda""") a_ = """A photo of sks dog in a bucket""" a_ = pipe(prompt, num_inference_steps=50, guidance_s...
622
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ...
96
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ : Tuple = logging.get_logger(__name__) lowerCamelCase__ : Optional[Any] = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-bas...
698
0
'''simple docstring''' import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever lowerCAmelCase : Dict = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE_...
432
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers im...
432
1
'''simple docstring''' import argparse import os import re _lowerCamelCase = """src/diffusers""" # Pattern that looks at the indentation in a line. _lowerCamelCase = re.compile(R"""^(\s*)\S""") # Pattern that matches `"key":" and puts `key` in group 0. _lowerCamelCase ...
71
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import To...
603
0
'''simple docstring''' from math import isqrt, loga def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): lowercase_ : List[Any] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j...
438
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ....
438
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_c...
417
import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : Any ...
417
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { '''configuration_xlm_roberta''...
718
"""simple docstring""" import argparse import hashlib # hashlib is only used inside the Test class import struct class __lowercase : """simple docstring""" def __init__(self , lowercase__ ): snake_case_ : Union[str, Any] = data s...
48
0
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowerCAmelCase_ = collections.namedtuple('''_Datasets''', ['''train'...
60
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase ) -> list: """simple docstring""" if len(_UpperCamelCase ) == 0: return [] snake_case_ , snake_case_ : Dict = min(_UpperCamelCase ), max(_UpperCamelCase ...
60
1
"""simple docstring""" import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSe...
349
"""simple docstring""" import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixi...
349
1
import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached...
79
'''simple docstring''' from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def lowerCamelCase__ ( A : str = "isbn/0140328726" ): '''simple docstring''' UpperCAmelCase = olid.strip().strip('''/''' ) # Remove leading/tr...
210
0
import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def UpperCamelCase_( lowerCamelCase_ ) -> Optional[Any]: _lowercase : int = test_file.split(os.path.sep ) ...
717
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor fro...
354
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_...
38
"""simple docstring""" def _lowerCamelCase ( UpperCAmelCase_ : Optional[Any] ) -> Dict: """simple docstring""" A__ = [] A__ = set({"(", "[", "{"} ) A__ = set({")", "]", "}"} ) A__ ...
104
0
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers...
430
"""simple docstring""" from statistics import mean import numpy as np def _UpperCAmelCase ( __lowerCamelCase : list , __lowerCamelCase : list , __lowerCamelCase : list , __lowerCamelCase : int ) -> list: _snake_case = 0 # Number of proce...
430
1
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowercase : int = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict , _lowerCamelCase : Li...
557
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): im...
557
1
"""simple docstring""" from __future__ import annotations import requests lowerCamelCase : Union[str, Any] =set( '''approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod...
237
"""simple docstring""" import math def _lowercase ( _SCREAMING_SNAKE_CASE : int ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or num...
237
1
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils impo...
167
import requests __lowercase = '''''' # <-- Put your OpenWeatherMap appid here! __lowercase = '''https://api.openweathermap.org/data/2.5/''' def lowerCamelCase ( SCREAMING_SNAKE_CASE = "Chicago" , SCREAMING_SNAKE_CASE = APPID ): '''simple docstring''' return reques...
167
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, Wav...
711
'''simple docstring''' import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHead...
344
0
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_fi...
496
def __snake_case ( _UpperCamelCase ) -> list: _a = len(_UpperCamelCase ) for i in range(1 , _UpperCamelCase ): _a = collection[i] _a = 0 _a = i - 1 while low <= high: _a = (low + high) // 2 if val < collection[mid]: _a = mi...
487
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import Fla...
719
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/...
77
0
'''simple docstring''' def _snake_case ( A_ : Union[str, Any] = 1000 ): """simple docstring""" a_ : str = 3 a_ : Any = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 ...
577
from numpy import exp, pi, sqrt def UpperCAmelCase ( a_ , a_ = 0.0 , a_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
55
0
from math import factorial def lowerCAmelCase_ ( A_ ,A_): # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive...
711
from collections import namedtuple import requests from lxml import html # type: ignore A__: str = namedtuple('''covid_data''', '''cases deaths recovered''') def lowerCAmelCase_ ( A_ = "https://www.worldometers.info/coronavirus/"): UpperCamelCase__: Union[str,...
221
0
import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Train...
272
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowercase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase = [...
272
1
def a__ ( A_, A_ ): '''simple docstring''' __magic_name__ = len(A_ ) __magic_name__ = len(A_ ) __magic_name__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] __magic_name__ = True for i in range(A_ ): ...
76
import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def a__ ( A_, A_ ): '''simple docstring''' assert i...
76
1
class UpperCAmelCase : '''simple docstring''' def __init__( self : int ,A : List[Any] ): __A = val __A = None __A = None def UpperCamelCase_ ( self : List[str] ,A : Dict ): if self.val: ...
55
"""simple docstring""" from collections import namedtuple UpperCAmelCase = namedtuple("""from_to""", """from_ to""") UpperCAmelCase = { """cubicmeter""": from_to(1, 1), """litre""": from_to(0.001, 1_0_0_0), """kilolitre""": from_to(1, 1), """gallon""": from_to(0.00_454, 264....
535
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCamelCase = {"""configuration_encoder_decoder""": ["""EncoderDecoderConfig"""]} try: ...
719
from functools import reduce UpperCamelCase = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66...
152
0