code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from __future__ import annotations import math def _UpperCAmelCase ( a__): '''simple docstring''' if num <= 0: a_ : Any = f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(a__) a_ : List[Any] = [True] * (num + 1) a_ ...
248
import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class A__(a_ ): """sim...
248
1
"""simple docstring""" import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mode...
157
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _SCREAMING_SNAKE_CASE : str = False class __a (...
157
1
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = abs(__UpperCamelCase ) UpperCamelCase = 0 while n > 0: res += n % 10 n //= 10 return res def lowercase__ ( _...
321
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> bool: return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(__UpperCamelCase ) ) def ...
321
1
def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): # Return True if there is node that has not iterated. _UpperCamelCase : Dict = [False] * len(UpperCAmelCase_ ) _UpperCamelCase : Union[str, Any] = [] queue.app...
368
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MA...
236
0
import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]: ...
230
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } ...
230
1
import logging import os from .state import PartialState class SCREAMING_SNAKE_CASE__ ( logging.LoggerAdapter ): """simple docstring""" @staticmethod def __lowerCamelCase ( __UpperCamelCase ) -> int: '''simple docstring''' __Up...
370
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetC...
171
0
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTok...
340
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( UpperCamelCase_ : int = 3 ) -> qiskit.result.counts.Counts: """simple docstring""" if isinstance(UpperCamelCase_ , Up...
340
1
def lowerCamelCase_ (UpperCamelCase__ : int = 1000 ): _UpperCAmelCase : Tuple = -1 _UpperCAmelCase : Optional[Any] = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c _UpperC...
368
"""simple docstring""" from itertools import count def lowerCamelCase_ (UpperCamelCase__ : int = 50 ): _UpperCAmelCase : Tuple = [1] * min_block_length for n in count(UpperCamelCase__ ): fill_count_functions.append(1 ) for block_length in...
68
0
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
157
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 _snake_case ( _...
157
1
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva lowerCAmelCase_ = '' lowerCAmelCase_ = '' lowerCAmelCase_ = '' lowerCAmelCase_ = 1 # (0 is vertical, ...
302
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score f...
302
1
'''simple docstring''' import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_fl...
346
import numpy # List of input, output pairs _UpperCAmelCase : List[str] = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) _UpperCAmelCase : Optional[Any] = (((515, 22, 13), 555), ((61, 35, 49), 150)) _UpperCAmelCase : Tuple = [2, 4, 1, 5...
236
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 ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() lowerCa...
368
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def UpperCamelCase( lowercase_ , lowercase_ , lowercase_ ) -> Any: '''simple docstring''' snake_case_ = AutoConfig.from_pretrained(lowercase_ ) s...
34
0
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class A ( unittest.TestCase ): __UpperCAmelCase : Dict = in...
65
"""simple docstring""" import os from datetime import datetime as dt from github import Github _A = [ """good first issue""", """feature request""", """wip""", ] def a__ ( ) -> str: UpperCAmelCase__ : Union[str, Any] = Github(os.environ["""GITHUB_TOKEN"""] ...
171
0
"""simple docstring""" import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _A ( UpperCamelCase_ : List[str], UpperCamelCase_ : str, UpperCamelCase_ : Union[str, Any], UpperCamelCase_ : int) -> Dict:...
368
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, ...
144
0
'''simple docstring''' 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=logg...
83
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTest...
68
0
_A = '''Alexander Joslin''' import operator as op from .stack import Stack def lowerCamelCase__ ( a__ : str ) -> int: UpperCamelCase_ = {"""*""": op.mul, """/""": op.truediv, """+""": op.add, """-""": op.sub} UpperCamelCase_ = Stack() ...
261
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _A = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''G...
261
1
from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuroncore, ) from transfo...
302
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[int] =(IPNDMScheduler,) __lowerCamelCase : int =(('num_inference_steps', 50),)...
302
1
'''simple docstring''' import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...im...
31
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput cl...
31
1
"""simple docstring""" import math import random def __SCREAMING_SNAKE_CASE ( A_ , A_ = False ): if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __UpperCamelCase : Any = 0.0_2 def __SCREAMING_SNAKE_CASE ( A_ , A_...
106
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, ...
34
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import req...
352
'''simple docstring''' from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): ...
214
0
import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' snake_case_ = None...
15
"""simple docstring""" 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', leve...
144
0
"""simple docstring""" def lowerCamelCase ( _UpperCamelCase : str ) -> str: '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
320
"""simple docstring""" from __future__ import annotations def lowerCamelCase ( _UpperCamelCase : list[float] , _UpperCamelCase : list[float] ) -> float: '''simple docstring''' __UpperCAmelCase : Tuple = sorted(numsa + numsa ) __Up...
320
1
"""simple docstring""" import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokeniz...
261
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnP...
261
1
import unittest import numpy as np def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , ): """simple docstring""" lowercase__ = np.shape(SCREAMING_SNAKE_CASE ) lowercase__ = ...
364
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class _a : _lowercase : int _lowercase : TreeNode | None = None _lowercase : TreeNode | None = None lowerCAmelCase =...
93
0
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transforme...
31
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from ....
31
1
def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = [0] * len(_A ) SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [1] * len(_A ) for values in graph.values(): for i in values: indegree[i] += 1...
371
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_p...
218
0
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavavec...
107
import math def snake_case__ ( SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' lowercase__ : Optional[Any] = [] lowercase__ : str = 2 lowercase__ : Optional[Any] = int(math.sqrt(SCREAMING_SNAKE_CASE_ ) ) # Size of ever...
214
0
from collections import Counter from timeit import timeit def __lowerCamelCase ( lowerCamelCase__ = "" , ): """simple docstring""" return sum(c % 2 for c in Counter(input_str.replace(" " , "" ).lower() ).values() ) < 2 def __lowerCamelCase ( lowerCamelCase__ =...
121
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class ...
121
1
"""simple docstring""" def A_ ( _lowerCAmelCase : str ): """simple docstring""" return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
320
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from ...
320
1
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def A_ ( snake_case_ : Dataset ,snake_case_ : Dict[str, str] ): '''simple docstring'...
370
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def A_ ( snake_case_ : int ): # picklable for...
27
0
"""simple docstring""" import torch def _snake_case ( ): if torch.cuda.is_available(): UpperCAmelCase : int = torch.cuda.device_count() else: UpperCAmelCase : Optional[int] = 0 print(F"Successfully ran on {num_gpus} GPUs" ) if __name__ == "__main__": main()
109
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_M...
93
0
'''simple docstring''' from __future__ import annotations def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ): if (stress, tangential_force, area).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif stress < 0: raise...
360
'''simple docstring''' # Lint as: python3 import itertools import os import re lowercase__ = re.compile(r"([A-Z]+)([A-Z][a-z])") lowercase__ = re.compile(r"([a-z\d])([A-Z])") lowercase__ = re.compile(r"(?<!_)_(?!_)") lowercase__ = re.compile(r"(_{2...
280
0
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import Ba...
60
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : Tuple = logging.get_logger(__name__) _lowerCAmelCase : Union[str, Any] = {"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"} class __magic_name__ ( lo...
218
0
from math import factorial def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # 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("Pleas...
325
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase__ ='src/di...
325
1
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( a , a , a = 1 , a = 1 , a = 1.0E4 , a = False , a = 1.0 , ) -> jnp.ndarray: assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, f"""Embedding dimensio...
121
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as Prophet...
121
1
'''simple docstring''' def __magic_name__( lowerCamelCase): if num <= 0: raise ValueError('''Input must be a positive integer''') __lowerCAmelCase = [True] * (num + 1) __lowerCAmelCase = 2 while p * p <= num: if...
358
'''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 TokenizerTest...
9
0
import warnings 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 cl...
212
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase : str = { 'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'], 'config...
27
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, apply_forward_hook from .modeling_utils import ModelMixin from .vae import ...
352
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase_ = { '''configuration_efficientformer''': [ '''EFFICIENTFORMER_PRETR...
174
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCamelCase_ = { '''configuration_mega''': ['''MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegaConfig''', '''MegaOnnxConfig'''], } try: if n...
309
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 from torch import nn ...
280
0
"""simple docstring""" import warnings from functools import wraps from typing import Callable def lowercase_ ( __UpperCAmelCase ) -> Callable: """simple docstring""" @wraps(lowercase__ ) def _inner_fn(*__UpperCAmelCase , **__UpperCAmelCase ): ...
351
"""simple docstring""" def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase ) -> str: return "\n".join( f"""{number} * {i} = {number * i}""" for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_term...
212
0
from math import factorial def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ) -> int: # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not po...
325
import math def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> bool: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are prime...
325
1
import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_G...
198
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class UpperCamelCase ( _UpperCAmelCas...
198
1
'''simple docstring''' from math import factorial def lowerCAmelCase (__A = 100): """simple docstring""" return sum(int(lowercase__) for x in str(factorial(lowercase__))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
211
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase : Any ={'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAv...
9
0
import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, ...
370
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import...
323
0
from __future__ import annotations from math import pow, sqrt def a__ ( UpperCAmelCase : str , UpperCAmelCase : int , UpperCAmelCase : Dict ) -> Tuple: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0'...
336
'''simple docstring''' def __magic_name__( lowerCamelCase): __lowerCAmelCase = set() # To detect a back edge, keep track of vertices currently in the recursion stack __lowerCAmelCase = set() return any( node not in visited and depth_first_searc...
174
0
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __UpperCamelCase = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any members...
38
"""simple docstring""" import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbos...
38
1
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path...
212
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...t...
212
1
import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def a__ ...
358
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( lowercase ):...
133
0
'''simple docstring''' import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase ( a__ , unittest.TestCase ): '''simple docstring''...
198
'''simple docstring''' from math import pow def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count +...
198
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-...
92
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _snake_case ( unittest.TestCase , lowercase_ ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstri...
92
1
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ = 10**9 ): __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 while perimeter <= max_p...
100
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class snake_case__ : def __init__( self , lowerCAmelCase__ = None ) -> None: if components is None: __magic_name__ : Any ...
342
0
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean lowercase_ = 0 lowercase_ = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1,...
351
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: lowercase__ = [ 'encoder.version', 'decoder.version', 'm...
269
0
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 UpperCAmelCase_ : List[str] = '''sshleifer/bart-tin...
38
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_available(): import tor...
38
1
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase_ = "src/...
344
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class a_ ( _snake_case ): UpperCamelCase__ : List[Any] =(PNDMScheduler,) UpperCamelCase__ : Optional[Any] =(("num_inference_steps", 50),) ...
344
1
from math import factorial def A ( a_ ,a_ ) -> int: # 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...
71
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from tr...
133
0
'''simple docstring''' from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder lowerCAmelCase :Tuple = datasets.utils.logging.get_logger(__name__) class _lowerCamelCase ( folder_based_builder.FolderBasedBu...
358
'''simple docstring''' def lowerCamelCase ( lowerCAmelCase : str ): """simple docstring""" if not all(x.isalpha() for x in string ): raise ValueError('String must only contain alphabetic characters.' ) __magic_name__ : int = sorted(string.lower() ) return len(l...
275
0
import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : float = 1E-12 , SCREAMING_SNAKE_CASE_ : int = 1_00 , ): assert np.shape(SCREAMING_SNAKE_CA...
92
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_S...
92
1
UpperCAmelCase_ = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'data...
29
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState ...
29
1
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): lowerCAmelCase__ = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections...
104
"""simple docstring""" from ..utils import DummyObject, requires_backends class A__ ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = ['torch', 'torchsde'] def __init__( self: int , *_SCREAMING_SNAK...
269
0
'''simple docstring''' import inspect import unittest from transformers import YolosConfig 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_configuration_common import ...
43
'''simple docstring''' import numpy as np def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 1e-12 , _lowerCAmelCase = 100 , ) -> tuple[float, np.ndarray]: assert np.shape(_lowerCAmelCase )[0] == np.shape(_lowerCAmelCase )[1]...
43
1
'''simple docstring''' import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/c...
344
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : Any = logging.get_logger(__name__) UpperCamelCase__ :...
344
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def SCREAMING_SNAKE_CASE__ ( lowercase ) -> Dict: snake_c...
368
from math import pow def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,) -> tuple[int, int]: if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 ...
176
0
'''simple docstring''' from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def __lowerCAmelCase ( ) -> tuple[list[int], int]: __lowerCamelCase = [randint(-10_00 , 10_00 ) for i in range(10 )] __lowerCamelCase ...
67
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _UpperCamelCase = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller tha...
275
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase = { """configuration_pegasus_x""": ["""PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PegasusXConfig"""], } try: if not is_torch_available(): ...
48
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/confi...
48
1
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is...
29
from __future__ import annotations def lowercase__ ( __snake_case : tuple[int, int] , __snake_case : int ): '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ : Tuple = position UpperCAmelCas...
29
1
'''simple docstring''' import os from collections.abc import Iterator def lowerCAmelCase_ ( snake_case_ : str = "." ) -> Iterator[str]: '''simple docstring''' for dir_path, dir_names, filenames in os.walk(snake_case_ ): UpperCAmelCase_ = [d for d in ...
106
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers i...
106
1
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClas...
43
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel ...
43
1
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule A_ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys A_ = _LazyModule(__name...
361
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int = 10_00 ): """simple docstring""" _snake_case , _snake_case : List[Any] = 1, 1 _snake_case : str = [] for i in range(1 , n + 1 ): _snake_case : Any = prev_num...
132
0
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils...
70
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_ver...
176
0
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging lowercase__ =...
280
'''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 ...
280
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Tuple = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): rai...
48
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {'configuration_mmbt': ['MMBTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAv...
48
1
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def lowerCamelCase__ ( _lowercase ): '''simple docstrin...
235
from random import shuffle import tensorflow as tf from numpy import array def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' UpperCAmelCase_ : Union[str, Any] = int(_lowercase ) assert noofclusters < len(_lowercase ) ...
235
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDepend...
106
"""simple docstring""" __UpperCamelCase : Optional[Any] = [ 9_9_9, 8_0_0, 7_9_9, 6_0_0, 5_9_9, 5_0_0, 4_0_0, 3_9_9, 3_7_7, 3_5_5, 3_3_3, 3_1_1, 2_8_8, 2_6_6, 2_4_4, 2_2_2, 2_0_0, 1_9_9, 1_7_7, 1_5_5, 1_3_3, ...
106
1
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def __lowerCamelCase ( __snake_case : list, __snake_case : list, __snake_case : list, __snake_c...
359
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( __snake_case : list[int] ) -> bool: """simple docstring""" return len(set(__snake_case ) ) == len(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
136
0
import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging __snake_case = lo...
259
"""simple docstring""" def _lowercase ( ) -> int: return [ a * b * (1000 - a - b) for a in range(1 , 999 ) for b in range(__lowerCAmelCase , 999 ) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": ...
132
0
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_...
352
"""simple docstring""" def _snake_case ( _snake_case : int ): assert isinstance(_snake_case , _snake_case ), f'''The input value of [n={number}] is not an integer''' if number == 1: return 2 elif number < 1: lowerCAmelCase : Tuple = f...
314
0
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_atten...
280
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils im...
280
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : Tuple = { """configuration_informer""": [ """INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """...
357
'''simple docstring''' a_ : List[Any] = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def a_ ( __snake_case : int ) -> int: """simple docstring""" lowerCamelCase_ =0 while number: # I...
6
0
from argparse import ArgumentParser from . import BaseTransformersCLICommand def __UpperCAmelCase ( __a : List[str] ) -> Optional[Any]: """simple docstring""" return DownloadCommand(args.model ,args.cache_dir ,args.force ,args.trust_remote_code ) class ...
235
from collections.abc import Callable class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a = None ) -> None: # Stores actual heap items. _a : list = [] # Stores indexes of each item fo...
235
1
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def UpperCAmelCase ( lowerCamelCase_ :str ): ''...
350
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @requi...
8
0
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def __lowerCamelCase ( A__ ...
28
"""simple docstring""" from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = "T5...
136
0
import collections import importlib.util import os import re from pathlib import Path UpperCamelCase__ ='src/transformers' # Matches is_xxx_available() UpperCamelCase__ =re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} UpperCamelCase__ =re.compile(R'^_...
353
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ...
325
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. 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...
22
from ...configuration_utils import PretrainedConfig _SCREAMING_SNAKE_CASE : Optional[Any] = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://...
314
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_vit_mae""": ["""VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """V...
112
"""simple docstring""" import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _lowerCAmelCase ( ...
112
1
def a ( snake_case__: int = 100 ): '''simple docstring''' lowercase_ = (n * (n + 1) // 2) ** 2 lowercase_ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
30
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def __lowerCAmelCase ( a__ , a__ , a__ = 1 / sqrt(2 ) ) -> IIRFilter: __a = tau * frequency / samplerate __a = sin(a__ ) __a = cos(a__ ) __a ...
6
0
from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
359
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowerCAmelCase_ ( lowerCamelCase__ ): '''simple docstring''' def __init__( ...
267
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase_ = { 'configuration_blip_2': [ 'BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Blip2Config', 'Blip2QFormerConfig', ...
243
from decimal import Decimal, getcontext from math import ceil, factorial def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('''Undefined for non-integers''' ) elif pre...
8
0
"""simple docstring""" A : List[Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0 while number: # Increased Speed Slig...
356
"""simple docstring""" from __future__ import annotations import time A : Union[str, Any] = list[tuple[int, int]] A : int = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, ...
259
0
import requests __snake_case = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=""" def _A ( SCREAMING_SNAKE_CASE__ : str ): # fetching a list of articles in json format UpperCamelCase :Tuple = requests.get(_NEWS_API + bbc_news_api_key ...
259
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: ...
325
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): ra...
356
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _lowerCAmelCase = 10 def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase...
184
0
'''simple docstring''' from __future__ import annotations from typing import Any def lowerCAmelCase_ ( _lowerCamelCase: list ): if not postfix_notation: return 0 __SCREAMING_SNAKE_CASE : Any = {"""+""", """-""", """*""", """/"""} __SCREAMING_SNAKE_CASE : list[A...
112
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) U...
112
1
"""simple docstring""" from math import ceil def lowercase__( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple ): lowercase_ : List[Any] = list(range(0 , __SCREAMING_SNAKE_CASE ) ) lowercase_ : List[Any]...
321
"""simple docstring""" class UpperCamelCase : def __init__( self ,__UpperCamelCase ) -> None: '''simple docstring''' lowercase_ : int = set_counts lowercase_ : List[Any] = max(__UpperCamelCase ) lower...
321
1
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_co...
90
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: Up...
267
0
import inspect import unittest from transformers import ViTMSNConfig 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_configuration_common import ConfigTester...
367
'''simple docstring''' def _lowerCAmelCase ( lowerCamelCase_ : int = 6_0_0_8_5_1_4_7_5_1_4_3 ): try: __lowercase = int(lowerCamelCase_ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n ...
217
0
# Copyright 2023 The HuggingFace Inc. 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 ...
259
from __future__ import annotations from typing import Any def _A ( SCREAMING_SNAKE_CASE__ : list[Any] ): create_state_space_tree(SCREAMING_SNAKE_CASE__ , [] , 0 ) def _A ( SCREAMING_SNAKE_CASE__ : list[Any] , SCREAMING_SNAKE_CASE__ : list[Any] , SCREAMING...
259
1
import os def __UpperCamelCase ( lowerCAmelCase__ : str = "input.txt" ): with open(os.path.join(os.path.dirname(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) as input_file: __a : Any = [ [int(lowerCAmelCase__ ) for element in line.split(''',''' )] for line i...
368
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart impor...
90
0
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_al...
24
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, Com...
184
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, log...
351
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel _UpperCamelCase = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn"...
234
0
'''simple docstring''' from math import ceil def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Tuple: UpperCamelCase = list(range(0 , __UpperCamelCase ) ) UpperCamelCase = [item for sublist in list(device_map.values(...
321
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 UpperCamelCase = 1 UpperCamelCase = 1 while repunit: UpperCamelCase = (10 * repunit + 1) % di...
321
1
import re def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = re.compile(R'''^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$''' ) if match := re.search(lowercase__ , lowercase__ ): return match.string == phone return False if __name_...
362
import argparse import copy def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = {} with open(_A ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE__ = [] ...
218
0