id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
177,974
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `get_closure` function. Write a Python function `def get_closure(f)` to solve the following problem: Get a fun...
Get a function's closure attribute
177,975
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `u_format` function. Write a Python function `def u_format(s)` to solve the following problem: {u}'abc'" --> "...
{u}'abc'" --> "u'abc'" (Python 2) Accepts a string or a function, so it can be used as a decorator.
177,976
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform def execfile(fname, glob=None, loc=None, compiler=None): loc = loc if (loc is not None) else glob scripttext = builtin_mod.open(fname).read()+ '\n' # com...
null
177,977
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING def encode(u, encoding=None): encoding = encoding or DEFAULT_ENCODING return u.encode(encoding, "replace") import platform if sys.version_info[0] >= 3 or platform.python_implementation() == 'IronPyt...
null
177,978
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `annotate` function. Write a Python function `def annotate(**kwargs)` to solve the following problem: Python 3...
Python 3 compatible function annotation for Python 2.
177,979
import functools import os import sys import re import shutil import types from .encoding import DEFAULT_ENCODING import platform The provided code snippet includes necessary dependencies for implementing the `with_metaclass` function. Write a Python function `def with_metaclass(meta, *bases)` to solve the following p...
Create a base class with a metaclass.
177,980
The provided code snippet includes necessary dependencies for implementing the `import_item` function. Write a Python function `def import_item(name)` to solve the following problem: Import and return ``bar`` given the string ``foo.bar``. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of execut...
Import and return ``bar`` given the string ``foo.bar``. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of executing the code ``from foo import bar``. Parameters ---------- name : string The fully qualified name of the module/package being imported. Returns ------- mod : module object The module t...
177,981
import errno import os import site import stat import sys import tempfile import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Dict, Iterator, List, Optional import platformdirs from .utils import deprecation Any = object() Optional: _SpecialForm = ... The provide...
Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional The resul...
177,982
import errno import os import site import stat import sys import tempfile import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Dict, Iterator, List, Optional import platformdirs from .utils import deprecation UF_HIDDEN = getattr(stat, "UF_HIDDEN", 32768) Any = object()...
Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional The resul...
177,983
import errno import os import site import stat import sys import tempfile import warnings from contextlib import contextmanager from pathlib import Path from typing import Any, Dict, Iterator, List, Optional import platformdirs from .utils import deprecation UF_HIDDEN = getattr(stat, "UF_HIDDEN", 32768) def exists(path...
Is a file hidden or contained in a hidden directory? This will start with the rightmost path element and work backwards to the given root to see if a path is hidden or in a hidden directory. Hidden is determined by either name starting with '.' or the UF_HIDDEN flag as reported by stat. If abs_path is the same director...
177,984
import argparse import errno import json import os import site import sys import sysconfig from shutil import which from subprocess import Popen from typing import List from . import paths from .version import __version__ class JupyterParser(argparse.ArgumentParser): """A Jupyter argument parser.""" def epilog(...
Create a jupyter parser object.
177,985
import argparse import errno import json import os import site import sys import sysconfig from shutil import which from subprocess import Popen from typing import List from . import paths from .version import __version__ class Popen(Generic[AnyStr]): args: _CMD stdin: Optional[IO[AnyStr]] stdout: Optional...
execvp, except on Windows where it uses Popen Python provides execvp on Windows, but its behavior is problematic (Python bug#9148).
177,986
import argparse import errno import json import os import site import sys import sysconfig from shutil import which from subprocess import Popen from typing import List from . import paths from .version import __version__ def _path_with_self(): """Put `jupyter`'s dir at the front of PATH Ensures that /path/to/j...
This method get the abspath of a specified jupyter-subcommand with no changes on ENV.
177,987
import argparse import errno import json import os import site import sys import sysconfig from shutil import which from subprocess import Popen from typing import List from . import paths from .version import __version__ class JupyterParser(argparse.ArgumentParser): """A Jupyter argument parser.""" def epilog(...
If argcomplete is enabled, trigger autocomplete or return current words If the first word looks like a subcommand, return the current command that is attempting to be completed so that the subcommand can evaluate it; otherwise auto-complete using the main parser.
177,988
import os import re import shutil from datetime import datetime, timezone from traitlets.config.loader import JSONFileConfigLoader, PyFileConfigLoader from traitlets.log import get_logger from .application import JupyterApp from .paths import jupyter_config_dir, jupyter_data_dir from .utils import ensure_dir_exists mig...
Migrate IPython configuration to Jupyter
177,989
import os import platform import subprocess import sys from typing import Any, Dict, List, Optional, Union def subs(cmd: Union[List[str], str]) -> Optional[str]: """ get data from commands that we need to run outside of python """ try: stdout = subprocess.check_output(cmd) return stdout....
returns a dict of various user environment data
177,991
import collections import itertools import re from typing import Callable, Optional, SupportsInt, Tuple, Union from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType class Version(_BaseVersion): """This class abstracts handling of a project's versions. A :class:`Version` instanc...
Parse the given version string. >>> parse('1.0.dev1') <Version('1.0.dev1')> :param version: The version string to parse. :raises InvalidVersion: When the version string is not a valid version.
177,992
import collections import itertools import re from typing import Callable, Optional, SupportsInt, Tuple, Union from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType Union: _SpecialForm = ... Optional: _SpecialForm = ... class SupportsInt(Protocol, metaclass=ABCMet...
null
177,993
import collections import itertools import re from typing import Callable, Optional, SupportsInt, Tuple, Union from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType LocalType = Union[ NegativeInfinityType, Tuple[ Union[ SubLocalType, Tuple[SubLoc...
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
177,994
import collections import itertools import re from typing import Callable, Optional, SupportsInt, Tuple, Union from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType PrePostDevType = Union[InfiniteTypes, Tuple[str, int]] SubLocalType = Union[InfiniteTypes, int, str] LocalType = Union[ ...
null
177,995
import re from typing import FrozenSet, NewType, Tuple, Union, cast from .tags import Tag, parse_tag from .version import InvalidVersion, Version Union: _SpecialForm = ... class InvalidVersion(ValueError): """Raised when a version string is not a valid version. >>> Version("invalid") Traceback (most rece...
This is very similar to Version.__str__, but has one subtle difference with the way it handles the release segment.
177,996
import re from typing import FrozenSet, NewType, Tuple, Union, cast from .tags import Tag, parse_tag from .version import InvalidVersion, Version BuildTag = Union[Tuple[()], Tuple[int, str]] NormalizedName = NewType("NormalizedName", str) class InvalidWheelFilename(ValueError): """ An invalid wheel filename was...
null
177,997
import re from typing import FrozenSet, NewType, Tuple, Union, cast from .tags import Tag, parse_tag from .version import InvalidVersion, Version NormalizedName = NewType("NormalizedName", str) class InvalidSdistFilename(ValueError): """ An invalid sdist filename was found, users should refer to the packaging u...
null
177,998
import logging import platform import subprocess import sys import sysconfig from importlib.machinery import EXTENSION_SUFFIXES from typing import ( Dict, FrozenSet, Iterable, Iterator, List, Optional, Sequence, Tuple, Union, cast, ) from . import _manylinux, _musllinux class Tag...
Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important.
177,999
import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ._parser import MarkerAtom, MarkerList, Op, Value, Variable, parse_marker from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canoni...
Normalize extra values.
178,000
import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ._parser import MarkerAtom, MarkerList, Op, Value, Variable, parse_marker from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canoni...
null
178,001
import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ._parser import MarkerAtom, MarkerList, Op, Value, Variable, parse_marker from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canoni...
null
178,002
import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ._parser import MarkerAtom, MarkerList, Op, Value, Variable, parse_marker from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canoni...
null
178,003
import ast from typing import Any, List, NamedTuple, Optional, Tuple, Union from ._tokenizer import DEFAULT_RULES, Tokenizer class ParsedRequirement(NamedTuple): def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = { "LEFT_PARENTHESIS": r"\(",...
null
178,004
import ast from typing import Any, List, NamedTuple, Optional, Tuple, Union from ._tokenizer import DEFAULT_RULES, Tokenizer MarkerList = List[Any] def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] w...
null
178,005
import abc import itertools import re from typing import ( Callable, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union, ) from .utils import canonicalize_version from .version import Version UnparsedVersion = Union[Version, str] class Version(_BaseVersion): def __i...
null
178,006
import abc import itertools import re from typing import ( Callable, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union, ) from .utils import canonicalize_version from .version import Version _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") List = _Alias() ...
null
178,007
import abc import itertools import re from typing import ( Callable, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union, ) from .utils import canonicalize_version from .version import Version def _is_not_suffix(segment: str) -> bool: return not any( segment.s...
null
178,008
import abc import itertools import re from typing import ( Callable, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union, ) from .utils import canonicalize_version from .version import Version List = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self):...
null
178,009
from __future__ import print_function, absolute_import import sys import warnings from xml.etree.ElementTree import ParseError from xml.etree.ElementTree import TreeBuilder as _TreeBuilder from xml.etree.ElementTree import parse as _parse from xml.etree.ElementTree import tostring from .common import PY3 from .common i...
Python 3.3 hides the pure Python code but defusedxml requires it. The code is based on test.support.import_fresh_module().
178,010
from __future__ import print_function, absolute_import import threading import warnings from lxml import etree as _etree from .common import DTDForbidden, EntitiesForbidden, NotSupportedError getDefaultParser = _parser_tls.getDefaultParser def check_docinfo(elementtree, forbid_dtd=False, forbid_entities=True): """C...
null
178,011
from __future__ import print_function, absolute_import import threading import warnings from lxml import etree as _etree from .common import DTDForbidden, EntitiesForbidden, NotSupportedError getDefaultParser = _parser_tls.getDefaultParser def check_docinfo(elementtree, forbid_dtd=False, forbid_entities=True): """C...
null
178,012
from __future__ import print_function, absolute_import import threading import warnings from lxml import etree as _etree from .common import DTDForbidden, EntitiesForbidden, NotSupportedError class NotSupportedError(DefusedXmlException): """The operation is not supported""" def iterparse(*args, **kwargs): rai...
null
178,013
from __future__ import print_function, absolute_import from xml.dom.minidom import _do_pulldom_parse from . import expatbuilder as _expatbuilder from . import pulldom as _pulldom The provided code snippet includes necessary dependencies for implementing the `parse` function. Write a Python function `def parse( fil...
Parse a file into a DOM by filename or file object.
178,014
from __future__ import print_function, absolute_import from xml.dom.minidom import _do_pulldom_parse from . import expatbuilder as _expatbuilder from . import pulldom as _pulldom The provided code snippet includes necessary dependencies for implementing the `parseString` function. Write a Python function `def parseStr...
Parse a file into a DOM from a string.
178,015
from __future__ import print_function, absolute_import import io from .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden, PY3 def defused_gzip_decode(data, limit=None): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ ...
null
178,016
from __future__ import print_function, absolute_import import io from .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden, PY3 def gzip_decode(data: str, max_decode: int = ...) -> str: ... class GzipDecodedResponse(GzipFile): stringio: StringIO[Any] def __init__(self, response: HTTPResp...
null
178,017
from __future__ import print_function, absolute_import from xml.dom.expatbuilder import ExpatBuilder as _ExpatBuilder from xml.dom.expatbuilder import Namespaces as _Namespaces from .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden class DefusedExpatBuilder(_ExpatBuilder): """Defused docume...
Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object.
178,018
from __future__ import print_function, absolute_import from xml.dom.expatbuilder import ExpatBuilder as _ExpatBuilder from xml.dom.expatbuilder import Namespaces as _Namespaces from .common import DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden class DefusedExpatBuilder(_ExpatBuilder): """Defused docume...
Parse a document from a string, returning the resulting Document node.
178,019
from __future__ import print_function, absolute_import from xml.dom.pulldom import parse as _parse from xml.dom.pulldom import parseString as _parseString from .sax import make_parser def make_parser(parser_list=[]): return expatreader.create_parser() def parse( stream_or_string, parser=None, bufsize=...
null
178,020
from __future__ import print_function, absolute_import from xml.dom.pulldom import parse as _parse from xml.dom.pulldom import parseString as _parseString from .sax import make_parser def make_parser(parser_list=[]): return expatreader.create_parser() def parseString( string, parser=None, forbid_dtd=False, fo...
null
178,021
import sys import xml.parsers.expat def _apply_defusing(defused_mod): assert defused_mod is sys.modules[defused_mod.__name__] stdlib_name = defused_mod.__origin__ __import__(stdlib_name, {}, {}, ["*"]) stdlib_mod = sys.modules[stdlib_name] stdlib_names = set(dir(stdlib_mod)) for name, obj in va...
null
178,022
import sys import xml.parsers.expat The provided code snippet includes necessary dependencies for implementing the `_generate_etree_functions` function. Write a Python function `def _generate_etree_functions(DefusedXMLParser, _TreeBuilder, _parse, _iterparse)` to solve the following problem: Factory for functions need...
Factory for functions needed by etree, dependent on whether cElementTree or ElementTree is used.
178,023
from __future__ import print_function, absolute_import from xml.sax import InputSource as _InputSource from xml.sax import ErrorHandler as _ErrorHandler from . import expatreader def parse( source, handler, errorHandler=_ErrorHandler(), forbid_dtd=False, forbid_entities=True, forbid_external=Tru...
null
178,024
import glob import os import shutil import sys import sysconfig try: import winreg as winreg except: import winreg import tempfile if sys.stdout is None: sys.stdout = sys.stderr sys.stderr = Tee(sys.stderr) sys.stdout = Tee(sys.stdout) verbose = 1 root_key_name = "Software\\Python\\PythonCore\\" + sys.winve...
null
178,025
import glob import os import shutil import sys import sysconfig import tempfile if sys.stdout is None: sys.stdout = sys.stderr sys.stderr = Tee(sys.stderr) sys.stdout = Tee(sys.stdout) verbose = 1 def LoadSystemModule(lib_dir, modname): # See if this is a debug build. import importlib.machinery import i...
null
178,026
import glob import os import shutil import sys import sysconfig import tempfile def verify_destination(location): if not os.path.isdir(location): raise argparse.ArgumentTypeError('Path "{}" does not exist!'.format(location)) return location
null
178,027
from flask import Flask, render_template, request, redirect import os import pandas as pd import matplotlib.pyplot as plt import base64 from io import BytesIO from wordcloud import WordCloud import snscrape.modules.twitter as sntwitter from tqdm.notebook import tqdm_notebook import datetime import re from textblob impo...
null
178,028
from flask import Flask, render_template, request, redirect import os import pandas as pd import matplotlib.pyplot as plt import base64 from io import BytesIO from wordcloud import WordCloud import snscrape.modules.twitter as sntwitter from tqdm.notebook import tqdm_notebook import datetime import re from textblob impo...
null
178,029
from setuptools import setup, find_packages from typing import List HYPEN_E_DOT='-e .' List = _Alias() def get_requirements(file_path:str)->List[str]: requirements=[] with open(file_path) as file_obj: requirements=file_obj.readlines() requirements=[req.replace("\n","") for req in requirements]...
null
178,030
import os import sys import pickle import numpy as np import pandas as pd from src.Heart.logger import logging from sklearn.metrics import accuracy_score from src.Heart.exception import customexception import os import sys if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py ...
null
178,031
import os import sys import pickle import numpy as np import pandas as pd from src.Heart.logger import logging from sklearn.metrics import accuracy_score from src.Heart.exception import customexception import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid(...
null
178,032
import os import sys import pickle import numpy as np import pandas as pd from src.Heart.logger import logging from sklearn.metrics import accuracy_score from src.Heart.exception import customexception import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid(...
null
178,033
from flask import Flask, request, render_template from src.Heart.pipeline.Prediction_pipeline import CustomData, PredictPipeline class PredictPipeline: def __init__(self): pass def predict(self,features): try: preprocessor_path=os.path.join("Artifacts","Preprocessor.pkl") ...
null
178,035
import os import sys import pickle import numpy as np import pandas as pd from src.DiamondPricePrediction.logger import logging from src.DiamondPricePrediction.exception import customexception from sklearn.metrics import r2_score, mean_absolute_error,mean_squared_error import os import sys if os....
null
178,036
import os import sys import pickle import numpy as np import pandas as pd from src.DiamondPricePrediction.logger import logging from src.DiamondPricePrediction.exception import customexception from sklearn.metrics import r2_score, mean_absolute_error,mean_squared_error import sys if sys.platfor...
null
178,037
import os import sys import pickle import numpy as np import pandas as pd from src.DiamondPricePrediction.logger import logging from src.DiamondPricePrediction.exception import customexception from sklearn.metrics import r2_score, mean_absolute_error,mean_squared_error import sys if sys.platfor...
null
178,038
from src.DiamondPricePrediction.pipelines.Prediction_Pipeline import CustomData,PredictPipeline from flask import Flask,request,render_template,jsonify class PredictPipeline: def __init__(self): pass def predict(self,features): try: preprocessor_path=os.path.join("Artifacts","p...
null
178,039
from chain_retriever import * from utils import * def read_root(): return {"Welcome": "to the Codebasics FAQs API"}
null
178,040
from chain_retriever import * from utils import * def retrieve_qa(querybody: QueryBody): # Use the QA retriever to get the QA chain qa_chain = qa_retriever.get_qa_chain( temperature=querybody.temperature, max_output_tokens=querybody.max_output_tokens, ) # You might need to adapt this pa...
null
178,041
import streamlit as st import keras import tensorflow as tf import requests import numpy as np import nltk import spacy from nltk.corpus import stopwords from tqdm import tqdm import pandas as pd import pycountry from keras.preprocessing.text import one_hot,Tokenizer from keras.utils import pad_sequences import datetim...
null
178,042
import streamlit as st import keras import tensorflow as tf import requests import numpy as np import nltk import spacy from nltk.corpus import stopwords from tqdm import tqdm import pandas as pd import pycountry from keras.preprocessing.text import one_hot,Tokenizer from keras.utils import pad_sequences import datetim...
null
178,043
import streamlit as st import keras import tensorflow as tf import requests import numpy as np import nltk import spacy from nltk.corpus import stopwords from tqdm import tqdm import pandas as pd import pycountry from keras.preprocessing.text import one_hot,Tokenizer from keras.utils import pad_sequences import datetim...
null
178,044
import streamlit as st import keras import tensorflow as tf import requests import numpy as np import nltk import spacy from nltk.corpus import stopwords from tqdm import tqdm import pandas as pd import pycountry from keras.preprocessing.text import one_hot,Tokenizer from keras.utils import pad_sequences import datetim...
null
178,045
import streamlit as st import keras import tensorflow as tf import requests import numpy as np import nltk import spacy from nltk.corpus import stopwords from tqdm import tqdm import pandas as pd import pycountry from keras.preprocessing.text import one_hot,Tokenizer from keras.utils import pad_sequences import datetim...
null
178,046
from keyword_extract import extract_keywords import re import spacy nlp = spacy.load("en_core_web_sm") def extract_entities(text): doc = nlp(text) entities = { "name": [], "location": [], "skills": [], "keywords": [] } for ent in doc.ents: if ent.label_ == "PERS...
null
178,047
from keyword_extract import extract_keywords import re import spacy def extract_phone_numbers(text): phone_numbers = re.findall(r'\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b', text) return phone_numbers
null
178,048
from keyword_extract import extract_keywords import re import spacy def extract_emails(text): emails = re.findall(r'\S+@\S+', text) return emails
null
178,049
from keyword_extract import extract_keywords import re import spacy nlp = spacy.load("en_core_web_sm") def extract_keywords(text): # Process the text with spaCy doc = nlp(text) # Extract keywords based on relevant criteria (e.g., noun phrases) keywords = [chunk.text for chunk in doc.noun_chunks] ...
null
178,050
from flask import Flask, render_template, request, redirect, url_for from ocr_engine import OCREngine from pdf_extractor import extract_text_from_pdf from utils.helper import allowed_file, save_uploaded_file from keyword_extract import extract_keywords from yake import KeywordExtractor import os import spacy import yak...
null
178,051
import argparse, os, sys, datetime, glob, importlib, csv import numpy as np import time import torch import torchvision import pytorch_lightning as pl from packaging import version from omegaconf import OmegaConf from torch.utils.data import random_split, DataLoader, Dataset, Subset from functools import partial from P...
null
178,052
import argparse, os, sys, datetime, glob, importlib, csv import numpy as np import time import torch import torchvision import pytorch_lightning as pl from packaging import version from omegaconf import OmegaConf from torch.utils.data import random_split, DataLoader, Dataset, Subset from functools import partial from P...
null
178,053
import argparse, os, sys, datetime, glob, importlib, csv import numpy as np import time import torch import torchvision import pytorch_lightning as pl from packaging import version from omegaconf import OmegaConf from torch.utils.data import random_split, DataLoader, Dataset, Subset from functools import partial from P...
null
178,054
import argparse, os, sys, datetime, glob, importlib, csv import numpy as np import time import torch import torchvision import pytorch_lightning as pl from packaging import version from omegaconf import OmegaConf from torch.utils.data import random_split, DataLoader, Dataset, Subset from functools import partial from P...
null
178,055
import argparse, os, sys, datetime, glob, importlib, csv import numpy as np import time import torch import torchvision import pytorch_lightning as pl from packaging import version from omegaconf import OmegaConf from torch.utils.data import random_split, DataLoader, Dataset, Subset from functools import partial from P...
null
178,056
import argparse, os, sys, glob import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from imwatermark import WatermarkEncoder from itertools import islice from einops import rearrange from torchvision.utils import make_grid import time from pytorc...
null
178,057
import argparse, os, sys, glob import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from imwatermark import WatermarkEncoder from itertools import islice from einops import rearrange from torchvision.utils import make_grid import time from pytorc...
null
178,058
import argparse, os, sys, glob import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from imwatermark import WatermarkEncoder from itertools import islice from einops import rearrange from torchvision.utils import make_grid import time from pytorc...
null
178,059
import argparse, os, sys, glob import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from imwatermark import WatermarkEncoder from itertools import islice from einops import rearrange from torchvision.utils import make_grid import time from pytorc...
null
178,060
import argparse, os, sys, glob import cv2 import torch import numpy as np from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from imwatermark import WatermarkEncoder from itertools import islice from einops import rearrange from torchvision.utils import make_grid import time from pytorc...
null
178,103
import math import torch as th import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `convert_module_to_f16` function. Write a Python function `def convert_module_to_f16(l)` to solve the following problem: Convert primitive modules to float16. Here is the function: def ...
Convert primitive modules to float16.
178,111
from __future__ import absolute_import from __future__ import division from __future__ import print_function import imp import os from io import BytesIO import json import logging import base64 from sys import prefix import threading import random from turtle import left, right import numpy as np from typing import Cal...
null
178,112
from __future__ import absolute_import from __future__ import division from __future__ import print_function import imp import os from io import BytesIO import json import logging import base64 from sys import prefix import threading import random from turtle import left, right import numpy as np from typing import Cal...
null
178,113
from __future__ import absolute_import from __future__ import division from __future__ import print_function import imp import os from io import BytesIO import json import logging import base64 from sys import prefix import threading import random from turtle import left, right import numpy as np from typing import Cal...
null
178,115
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning...
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
178,116
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning...
null
178,117
import torch import torch.nn as nn import torch.nn.functional as F import torchvision import clip FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' def _inception_v3(*args, **kwargs): """Wraps `torchvision.models.inception_v3` Skips d...
Build pretrained Inception model for FID computation The Inception model for FID computation uses a different set of weights and has a slightly different structure than torchvision's Inception. This method first constructs torchvision's Inception and then patches the necessary parts that are different in the FID Incept...
178,118
import os import pathlib from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser import numpy as np import torch import torchvision.transforms as TF from PIL import Image from scipy import linalg from torch.nn.functional import adaptive_avg_pool2d import clip from inception import InceptionV3 def calculate_f...
Calculates the FID of two paths
178,120
import os import pathlib from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import numpy as np import torch from scipy import linalg from PIL import Image from torch.nn.functional import adaptive_avg_pool2d import pickle from scipy.stats import multivariate_normal from sklearn import mixture from incept...
null
178,122
import argparse import itertools import json import os import random import time from functools import partial from typing import Optional import torch from tqdm import tqdm from PIL import Image from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN from mplug_owl2.conversation import conv_templates, ...
null
178,123
import argparse import itertools import json import os import random import time from functools import partial from typing import Optional import torch from tqdm import tqdm from PIL import Image from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN from mplug_owl2.conversation import conv_templates, ...
null
178,124
import argparse import itertools import json import os import random import time from functools import partial import torch from pycocoevalcap.eval import COCOEvalCap from pycocotools.coco import COCO from tqdm import tqdm from PIL import Image from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN fro...
null
178,125
import argparse import itertools import json import os import random import time from functools import partial from typing import Optional import torch from tqdm import tqdm from PIL import Image import pandas as pd from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN from mplug_owl2.conversation imp...
null
178,126
import argparse import itertools import json import os import random import time from functools import partial from typing import Optional import torch from tqdm import tqdm from PIL import Image import pandas as pd from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN from mplug_owl2.conversation imp...
null
178,127
import argparse import itertools import json import os import random import time from functools import partial from typing import Optional import torch from tqdm import tqdm from PIL import Image import pandas as pd from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN from mplug_owl2.conversation imp...
null