id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
167,765 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Create composite image by blending images using a transparency mask. :param image1: The first image. :param image2: The second image. Must have the same mode and size as the first image. :param mask: A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images. |
167,766 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators. :param image: The input... |
167,767 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Register an image file plugin. This function should not be used in application code. :param id: An image format identifier. :param factory: An image file factory method. :param accept: An optional function that can be used to quickly reject images having another format. |
167,768 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Registers an image MIME type. This function should not be used in application code. :param id: An image format identifier. :param mimetype: The image MIME type for this format. |
167,769 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Registers an image save function. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. |
167,770 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Registers an image function to save all the frames of a multiframe format. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. |
167,771 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Registers image extensions. This function should not be used in application code. :param id: An image format identifier. :param extensions: A list of extensions used for this format. |
167,772 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Returns a dictionary containing all file extensions belonging to registered plugins |
167,773 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Registers an image decoder. This function should not be used in application code. :param name: The name of the decoder :param decoder: A callable(mode, args) that returns an ImageFile.PyDecoder object .. versionadded:: 4.1.0 |
167,774 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Registers an image encoder. This function should not be used in application code. :param name: The name of the encoder :param encoder: A callable(mode, args) that returns an ImageFile.PyEncoder object .. versionadded:: 4.1.0 |
167,775 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | null |
167,776 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Generate a Mandelbrot set covering the given extent. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param extent: The extent to cover, as a 4-tuple: (x0, y0, x1, y2). :param quality: Quality. |
167,777 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Generate Gaussian noise centered around 128. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param sigma: Standard deviation of noise. |
167,778 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Generate 256x256 linear gradient from black to white, top to bottom. :param mode: Input mode. |
167,779 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | Generate 256x256 radial gradient from black to white, centre to edge. :param mode: Input mode. |
167,780 | import atexit
import builtins
import io
import logging
import math
import numbers
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from pathlib import Path
from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins
fr... | null |
167,781 | import olefile
from . import Image, ImageFile
from ._binary import i32le as i32
def _accept(prefix):
return prefix[:8] == olefile.MAGIC | null |
167,782 | import collections
import os
import sys
import warnings
import PIL
from . import Image
def get_supported_modules():
"""
:returns: A list of all supported modules.
"""
return [f for f in modules if check_module(f)]
def get_supported_codecs():
"""
:returns: A list of all supported codecs.
"""
... | :returns: A list of all supported modules, features, and codecs. |
167,783 | import collections
import os
import sys
import warnings
import PIL
from . import Image
features = {
"webp_anim": ("PIL._webp", "HAVE_WEBPANIM", None),
"webp_mux": ("PIL._webp", "HAVE_WEBPMUX", None),
"transp_webp": ("PIL._webp", "HAVE_TRANSPARENCY", None),
"raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_v... | Prints information about this installation of Pillow. This function can be called with ``python3 -m PIL``. :param out: The output stream to print to. Defaults to ``sys.stdout`` if ``None``. :param supported_formats: If ``True``, a list of all supported image file formats will be printed. |
167,784 | from inspect import signature
from typing import List, Type
from beanie.migrations.controllers.base import BaseMigrationController
from beanie.odm.documents import Document
class BaseMigrationController(ABC):
def __init__(self, function):
self.function = function
async def run(self, session):
... | null |
167,785 | import asyncio
from inspect import isclass, signature
from typing import List, Optional, Type, Union
from beanie.migrations.controllers.base import BaseMigrationController
from beanie.migrations.utils import update_dict
from beanie.odm.documents import Document
from beanie.odm.utils.pydantic import parse_model
class Du... | null |
167,786 | import pydantic
def is_second_version() -> bool:
return int(pydantic.VERSION.split(".")[0]) >= 2 | null |
167,787 | import asyncio
import logging
import os
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
import click
import toml
from beanie.migrations import template
from beanie.migrations.database import DBHandler
from beanie.migrations.models import RunningDirections, RunningMode
from be... | null |
167,788 | import asyncio
import logging
import os
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
import click
import toml
from beanie.migrations import template
from beanie.migrations.database import DBHandler
from beanie.migrations.models import RunningDirections, RunningMode
from be... | null |
167,789 | import asyncio
import logging
import os
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
import click
import toml
from beanie.migrations import template
from beanie.migrations.database import DBHandler
from beanie.migrations.models import RunningDirections, RunningMode
from be... | null |
167,790 | import asyncio
import inspect
from enum import Enum
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
Union,
)
class EventTypes(str, Enum):
INSERT = "INSERT"
REPLACE = "REPLACE"
SAVE = "SAVE"
SAVE_CHANGES... | Decorator. It adds action, which should run before mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None |
167,791 | import asyncio
import inspect
from enum import Enum
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
Union,
)
class EventTypes(str, Enum):
INSERT = "INSERT"
REPLACE = "REPLACE"
SAVE = "SAVE"
SAVE_CHANGES... | Decorator. It adds action, which should run after mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None |
167,792 | import asyncio
import inspect
from enum import Enum
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
Union,
)
class EventTypes(str, Enum):
INSERT = "INSERT"
REPLACE = "REPLACE"
SAVE = "SAVE"
SAVE_CHANGES... | Helper function to wrap Document methods with before and after event listeners :param event_type: EventTypes - event types :return: None |
167,793 | from typing import Any
import bson
import pydantic
from typing_extensions import Annotated
from beanie.odm.utils.pydantic import IS_PYDANTIC_V2
def _to_bson_binary(value: Any) -> bson.Binary:
return value if isinstance(value, bson.Binary) else bson.Binary(value) | null |
167,794 | import asyncio
import warnings
from enum import Enum
from typing import (
Any,
ClassVar,
Dict,
Iterable,
List,
Mapping,
Optional,
Type,
TypeVar,
Union,
)
from uuid import UUID, uuid4
from bson import DBRef, ObjectId
from lazy_model import LazyModel
from pydantic import (
Conf... | null |
167,795 | import asyncio
import warnings
from enum import Enum
from typing import (
Any,
ClassVar,
Dict,
Iterable,
List,
Mapping,
Optional,
Type,
TypeVar,
Union,
)
from uuid import UUID, uuid4
from bson import DBRef, ObjectId
from lazy_model import LazyModel
from pydantic import (
Conf... | null |
167,796 | import asyncio
import sys
from collections import OrderedDict
from dataclasses import dataclass
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
List,
Optional,
Type,
TypeVar,
Union,
)
from typing import OrderedDict as OrderedDictType
from typing import T... | If `typ` is defined, returns a subclass of `typ` with an extra attribute `_indexed` as a tuple: - Index 0: `index_type` such as `pymongo.ASCENDING` - Index 1: `kwargs` passed to `IndexModel` When instantiated the type of the result will actually be `typ`. When `typ` is not defined, returns an `IndexedAnnotation` instan... |
167,797 | from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type
from beanie.odm.fields import LinkInfo, LinkTypes
def construct_query(
link_info: LinkInfo,
queries: List,
database_major_version: int,
current_depth: Optional[int] = None,
):
if link_info.is_fetchable is False or (
cur... | null |
167,798 | from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type
from beanie.odm.fields import LinkInfo, LinkTypes
The provided code snippet includes necessary dependencies for implementing the `split_text_query` function. Write a Python function `def split_text_query( query: Dict[str, Any] ) -> Tuple[List... | Divide query into text and non-text matches :param query: Dict[str, Any] - query dict :return: Tuple[Dict[str, Any], Dict[str, Any]] - text and non-text queries, respectively |
167,799 | import asyncio
import sys
from beanie.odm.utils.pydantic import (
IS_PYDANTIC_V2,
get_extra_field_info,
get_model_fields,
parse_model,
)
from beanie.odm.utils.typing import get_index_attributes
import importlib
import inspect
from typing import ( # type: ignore
List,
Optional,
Type,
Uni... | Beanie initialization :param database: AsyncIOMotorDatabase - motor database instance :param connection_string: str - MongoDB connection string :param document_models: List[Union[Type[DocType], str]] - model classes or strings with dot separated paths :param allow_index_dropping: bool - if index dropping is allowed. De... |
167,800 | import inspect
import sys
from typing import Any, Dict, Optional, Tuple, Type
from beanie.odm.fields import IndexedAnnotation
from .pydantic import IS_PYDANTIC_V2, get_field_type
def extract_id_class(annotation) -> Type[Any]:
if get_origin(annotation) is not None:
try:
annotation = next(
... | null |
167,801 | import inspect
import sys
from typing import Any, Dict, Optional, Tuple, Type
from beanie.odm.fields import IndexedAnnotation
from .pydantic import IS_PYDANTIC_V2, get_field_type
class IndexedAnnotation:
_indexed: Tuple[int, Dict[str, Any]]
IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2
if IS_PYDANTIC... | Gets the index attributes from the field, if it is indexed. :param field: The field to get the index attributes from. :return: The index attributes, if the field is indexed. Otherwise, None. |
167,802 | from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Dict
from typing import Mapping as MappingType
from beanie.odm.fields import (
ExpressionField,
)
class ExpressionField(str):
def __getitem__(self, item):
def __getattr__(self, item):
def __hash__(self):
def __eq__(self,... | null |
167,803 | from typing import Any, Type
import pydantic
from pydantic import BaseModel
IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2
if IS_PYDANTIC_V2:
from pydantic import TypeAdapter
else:
from pydantic import parse_obj_as
def parse_object_as(object_type: Type, data: Any):
if IS_PYDANTIC_V2:
ret... | null |
167,804 | from typing import Any, Type
import pydantic
from pydantic import BaseModel
IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2
if IS_PYDANTIC_V2:
from pydantic import TypeAdapter
else:
from pydantic import parse_obj_as
def get_extra_field_info(field, parameter: str):
if IS_PYDANTIC_V2:
if fi... | null |
167,805 | from typing import Any, Type
import pydantic
from pydantic import BaseModel
IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2
if IS_PYDANTIC_V2:
from pydantic import TypeAdapter
else:
from pydantic import parse_obj_as
def get_model_dump(model, *args, **kwargs):
if IS_PYDANTIC_V2:
return mod... | null |
167,806 | from typing import TYPE_CHECKING, Any, Dict, Type, Union
from pydantic import BaseModel
from beanie.exceptions import (
ApplyChangesException,
DocWasNotRegisteredInUnionClass,
UnionHasNoRegisteredDocs,
)
from beanie.odm.interfaces.detector import ModelType
from beanie.odm.utils.pydantic import get_config_va... | Merge two models :param left: left model :param right: right model :return: None |
167,807 | from typing import TYPE_CHECKING, Any, Dict, Type, Union
from pydantic import BaseModel
from beanie.exceptions import (
ApplyChangesException,
DocWasNotRegisteredInUnionClass,
UnionHasNoRegisteredDocs,
)
from beanie.odm.interfaces.detector import ModelType
from beanie.odm.utils.pydantic import get_config_va... | null |
167,808 | from typing import TYPE_CHECKING, Any, Dict, Type, Union
from pydantic import BaseModel
from beanie.exceptions import (
ApplyChangesException,
DocWasNotRegisteredInUnionClass,
UnionHasNoRegisteredDocs,
)
from beanie.odm.interfaces.detector import ModelType
from beanie.odm.utils.pydantic import get_config_va... | null |
167,809 | from typing import TYPE_CHECKING, Optional, Set
from beanie.odm.utils.encoder import Encoder
def get_dict(
document: "Document",
to_db: bool = False,
exclude: Optional[Set[str]] = None,
keep_nulls: bool = True,
):
if exclude is None:
exclude = set()
if document.id is None:
exclud... | null |
167,810 | from typing import TYPE_CHECKING, Optional, Set
from beanie.odm.utils.encoder import Encoder
def get_dict(
document: "Document",
to_db: bool = False,
exclude: Optional[Set[str]] = None,
keep_nulls: bool = True,
):
if exclude is None:
exclude = set()
if document.id is None:
exclud... | null |
167,811 | from typing import Dict, Optional, Type, TypeVar
from pydantic import BaseModel
from beanie.odm.interfaces.detector import ModelType
from beanie.odm.utils.pydantic import get_config_value, get_model_fields
ProjectionModelType = TypeVar("ProjectionModelType", bound=BaseModel)
class ModelType(str, Enum):
def get_model_... | null |
167,812 | from functools import wraps
from typing import TYPE_CHECKING, Callable
def validate_self_before(f: Callable):
@wraps(f)
async def wrapper(self: "DocType", *args, **kwargs):
await self.validate_self(*args, **kwargs)
return await f(self, *args, **kwargs)
return wrapper | null |
167,813 | import inspect
from functools import wraps
from typing import TYPE_CHECKING, Callable
from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved
def check_if_state_saved(self: "DocType"):
if not self.use_state_management():
raise StateManagementIsTurnedOff(
"State management is turn... | null |
167,814 | import inspect
from functools import wraps
from typing import TYPE_CHECKING, Callable
from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved
def check_if_previous_state_saved(self: "DocType"):
if not self.use_state_management():
raise StateManagementIsTurnedOff(
"State managemen... | null |
167,815 | import inspect
from functools import wraps
from typing import TYPE_CHECKING, Callable
from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved
def save_state_after(f: Callable):
@wraps(f)
async def wrapper(self: "DocType", *args, **kwargs):
result = await f(self, *args, **kwargs)
... | null |
167,816 | import dataclasses as dc
import datetime
import decimal
import enum
import ipaddress
import operator
import pathlib
import re
import uuid
from enum import Enum
from typing import (
Any,
Callable,
Container,
Iterable,
Mapping,
MutableMapping,
Optional,
Tuple,
)
import bson
import pydantic... | null |
167,817 | from typing import Optional
from fastapi import Depends, HTTPException, Path, Query
from starlette import status
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.db.errors import EntityDoesNotExist
from app.db.repositories.arti... | null |
167,818 | from typing import Optional
from fastapi import Depends, HTTPException, Path
from starlette import status
from app.api.dependencies import articles, authentication, database
from app.db.errors import EntityDoesNotExist
from app.db.repositories.comments import CommentsRepository
from app.models.domain.articles import Ar... | null |
167,819 | from fastapi import APIRouter, Depends
from app.api.dependencies.database import get_repository
from app.db.repositories.tags import TagsRepository
from app.models.schemas.tags import TagsInList
def get_repository(
repo_type: Type[BaseRepository],
) -> Callable[[Connection], BaseRepository]:
def _get_repo(
... | null |
167,820 | from fastapi import APIRouter, Body, Depends, HTTPException
from starlette.status import HTTP_400_BAD_REQUEST
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.core.config import get_app_settings
from app.core.settings.app impor... | null |
167,821 | from fastapi import APIRouter, Body, Depends, HTTPException
from starlette.status import HTTP_400_BAD_REQUEST
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.core.config import get_app_settings
from app.core.settings.app impor... | null |
167,822 | from fastapi import APIRouter, Depends, HTTPException
from starlette.status import HTTP_400_BAD_REQUEST
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.api.dependencies.profiles import get_profile_by_username_from_path
from ap... | null |
167,823 | from fastapi import APIRouter, Depends, HTTPException
from starlette.status import HTTP_400_BAD_REQUEST
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.api.dependencies.profiles import get_profile_by_username_from_path
from ap... | null |
167,824 | from fastapi import APIRouter, Depends, HTTPException
from starlette.status import HTTP_400_BAD_REQUEST
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.api.dependencies.profiles import get_profile_by_username_from_path
from ap... | null |
167,825 | from fastapi import APIRouter, Body, Depends, HTTPException
from starlette.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from app.api.dependencies.database import get_repository
from app.core.config import get_app_settings
from app.core.settings.app import AppSettings
from app.db.errors import EntityDoesNotExist... | null |
167,826 | from fastapi import APIRouter, Body, Depends, HTTPException
from starlette.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from app.api.dependencies.database import get_repository
from app.core.config import get_app_settings
from app.core.settings.app import AppSettings
from app.db.errors import EntityDoesNotExist... | null |
167,827 | from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Response
from starlette import status
from app.api.dependencies.articles import (
check_article_modification_permissions,
get_article_by_slug_from_path,
get_articles_filters,
)
from app.api.dependencies.authentication i... | null |
167,828 | from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Response
from starlette import status
from app.api.dependencies.articles import (
check_article_modification_permissions,
get_article_by_slug_from_path,
get_articles_filters,
)
from app.api.dependencies.authentication i... | null |
167,829 | from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Response
from starlette import status
from app.api.dependencies.articles import (
check_article_modification_permissions,
get_article_by_slug_from_path,
get_articles_filters,
)
from app.api.dependencies.authentication i... | null |
167,830 | from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Response
from starlette import status
from app.api.dependencies.articles import (
check_article_modification_permissions,
get_article_by_slug_from_path,
get_articles_filters,
)
from app.api.dependencies.authentication i... | null |
167,831 | from typing import Optional
from fastapi import APIRouter, Body, Depends, HTTPException, Response
from starlette import status
from app.api.dependencies.articles import (
check_article_modification_permissions,
get_article_by_slug_from_path,
get_articles_filters,
)
from app.api.dependencies.authentication i... | null |
167,832 | from fastapi import APIRouter, Depends, HTTPException, Query
from starlette import status
from app.api.dependencies.articles import get_article_by_slug_from_path
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.db.repositories.... | null |
167,833 | from fastapi import APIRouter, Depends, HTTPException, Query
from starlette import status
from app.api.dependencies.articles import get_article_by_slug_from_path
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.db.repositories.... | null |
167,834 | from fastapi import APIRouter, Depends, HTTPException, Query
from starlette import status
from app.api.dependencies.articles import get_article_by_slug_from_path
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.database import get_repository
from app.db.repositories.... | null |
167,835 | from typing import Optional
from fastapi import APIRouter, Body, Depends, Response
from starlette import status
from app.api.dependencies.articles import get_article_by_slug_from_path
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.comments import (
check_commen... | null |
167,836 | from typing import Optional
from fastapi import APIRouter, Body, Depends, Response
from starlette import status
from app.api.dependencies.articles import get_article_by_slug_from_path
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.comments import (
check_commen... | null |
167,837 | from typing import Optional
from fastapi import APIRouter, Body, Depends, Response
from starlette import status
from app.api.dependencies.articles import get_article_by_slug_from_path
from app.api.dependencies.authentication import get_current_user_authorizer
from app.api.dependencies.comments import (
check_commen... | null |
167,838 | from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware
from app.api.errors.http_error import http_error_handler
from app.api.errors.validation_error import http422_error_handler
from app.api.ro... | null |
167,839 | import bcrypt
from passlib.context import CryptContext
def generate_salt() -> str:
return bcrypt.gensalt().decode() | null |
167,840 | import bcrypt
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password) | null |
167,841 | import bcrypt
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def get_password_hash(password: str) -> str:
return pwd_context.hash(password) | null |
167,842 | from typing import Tuple
import sqlalchemy as sa
from alembic import op
from sqlalchemy import func
def create_updated_at_trigger() -> None:
op.execute(
"""
CREATE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS
$$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;... | null |
167,843 | from typing import Tuple
import sqlalchemy as sa
from alembic import op
from sqlalchemy import func
def downgrade() -> None:
op.drop_table("commentaries")
op.drop_table("favorites")
op.drop_table("articles_to_tags")
op.drop_table("tags")
op.drop_table("articles")
op.drop_table("followers_to_fol... | null |
167,844 | import pathlib
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.core.config import get_app_settings
config = context.config
target_metadata = None
config.set_main_option("sqlalchemy.url", str(DATABASE_URL))
def run_migrations_online(... | null |
167,845 | import datetime
from pydantic import BaseConfig, BaseModel
def convert_datetime_to_realworld(dt: datetime.datetime) -> str:
return dt.replace(tzinfo=datetime.timezone.utc).isoformat().replace("+00:00", "Z") | null |
167,846 | import datetime
from pydantic import BaseConfig, BaseModel
def convert_field_to_camel_case(string: str) -> str:
return "".join(
word if index == 0 else word.capitalize()
for index, word in enumerate(string.split("_"))
) | null |
167,847 | import os, sys
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import logging
import click
import numpy as np
from functools import partial
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
from datetime import datetime
from datasets import Dataset, load_dataset, load_from_disk
from transformers ... | null |
167,848 | import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import logging, torch
import click
import numpy as np
from functools import partial
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
from datetime import datetime
from datasets import Dataset, load_dataset, load_from_disk
from transformer... | null |
167,849 | import os, sys
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import logging
import click
import numpy as np
from functools import partial
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
from datetime import datetime
from datasets import Dataset, load_dataset, load_from_disk
from transformers ... | null |
167,850 | import os, json
from argparse import ArgumentParser
from tqdm import tqdm
The provided code snippet includes necessary dependencies for implementing the `convert_inst_to_chat` function. Write a Python function `def convert_inst_to_chat(path)` to solve the following problem:
Usage: 将 `指令数据格式` 转换为 `对话数据格式`.
Here is the... | Usage: 将 `指令数据格式` 转换为 `对话数据格式`. |
167,851 | import os, json
from argparse import ArgumentParser
from tqdm import tqdm
The provided code snippet includes necessary dependencies for implementing the `convert_chat_to_inst` function. Write a Python function `def convert_chat_to_inst(path)` to solve the following problem:
Usage: 将 `对话数据格式` 转换为 `指令数据格式` 忽略多轮数据.
Here... | Usage: 将 `对话数据格式` 转换为 `指令数据格式` 忽略多轮数据. |
167,852 | import os, json
from argparse import ArgumentParser
from tqdm import tqdm
The provided code snippet includes necessary dependencies for implementing the `merge_multi_chat_files` function. Write a Python function `def merge_multi_chat_files(path)` to solve the following problem:
Usage: 合并多个 `对话数据格式` 文件.
Here is the fu... | Usage: 合并多个 `对话数据格式` 文件. |
167,854 | from setuptools import find_packages, setup
import os
import subprocess
import time
version_file = 'pyiqa/version.py'
def get_hash():
def write_version_py():
content = """# GENERATED VERSION FILE
# TIME: {}
__version__ = '{}'
__gitsha__ = '{}'
version_info = ({})
"""
sha = get_hash()
with open('VERSION', '... | null |
167,855 | from setuptools import find_packages, setup
import os
import subprocess
import time
version_file = 'pyiqa/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
167,858 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def l1_loss(pred, target):
return F.l1_loss(pred, target, reduction='none') | null |
167,859 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def mse_loss(pred, target):
return F.mse_loss(pred, target, reduction='none') | null |
167,860 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def cross_entropy(pred, target):
return F.cross_entropy(pred, target, reduction='none') | null |
167,861 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def nll_loss(pred, target):
return F.nll_loss(pred, target, reduction='none') | null |
167,862 | import math
import torch
from torch import autograd as autograd
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
def charbonnier_loss(pred, target, eps=1e-12):
return torch.sqrt((pred - target)**2 + eps) | null |
167,863 | from cv2 import reduce
import torch
import numpy as np
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
The provided code snippet includes necessary dependencies for implementing the `emd_loss` function. Write a Python f... | Args: pred (Tensor): of shape (N, C). Predicted tensor. target (Tensor): of shape (N, C). Ground truth tensor. r (float): norm level, default l2 norm. |
167,864 | from cv2 import reduce
import torch
import numpy as np
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
The provided code snippet includes necessary dependencies for implementing the `plcc_loss` function. Write a Python ... | Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor. |
167,865 | from cv2 import reduce
import torch
import numpy as np
from torch import nn as nn
from torch.nn import functional as F
from pyiqa.utils.registry import LOSS_REGISTRY
from .loss_util import weighted_loss
The provided code snippet includes necessary dependencies for implementing the `norm_loss_with_normalization` functi... | Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor. |
167,866 | import math
import collections.abc
from itertools import repeat
import numpy as np
from typing import Tuple
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
def _ntuple(n):
def parse(x):
if isinstance(x, collections.abc.Iterable):
r... | null |
167,867 | import math
import collections.abc
from itertools import repeat
import numpy as np
from typing import Tuple
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn import init as init
to_2tuple = _ntuple(2)
def symm_pad(im: torch.Tensor, padding: Tuple[int, int, int, int]):
"""Sym... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.