index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35,327 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/layers/with_nvtx_range.py | 9,16 | 1,46 | with_nvtx_range | 22,46 | 16,46 | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..model import Model
from ..util import use_nvtx_range
_ModelT = TypeVar("_ModelT", bound=Model)
def with_nvtx_range(
layer: _ModelT,
name: Optional[str] = None,
*,
forward_color: int = -1,
backprop_color: int = -1,
) -> _ModelT:
FI... | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..model import Model
from ..util import use_nvtx_range
_ModelT = TypeVar("_ModelT", bound=Model)
def with_nvtx_range(
layer: _ModelT,
name: Optional[str] = None,
*,
forward_color: int = -1,
backprop_color: int = -1,
) -> _ModelT:
... | name = layer.name if name is None else name
orig_forward = layer._func
orig_init = layer.init
def forward(model: Model, X: Any, is_train: bool) -> Tuple[Any, Callable]:
with use_nvtx_range(f"{name} forward", forward_color):
layer_Y, layer_callback = orig_forward(model, X, is_train=... | """Wraps any layer and marks the forward and backprop phases as
NVTX ranges for CUDA profiling.
By default, the name of the layer is used as the name of the range,
followed by the name of the pass.
"""
name = layer.name if name is None else name
orig_forward = layer._func
orig_init = l... | 74 | 186 | 266 | 452 | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..model import Model
from ..util import use_nvtx_range
_ModelT = TypeVar("_ModelT", bound=Model)
def with_nvtx_range(
layer: _ModelT,
name: Optional[str] = None,
*,
forward_color: int = -1,
backprop_color: int = -1,
) -> _ModelT:
FI... | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..model import Model
from ..util import use_nvtx_range
_ModelT = TypeVar("_ModelT", bound=Model)
def with_nvtx_range(
layer: _ModelT,
name: Optional[str] = None,
*,
forward_color: int = -1,
backprop_color: int = -1,
) -> _ModelT:
... | |
35,328 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/layers/with_padded.py | 77,80 | 1,144 | _array_forward | 80,95 | 80,95 | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Floats3d, Ints1d, List2d, Padded, Ragged
from ..util import is_xp_array
PaddedData = Tuple[Floats3d, Ints1d, Ints1d, Ints1d]
SeqT = TypeVar("SeqT", bound=Union[... | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Floats3d, Ints1d, List2d, Padded, Ragged
from ..util import is_xp_array
PaddedData = Tuple[Floats3d, Ints1d, Ints1d, Ints1d]
SeqT = TypeVar("SeqT", bound=Union[... | # Create bogus metadata for Padded.
Xp = _get_padded(layer, X)
Yp, get_dXp = layer(Xp, is_train)
size_at_t = Xp.size_at_t
lengths = Xp.lengths
indices = Xp.indices
def backprop(dY: Floats3d) -> Floats3d:
dYp = Padded(dY, size_at_t, lengths, indices)
dXp = get_dXp(dYp)
... | # Create bogus metadata for Padded.
Xp = _get_padded(layer, X)
Yp, get_dXp = layer(Xp, is_train)
size_at_t = Xp.size_at_t
lengths = Xp.lengths
indices = Xp.indices
def backprop(dY: Floats3d) -> Floats3d:
dYp = Padded(dY, size_at_t, lengths, indices)
dXp = get_dXp(dYp)
... | 44 | 1,722 | 184 | 1,906 | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Floats3d, Ints1d, List2d, Padded, Ragged
from ..util import is_xp_array
PaddedData = Tuple[Floats3d, Ints1d, Ints1d, Ints1d]
SeqT = TypeVar("SeqT", bound=Union[... | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Floats3d, Ints1d, List2d, Padded, Ragged
from ..util import is_xp_array
PaddedData = Tuple[Floats3d, Ints1d, Ints1d, Ints1d]
SeqT = TypeVar("SeqT", bound=Union[... | |
35,329 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/layers/with_ragged.py | 82,85 | 1,129 | _padded_forward | 85,114 | 85,114 | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..backends import NumpyOps
from ..config import registry
from ..model import Model
from ..types import Array2d, Ints1d, List2d, ListXd, Padded, Ragged
NUMPY_OPS = NumpyOps()
RaggedData = Tuple[Array2d, Ints1d]
SeqT = TypeVar("SeqT", bound... | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..backends import NumpyOps
from ..config import registry
from ..model import Model
from ..types import Array2d, Ints1d, List2d, ListXd, Padded, Ragged
NUMPY_OPS = NumpyOps()
RaggedData = Tuple[Array2d, Ints1d]
SeqT = TypeVar("SeqT", bound... | # Assign these to locals, to keep code a bit shorter.
list2padded = layer.ops.list2padded
padded2list = layer.ops.padded2list
unflatten = layer.ops.unflatten
flatten = layer.ops.flatten
# It's worth being a bit careful about memory here, as the activations
# are potentially large on GPU. So ... | # Assign these to locals, to keep code a bit shorter.
list2padded = layer.ops.list2padded
padded2list = layer.ops.padded2list
unflatten = layer.ops.unflatten
flatten = layer.ops.flatten
# It's worth being a bit careful about memory here, as the activations
# are potentially large on GPU. So ... | 166 | 1,224 | 440 | 1,664 | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..backends import NumpyOps
from ..config import registry
from ..model import Model
from ..types import Array2d, Ints1d, List2d, ListXd, Padded, Ragged
NUMPY_OPS = NumpyOps()
RaggedData = Tuple[Array2d, Ints1d]
SeqT = TypeVar("SeqT", bound... | from typing import Callable, List, Optional, Tuple, TypeVar, Union, cast
from ..backends import NumpyOps
from ..config import registry
from ..model import Model
from ..types import Array2d, Ints1d, List2d, ListXd, Padded, Ragged
NUMPY_OPS = NumpyOps()
RaggedData = Tuple[Array2d, Ints1d]
SeqT = TypeVar("SeqT", bound... | |
35,330 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/layers/with_reshape.py | 40,43 | 1,57 | init | 43,57 | 43,57 | from typing import Callable, List, Optional, Tuple, TypeVar, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Array3d
InT = TypeVar("InT", bound=Array3d)
OutT = TypeVar("OutT", bound=Array2d)
@registry.layers("with_reshape.v1")
def with_reshape(layer: Model[OutT, OutT]) -> M... | from typing import Callable, List, Optional, Tuple, TypeVar, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Array3d
InT = TypeVar("InT", bound=Array3d)
OutT = TypeVar("OutT", bound=Array2d)
@registry.layers("with_reshape.v1")
def with_reshape(layer: Model[OutT, OutT]) -> M... | layer = model.layers[0]
if X is None and Y is None:
layer.initialize()
X2d: Optional[Array2d] = None
Y2d: Optional[Array2d] = None
if X is not None:
X2d = cast(Array2d, model.ops.reshape(X, (-1, X.shape[-1])))
if Y is not None:
Y2d = cast(Array2d, model.ops.reshape(Y, (-1... | layer = model.layers[0]
if X is None and Y is None:
layer.initialize()
X2d: Optional[Array2d] = None
Y2d: Optional[Array2d] = None
if X is not None:
X2d = cast(Array2d, model.ops.reshape(X, (-1, X.shape[-1])))
if Y is not None:
Y2d = cast(Array2d, model.ops.reshape(Y, (-1... | 52 | 508 | 233 | 741 | from typing import Callable, List, Optional, Tuple, TypeVar, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Array3d
InT = TypeVar("InT", bound=Array3d)
OutT = TypeVar("OutT", bound=Array2d)
@registry.layers("with_reshape.v1")
def with_reshape(layer: Model[OutT, OutT]) -> M... | from typing import Callable, List, Optional, Tuple, TypeVar, cast
from ..config import registry
from ..model import Model
from ..types import Array2d, Array3d
InT = TypeVar("InT", bound=Array3d)
OutT = TypeVar("OutT", bound=Array2d)
@registry.layers("with_reshape.v1")
def with_reshape(layer: Model[OutT, OutT]) -> M... | |
35,331 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/layers/with_signpost_interval.py | 9,14 | 1,50 | with_signpost_interval | 20,50 | 14,50 | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..compat import has_os_signpost, os_signpost
from ..model import Model
_ModelT = TypeVar("_ModelT", bound=Model)
def with_signpost_interval(
layer: _ModelT,
signposter: "os_signpost.Signposter",
name: Optional[str] = None,
) -> _ModelT:
FIL... | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..compat import has_os_signpost, os_signpost
from ..model import Model
_ModelT = TypeVar("_ModelT", bound=Model)
def with_signpost_interval(
layer: _ModelT,
signposter: "os_signpost.Signposter",
name: Optional[str] = None,
) -> _ModelT:
... | if not has_os_signpost:
raise ValueError(
"with_signpost_interval layer requires the 'os_signpost' package"
)
name = layer.name if name is None else name
orig_forward = layer._func
orig_init = layer.init
def forward(model: Model, X: Any, is_train: bool) -> Tuple[Any, C... | """Wraps any layer and marks the init, forward and backprop phases using
signpost intervals for macOS Instruments profiling
By default, the name of the layer is used as the name of the range,
followed by the name of the pass.
"""
if not has_os_signpost:
raise ValueError(
"wi... | 87 | 183 | 327 | 510 | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..compat import has_os_signpost, os_signpost
from ..model import Model
_ModelT = TypeVar("_ModelT", bound=Model)
def with_signpost_interval(
layer: _ModelT,
signposter: "os_signpost.Signposter",
name: Optional[str] = None,
) -> _ModelT:
FIL... | from typing import Any, Callable, Optional, Tuple, TypeVar
from ..compat import has_os_signpost, os_signpost
from ..model import Model
_ModelT = TypeVar("_ModelT", bound=Model)
def with_signpost_interval(
layer: _ModelT,
signposter: "os_signpost.Signposter",
name: Optional[str] = None,
) -> _ModelT:
... | |
35,333 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/loss.py | 144,145 | 49,171 | get_grad | CategoricalCrossentropy | 145,162 | 145,162 | class CategoricalCrossentropy(Loss):
names: Optional[Sequence[str]]
missing_value: Optional[Union[str, int]]
_name_to_i: Dict[str, int]
def __init__(
self,
*,
normalize: bool = True,
names: Optional[Sequence[str]] = None,
missing_value: Optional[Union[str, int]] ... | class CategoricalCrossentropy(Loss):
names: Optional[Sequence[str]]
missing_value: Optional[Union[str, int]]
_name_to_i: Dict[str, int]
def __init__(
self,
*,
normalize: bool = True,
names: Optional[Sequence[str]] = None,
missing_value: Optional[Union[str, int]] ... | target, mask = self.convert_truths(truths, guesses)
xp = get_array_module(target)
if guesses.shape != target.shape: # pragma: no cover
err = f"Cannot calculate CategoricalCrossentropy loss: mismatched shapes: {guesses.shape} vs {target.shape}."
raise ValueError(err)
... | target, mask = self.convert_truths(truths, guesses)
xp = get_array_module(target)
if guesses.shape != target.shape: # pragma: no cover
err = f"Cannot calculate CategoricalCrossentropy loss: mismatched shapes: {guesses.shape} vs {target.shape}."
raise ValueError(err)
... | 99 | 1,274 | 284 | 1,558 | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... |
35,334 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/loss.py | 360,361 | 337,404 | get_grad | CosineDistance | 361,386 | 361,386 | class CosineDistance(Loss):
def __init__(self, *, normalize: bool = True, ignore_zeros: bool = False):
self.normalize = normalize
self.ignore_zeros = ignore_zeros
def __call__(self, guesses: Floats2d, truths: Floats2d) -> Tuple[Floats2d, float]:
return self.get_grad(guesses, truths), se... | class CosineDistance(Loss):
def __init__(self, *, normalize: bool = True, ignore_zeros: bool = False):
self.normalize = normalize
self.ignore_zeros = ignore_zeros
def __call__(self, guesses: Floats2d, truths: Floats2d) -> Tuple[Floats2d, float]:
return self.get_grad(guesses, truths), se... | if guesses.shape != truths.shape: # pragma: no cover
err = f"Cannot calculate cosine similarity: mismatched shapes: {guesses.shape} vs {truths.shape}."
raise ValueError(err)
# Note: not using get_distance() here to avoid duplicating certain calculations
xp = get_array_m... | if guesses.shape != truths.shape: # pragma: no cover
err = f"Cannot calculate cosine similarity: mismatched shapes: {guesses.shape} vs {truths.shape}."
raise ValueError(err)
# Note: not using get_distance() here to avoid duplicating certain calculations
xp = get_array_m... | 130 | 654 | 446 | 1,100 | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... |
35,335 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/loss.py | 323,324 | 307,332 | get_loss | L2Distance | 324,332 | 324,332 | class L2Distance(Loss):
def __init__(self, *, normalize: bool = True):
self.normalize = normalize
def __call__(self, guesses: Floats2d, truths: Floats2d) -> Tuple[Floats2d, float]:
return self.get_grad(guesses, truths), self.get_loss(guesses, truths)
def get_grad(self, guesses: Floats2d, t... | class L2Distance(Loss):
def __init__(self, *, normalize: bool = True):
self.normalize = normalize
def __call__(self, guesses: Floats2d, truths: Floats2d) -> Tuple[Floats2d, float]:
return self.get_grad(guesses, truths), self.get_loss(guesses, truths)
def get_grad(self, guesses: Floats2d, t... | if guesses.shape != truths.shape: # pragma: no cover
err = f"Cannot calculate L2 distance: mismatched shapes: {guesses.shape} vs {truths.shape}."
raise ValueError(err)
d_truth = self.get_grad(guesses, truths)
# TODO: Add overload for axis=None case to sum
return ... | if guesses.shape != truths.shape: # pragma: no cover
err = f"Cannot calculate L2 distance: mismatched shapes: {guesses.shape} vs {truths.shape}."
raise ValueError(err)
d_truth = self.get_grad(guesses, truths)
# TODO: Add overload for axis=None case to sum
return ... | 39 | 269 | 122 | 391 | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... |
35,336 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/loss.py | 40,42 | 27,49 | get_grad | Loss | 42,44 | 42,44 | class Loss(Generic[GuessT, TruthT, GradT, LossT]): # pragma: no cover
"""Base class for classes computing the loss / gradient. The class can
be initialized with settings if needed. It provides get_loss and
get_grad as separate methods to allow calculating them separately. It
also provides a __call__ me... | class Loss(Generic[GuessT, TruthT, GradT, LossT]): # pragma: no cover
"""Base class for classes computing the loss / gradient. The class can
be initialized with settings if needed. It provides get_loss and
get_grad as separate methods to allow calculating them separately. It
also provides a __call__ me... | ...
| ...
| 1 | 261 | 6 | 267 | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... |
35,337 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/loss.py | 243,246 | 217,270 | get_grad | SequenceCategoricalCrossentropy | 246,258 | 246,258 | class SequenceCategoricalCrossentropy(Loss):
def __init__(
self,
*,
normalize: bool = True,
names: Optional[Sequence[str]] = None,
missing_value: Optional[Union[str, int]] = None,
neg_prefix: Optional[str] = None,
label_smoothing: float = 0.0,
):
s... | class SequenceCategoricalCrossentropy(Loss):
def __init__(
self,
*,
normalize: bool = True,
names: Optional[Sequence[str]] = None,
missing_value: Optional[Union[str, int]] = None,
neg_prefix: Optional[str] = None,
label_smoothing: float = 0.0,
):
s... | err = "Cannot calculate SequenceCategoricalCrossentropy loss: guesses and truths must be same length"
if len(guesses) != len(truths): # pragma: no cover
raise ValueError(err)
n = len(guesses)
d_scores = []
for yh, y in zip(guesses, truths):
d_yh = self.cc... | err = "Cannot calculate SequenceCategoricalCrossentropy loss: guesses and truths must be same length"
if len(guesses) != len(truths): # pragma: no cover
raise ValueError(err)
n = len(guesses)
d_scores = []
for yh, y in zip(guesses, truths):
d_yh = self.cc... | 47 | 464 | 164 | 628 | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... | from abc import abstractmethod
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from .config import registry
from .types import Floats2d, Ints1d
from .util import get_array_module, to_categorical
LossT = TypeVar("LossT")
GradT = ... |
35,341 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/schedules.py | 47,50 | 13,69 | to_generator | Schedule | 57,69 | 50,69 | class Schedule(Generic[OutT]):
"""Class for implementing Thinc schedules."""
name: str
_schedule: Callable
_attrs: Dict[str, Any]
__slots__ = ["name", "_schedule", "_attrs"]
def __init__(
self, name: str, schedule: Callable, *, attrs: Dict[str, Any] = {}
) -> None:
"""Init... | class Schedule(Generic[OutT]):
"""Class for implementing Thinc schedules."""
name: str
_schedule: Callable
_attrs: Dict[str, Any]
__slots__ = ["name", "_schedule", "_attrs"]
def __init__(
self, name: str, schedule: Callable, *, attrs: Dict[str, Any] = {}
) -> None:
"""Init... | if start < 0:
raise ValueError(f"Schedule start must be non-negative, was: {start}")
if step_size < 0:
raise ValueError(f"Step size must be non-negative, was: {step_size}")
def generate():
for step in itertools.count(start, step_size):
yield s... | """Turn the schedule into a generator.
start (int): The schedule initial step.
step_size (int): The amount to increase the step for each generated value.
**extra: Additional arguments that are passed to the schedule.
RETURNS (Generator[OutT, None, None]): The generator.
... | 36 | 407 | 115 | 522 | """Generators that provide different rates, schedules, decays or series."""
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, Generator, Generic, Optional, Tuple, TypeVar
import numpy
from .config import registry
OutT = TypeVar("OutT")
class Schedule(Generic[OutT]):
"""... | """Generators that provide different rates, schedules, decays or series."""
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, Generator, Generic, Optional, Tuple, TypeVar
import numpy
from .config import registry
OutT = TypeVar("OutT")
class Schedule(Generic[OutT]):
"""... |
35,342 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/shims/mxnet.py | 61,62 | 20,124 | finish_update | MXNetShim | 62,86 | 62,86 | class MXNetShim(Shim):
"""Interface between a MXNet model and a Thinc Model. This container is
*not* a Thinc Model subclass itself.
"""
def __call__(self, inputs, is_train):
if is_train:
return self.begin_update(inputs)
else:
return self.predict(inputs), lambda a... | class MXNetShim(Shim):
"""Interface between a MXNet model and a Thinc Model. This container is
*not* a Thinc Model subclass itself.
"""
def __call__(self, inputs, is_train):
if is_train:
return self.begin_update(inputs)
else:
return self.predict(inputs), lambda a... | params = []
grads = []
shapes = []
ctx = mx.current_context()
for key, value in self._model.collect_params().items():
grad = cast(FloatsXd, mxnet2xp(value.grad(ctx)))
param = cast(FloatsXd, mxnet2xp(value.data(ctx)))
params.append(param.ravel()... | params = []
grads = []
shapes = []
ctx = mx.current_context()
for key, value in self._model.collect_params().items():
grad = cast(FloatsXd, mxnet2xp(value.grad(ctx)))
param = cast(FloatsXd, mxnet2xp(value.data(ctx)))
params.append(param.ravel()... | 69 | 934 | 310 | 1,244 | # mypy: ignore-errors
import copy
from typing import Any, cast
import srsly
from ..compat import mxnet as mx
from ..optimizers import Optimizer
from ..types import ArgsKwargs, FloatsXd
from ..util import (
convert_recursive,
get_array_module,
make_tempfile,
mxnet2xp,
xp2mxnet,
)
from .shim import ... | # mypy: ignore-errors
import copy
from typing import Any, cast
import srsly
from ..compat import mxnet as mx
from ..optimizers import Optimizer
from ..types import ArgsKwargs, FloatsXd
from ..util import (
convert_recursive,
get_array_module,
make_tempfile,
mxnet2xp,
xp2mxnet,
)
from .shim import ... |
35,343 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/shims/pytorch_grad_scaler.py | 62,65 | 7,182 | scale | PyTorchGradScaler | 66,94 | 65,94 | class PyTorchGradScaler:
"""
Gradient scaler for the PyTorch shim.
Gradients with small magnitudes are not representable in half-precision and
will underflow to zero. A gradient scaler counters this issue by scaling
up the loss before backpropagation, increasing the gradients by the same
magnit... | class PyTorchGradScaler:
"""
Gradient scaler for the PyTorch shim.
Gradients with small magnitudes are not representable in half-precision and
will underflow to zero. A gradient scaler counters this issue by scaling
up the loss before backpropagation, increasing the gradients by the same
magnit... | if not self._enabled:
return cast("torch.Tensor", tensors)
incorrect_type = ValueError(
"Input to gradient scaling must be a Tensor or Iterable[Tensor]"
)
# Cache per-device scales to avoid unnecessary d2d copies of the current scale.
scale_per_device: D... | """Scale up the values in the given tensors."""
if not self._enabled:
return cast("torch.Tensor", tensors)
incorrect_type = ValueError(
"Input to gradient scaling must be a Tensor or Iterable[Tensor]"
)
# Cache per-device scales to avoid unnecessary d2d ... | 72 | 1,416 | 279 | 1,695 | from typing import Dict, Iterable, List, Union, cast
from ..compat import has_torch_amp, torch
from ..util import is_torch_array
class PyTorchGradScaler:
"""
Gradient scaler for the PyTorch shim.
Gradients with small magnitudes are not representable in half-precision and
will underflow to zero. A gr... | from typing import Dict, Iterable, List, Union, cast
from ..compat import has_torch_amp, torch
from ..util import is_torch_array
class PyTorchGradScaler:
"""
Gradient scaler for the PyTorch shim.
Gradients with small magnitudes are not representable in half-precision and
will underflow to zero. A gr... |
35,344 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/shims/shim.py | 58,59 | 8,75 | to_disk | Shim | 59,64 | 59,64 | class Shim: # pragma: no cover
"""Define a basic interface for external models. Users can create subclasses
of 'shim' to wrap external libraries. We provide shims for PyTorch.
The Thinc Model class treats Shim objects as a sort of special type of
sublayer: it knows they're not actual Thinc Model insta... | class Shim: # pragma: no cover
"""Define a basic interface for external models. Users can create subclasses
of 'shim' to wrap external libraries. We provide shims for PyTorch.
The Thinc Model class treats Shim objects as a sort of special type of
sublayer: it knows they're not actual Thinc Model insta... | bytes_data = self.to_bytes()
path = Path(path) if isinstance(path, str) else path
with path.open("wb") as file_:
file_.write(bytes_data)
| bytes_data = self.to_bytes()
path = Path(path) if isinstance(path, str) else path
with path.open("wb") as file_:
file_.write(bytes_data)
| 16 | 676 | 59 | 735 | import contextlib
import copy
import threading
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Tuple, Union
class Shim: # pragma: no cover
"""Define a basic interface for external models. Users can create subclasses
of 'shim' to wrap external libraries. We provide shims for PyTorch... | import contextlib
import copy
import threading
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Tuple, Union
class Shim: # pragma: no cover
"""Define a basic interface for external models. Users can create subclasses
of 'shim' to wrap external libraries. We provide shims for PyTorch... |
35,347 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/shims/torchscript.py | 55,56 | 12,68 | from_bytes | TorchScriptShim | 56,68 | 56,68 | class TorchScriptShim(PyTorchShim):
"""A Thinc shim that wraps a TorchScript module.
model:
The TorchScript module. A value of `None` is also possible to
construct a shim to deserialize into.
mixed_precision:
Enable mixed-precision. This changes whitelisted ops to run
in hal... | class TorchScriptShim(PyTorchShim):
"""A Thinc shim that wraps a TorchScript module.
model:
The TorchScript module. A value of `None` is also possible to
construct a shim to deserialize into.
mixed_precision:
Enable mixed-precision. This changes whitelisted ops to run
in hal... | device = get_torch_default_device()
msg = srsly.msgpack_loads(bytes_data)
self.cfg = msg["config"]
filelike = BytesIO(msg["model"])
filelike.seek(0)
# As of Torch 2.0.0, loading TorchScript models directly to
# an MPS device is not supported.
map_location ... | device = get_torch_default_device()
msg = srsly.msgpack_loads(bytes_data)
self.cfg = msg["config"]
filelike = BytesIO(msg["model"])
filelike.seek(0)
# As of Torch 2.0.0, loading TorchScript models directly to
# an MPS device is not supported.
map_location ... | 47 | 487 | 184 | 671 | from io import BytesIO
from typing import Any, Optional
import srsly
from ..compat import torch
from ..util import get_torch_default_device
from .pytorch import PyTorchShim
from .pytorch_grad_scaler import PyTorchGradScaler
class TorchScriptShim(PyTorchShim):
"""A Thinc shim that wraps a TorchScript module.
... | from io import BytesIO
from typing import Any, Optional
import srsly
from ..compat import torch
from ..util import get_torch_default_device
from .pytorch import PyTorchShim
from .pytorch_grad_scaler import PyTorchGradScaler
class TorchScriptShim(PyTorchShim):
"""A Thinc shim that wraps a TorchScript module.
... |
35,349 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 1265,1267 | 1255,1298 | from_items | ArgsKwargs | 1273,1282 | 1267,1282 | @dataclass
class ArgsKwargs:
"""A tuple of (args, kwargs) that can be spread into some function f:
f(*args, **kwargs)
"""
args: Tuple[Any, ...]
kwargs: Dict[str, Any]
@classmethod
def from_items(cls, items: Sequence[Tuple[Union[int, str], Any]]) -> "ArgsKwargs":
FILL_FUNC_BODY def keys... | @dataclass
class ArgsKwargs:
"""A tuple of (args, kwargs) that can be spread into some function f:
f(*args, **kwargs)
"""
args: Tuple[Any, ...]
kwargs: Dict[str, Any]
@classmethod
def from_items(cls, items: Sequence[Tuple[Union[int, str], Any]]) -> "ArgsKwargs":
"""Create an ArgsK... | args = []
kwargs = {}
for key, value in items:
if isinstance(key, int):
args.append(value)
else:
kwargs[key] = value
return cls(args=tuple(args), kwargs=kwargs)
| """Create an ArgsKwargs object from a sequence of (key, value) tuples,
such as produced by argskwargs.items(). Each key should be either a string
or an integer. Items with int keys are added to the args list, and
items with string keys are added to the kwargs list. The args list is
... | 22 | 406 | 82 | 488 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,350 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 492,494 | 452,502 | sum | Floats1d | 494,495 | 494,495 | class Floats1d(_Array1d, _Floats):
"""1-dimensional array of floats."""
T: "Floats1d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=1, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[float]: ..... | class Floats1d(_Array1d, _Floats):
"""1-dimensional array of floats."""
T: "Floats1d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=1, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[float]: ..... | def sum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ...
| def sum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ...
| 16 | 643 | 48 | 691 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,351 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 658,659 | 612,663 | sum | Floats2d | 659,660 | 659,660 | class Floats2d(_Array2d, _Floats):
"""2-dimensional array of floats"""
T: "Floats2d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=2, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[Floats1d]: ... | class Floats2d(_Array2d, _Floats):
"""2-dimensional array of floats"""
T: "Floats2d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=2, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[Floats1d]: ... | def sum(self, *, keepdims: bool = False, axis: _2_AllAx = None, out: Union[None, "Floats1d", "Floats2d"] = None) -> _2F_ReduceResults: ...
| def sum(self, *, keepdims: bool = False, axis: _2_AllAx = None, out: Union[None, "Floats1d", "Floats2d"] = None) -> _2F_ReduceResults: ...
| 20 | 596 | 61 | 657 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,352 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 805,807 | 762,821 | sum | Floats3d | 807,808 | 807,808 | class Floats3d(_Array3d, _Floats):
"""3-dimensional array of floats"""
T: "Floats3d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=3, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[Floats2d]: ... | class Floats3d(_Array3d, _Floats):
"""3-dimensional array of floats"""
T: "Floats3d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=3, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[Floats2d]: ... | def sum(self, *, keepdims: Tru, axis: _3_AllAx = None, out: Optional["Floats3d"] = None) -> "Floats3d": ...
| def sum(self, *, keepdims: Tru, axis: _3_AllAx = None, out: Optional["Floats3d"] = None) -> "Floats3d": ...
| 16 | 735 | 48 | 783 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,353 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 980,982 | 924,994 | sum | Floats4d | 982,983 | 982,983 | class Floats4d(_Array4d, _Floats):
"""4-dimensional array of floats."""
T: "Floats4d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=4, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[Floats3d]:... | class Floats4d(_Array4d, _Floats):
"""4-dimensional array of floats."""
T: "Floats4d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=4, dtype="f")
@abstractmethod
def __iter__(self) -> Iterator[Floats3d]:... | def sum(self, *, keepdims: Fal = False, axis: TwoAx, out: Optional[Floats2d] = None) -> Floats2d: ...
| def sum(self, *, keepdims: Fal = False, axis: TwoAx, out: Optional[Floats2d] = None) -> Floats2d: ...
| 16 | 884 | 44 | 928 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,354 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 1086,1088 | 1076,1093 | validate | Generator | 1088,1093 | 1088,1093 | class Generator(Iterator):
"""Custom generator type. Used to annotate function arguments that accept
generators so they can be validated by pydantic (which doesn't support
iterators/iterables otherwise).
"""
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
... | class Generator(Iterator):
"""Custom generator type. Used to annotate function arguments that accept
generators so they can be validated by pydantic (which doesn't support
iterators/iterables otherwise).
"""
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
... | if not hasattr(v, "__iter__") and not hasattr(v, "__next__"):
raise TypeError("not a valid iterator")
return v
| if not hasattr(v, "__iter__") and not hasattr(v, "__next__"):
raise TypeError("not a valid iterator")
return v
| 15 | 102 | 50 | 152 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,355 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 548,549 | 502,553 | sum | Ints1d | 549,550 | 549,550 | class Ints1d(_Array1d, _Ints):
"""1-dimensional array of ints."""
T: "Ints1d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=1, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[int]: ...
@ov... | class Ints1d(_Array1d, _Ints):
"""1-dimensional array of ints."""
T: "Ints1d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=1, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[int]: ...
@ov... | def sum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Ints1d"] = None) -> _1I_ReduceResults: ...
| def sum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Ints1d"] = None) -> _1I_ReduceResults: ...
| 18 | 641 | 52 | 693 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,356 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 700,702 | 663,710 | sum | Ints2d | 702,703 | 702,703 | class Ints2d(_Array2d, _Ints):
"""2-dimensional array of ints."""
T: "Ints2d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=2, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[Ints1d]: ...
... | class Ints2d(_Array2d, _Ints):
"""2-dimensional array of ints."""
T: "Ints2d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=2, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[Ints1d]: ...
... | def sum(self, keepdims: Fal = False, axis: int = -1, out: Optional["Ints1d"] = None) -> Ints1d: ...
| def sum(self, keepdims: Fal = False, axis: int = -1, out: Optional["Ints1d"] = None) -> Ints1d: ...
| 17 | 557 | 43 | 600 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,357 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 870,872 | 821,880 | sum | Ints3d | 872,873 | 872,873 | class Ints3d(_Array3d, _Ints):
"""3-dimensional array of ints."""
T: "Ints3d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=3, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[Ints2d]: ...
... | class Ints3d(_Array3d, _Ints):
"""3-dimensional array of ints."""
T: "Ints3d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=3, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[Ints2d]: ...
... | def sum(self, *, keepdims: Fal, axis: TwoAx, out: Optional[Ints1d] = None) -> Ints1d: ...
| def sum(self, *, keepdims: Fal, axis: TwoAx, out: Optional[Ints1d] = None) -> Ints1d: ...
| 14 | 741 | 42 | 783 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,358 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 1059,1060 | 994,1064 | sum | Ints4d | 1060,1061 | 1060,1061 | class Ints4d(_Array4d, _Ints):
"""4-dimensional array of ints."""
T: "Ints4d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=4, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[Ints3d]: ...
... | class Ints4d(_Array4d, _Ints):
"""4-dimensional array of ints."""
T: "Ints4d"
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=4, dtype="i")
@abstractmethod
def __iter__(self) -> Iterator[Ints3d]: ...
... | def sum(self, *, keepdims: bool = False, axis: _4_AllAx = None, out: Optional[Union[Ints1d, Ints2d, Ints3d, "Ints4d"]] = None) -> _4I_ReduceResults: ...
| def sum(self, *, keepdims: bool = False, axis: _4_AllAx = None, out: Optional[Union[Ints1d, Ints2d, Ints3d, "Ints4d"]] = None) -> _4I_ReduceResults: ...
| 21 | 862 | 72 | 934 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,359 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 1123,1124 | 1109,1163 | copy | Padded | 1124,1131 | 1124,1131 | @dataclass
class Padded:
"""A batch of padded sequences, sorted by decreasing length. The data array
is of shape (step, batch, ...). The auxiliary array size_at_t indicates the
length of the batch at each timestep, so you can do data[:, :size_at_t[t]] to
shrink the batch. The lengths array indicates the... | @dataclass
class Padded:
"""A batch of padded sequences, sorted by decreasing length. The data array
is of shape (step, batch, ...). The auxiliary array size_at_t indicates the
length of the batch at each timestep, so you can do data[:, :size_at_t[t]] to
shrink the batch. The lengths array indicates the... | return Padded(
self.data.copy(),
self.size_at_t.copy(),
self.lengths.copy(),
self.indices.copy(),
)
| return Padded(
self.data.copy(),
self.size_at_t.copy(),
self.lengths.copy(),
self.indices.copy(),
)
| 7 | 479 | 55 | 534 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,360 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 1229,1230 | 1163,1236 | _get_starts | Ragged | 1230,1232 | 1230,1232 | @dataclass
class Ragged:
"""A batch of concatenated sequences, that vary in the size of their
first dimension. Ragged allows variable-length sequence data to be contiguous
in memory, without padding.
Indexing into Ragged is just like indexing into the *lengths* array, except
it returns a Ragged obj... | @dataclass
class Ragged:
"""A batch of concatenated sequences, that vary in the size of their
first dimension. Ragged allows variable-length sequence data to be contiguous
in memory, without padding.
Indexing into Ragged is just like indexing into the *lengths* array, except
it returns a Ragged obj... | return self._get_starts_ends()[:-1]
| return self._get_starts_ends()[:-1]
| 2 | 935 | 19 | 954 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,362 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 436,438 | 387,452 | argmax | _Array1d | 438,439 | 438,439 | class _Array1d(_Array):
"""1-dimensional array."""
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=1)
@property
@abstractmethod
def ndim(self) -> Literal[1]: ...
@property
@abstractmethod
def sh... | class _Array1d(_Array):
"""1-dimensional array."""
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=1)
@property
@abstractmethod
def ndim(self) -> Literal[1]: ...
@property
@abstractmethod
def sh... | def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints1d": ...
| def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints1d": ...
| 15 | 965 | 41 | 1,006 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,363 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 602,604 | 553,612 | mean | _Array2d | 604,605 | 604,605 | class _Array2d(_Array):
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=2)
@property
@abstractmethod
def ndim(self) -> Literal[2]: ...
@property
@abstractmethod
def shape(self) -> Tuple[int, int]: ..... | class _Array2d(_Array):
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=2)
@property
@abstractmethod
def ndim(self) -> Literal[2]: ...
@property
@abstractmethod
def shape(self) -> Tuple[int, int]: ..... | def mean(self, keepdims: Fal = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> Floats1d: ...
| def mean(self, keepdims: Fal = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> Floats1d: ...
| 21 | 931 | 54 | 985 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,364 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 727,728 | 710,762 | astype | _Array3d | 728,729 | 728,729 | class _Array3d(_Array):
"""3-dimensional array of floats"""
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=3)
@property
@abstractmethod
def ndim(self) -> Literal[3]: ...
@property
@abstractmethod
... | class _Array3d(_Array):
"""3-dimensional array of floats"""
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=3)
@property
@abstractmethod
def ndim(self) -> Literal[3]: ...
@property
@abstractmethod
... | def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "Array3d": ...
| def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "Array3d": ...
| 23 | 793 | 48 | 841 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,365 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 897,898 | 880,924 | astype | _Array4d | 898,899 | 898,899 | class _Array4d(_Array):
"""4-dimensional array."""
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=4)
@property
@abstractmethod
def ndim(self) -> Literal[4]: ...
@property
@abstractmethod
def sh... | class _Array4d(_Array):
"""4-dimensional array."""
@classmethod
def __get_validators__(cls):
"""Runtime validation for pydantic."""
yield lambda v: validate_array(v, ndim=4)
@property
@abstractmethod
def ndim(self) -> Literal[4]: ...
@property
@abstractmethod
def sh... | def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "_Array4d": ...
| def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "_Array4d": ...
| 23 | 674 | 48 | 722 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,366 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 353,354 | 348,359 | fill | _Floats | 354,355 | 354,355 | class _Floats(_Array):
@property
@abstractmethod
def dtype(self) -> DTypesFloat: ...
@abstractmethod
FILL_FUNC_BODY @abstractmethod
def reshape(self, shape: Shape, *, order: str = ...) -> "_Floats": ...
| class _Floats(_Array):
@property
@abstractmethod
def dtype(self) -> DTypesFloat: ...
@abstractmethod
FILL_FUNC_BODY @abstractmethod
def reshape(self, shape: Shape, *, order: str = ...) -> "_Floats": ...
| def fill(self, value: float) -> None: ...
| def fill(self, value: float) -> None: ...
| 7 | 87 | 17 | 104 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,367 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/types.py | 366,367 | 359,370 | reshape | _Ints | 367,368 | 367,368 | class _Ints(_Array):
@property
@abstractmethod
def dtype(self) -> DTypesInt: ...
@abstractmethod
def fill(self, value: int) -> None: ...
@abstractmethod
FILL_FUNC_BODY
| class _Ints(_Array):
@property
@abstractmethod
def dtype(self) -> DTypesInt: ...
@abstractmethod
def fill(self, value: int) -> None: ...
@abstractmethod
FILL_FUNC_BODY
| def reshape(self, shape: Shape, *, order: str = ...) -> "_Ints": ...
| def reshape(self, shape: Shape, *, order: str = ...) -> "_Ints": ...
| 12 | 74 | 30 | 104 | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... | import sys
from abc import abstractmethod
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Sequence,
Sized,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy
from .com... |
35,369 | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc | /home/hieuvd/dung_repo/raw/stars_02/explosion_thinc/thinc/thinc/util.py | 635,636 | 624,647 | check_consistency | ArrayInfo | 636,647 | 636,647 | @dataclass
class ArrayInfo:
"""Container for info for checking array compatibility."""
shape: types.Shape
dtype: types.DTypes
@classmethod
def from_array(cls, arr: ArrayXd):
return cls(shape=arr.shape, dtype=arr.dtype)
def check_consistency(self, arr: ArrayXd):
FILL_FUNC_BODY | @dataclass
class ArrayInfo:
"""Container for info for checking array compatibility."""
shape: types.Shape
dtype: types.DTypes
@classmethod
def from_array(cls, arr: ArrayXd):
return cls(shape=arr.shape, dtype=arr.dtype)
def check_consistency(self, arr: ArrayXd):
FILL_FUNC_BODY | if arr.shape != self.shape:
raise ValueError(
f"Shape mismatch in backprop. Y: {self.shape}, dY: {arr.shape}"
)
if arr.dtype != self.dtype:
raise ValueError(
f"Type mismatch in backprop. Y: {self.dtype}, dY: {arr.dtype}"
)
... | if arr.shape != self.shape:
raise ValueError(
f"Shape mismatch in backprop. Y: {self.shape}, dY: {arr.shape}"
)
if arr.dtype != self.dtype:
raise ValueError(
f"Type mismatch in backprop. Y: {self.dtype}, dY: {arr.dtype}"
)
... | 33 | 106 | 116 | 222 | import contextlib
import functools
import inspect
import os
import platform
import random
import tempfile
import threading
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Sequence,
... | import contextlib
import functools
import inspect
import os
import platform
import random
import tempfile
import threading
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Sequence,
... |
35,370 | /home/hieuvd/dung_repo/raw/stars_02/facebookresearch_Detic/Detic | /home/hieuvd/dung_repo/raw/stars_02/facebookresearch_Detic/Detic/tools/preprocess_imagenet22k.py | 70,71 | 1,149 | preprocess | 71,147 | 71,147 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import numpy as np
import sys
sys.path.insert(0, 'third_party/CenterNet2/')
sys.path.insert(0, 'third_party/Deformable-DETR')
from detic.data.tar_dataset import _TarDataset, DiskTarDataset
import pickle
import io
import gzip
import ti... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import numpy as np
import sys
sys.path.insert(0, 'third_party/CenterNet2/')
sys.path.insert(0, 'third_party/Deformable-DETR')
from detic.data.tar_dataset import _TarDataset, DiskTarDataset
import pickle
import io
import gzip
import ti... | # Follow https://github.com/Alibaba-MIIL/ImageNet21K/blob/main/dataset_preprocessing/processing_script.sh
# Expect 12358684 samples with 11221 classes
# ImageNet folder has 21841 classes (synsets)
i22kdir = '/datasets01/imagenet-22k/062717/'
i22ktarlogs = '/checkpoint/imisra/datasets/imagenet-22k/t... | # Follow https://github.com/Alibaba-MIIL/ImageNet21K/blob/main/dataset_preprocessing/processing_script.sh
# Expect 12358684 samples with 11221 classes
# ImageNet folder has 21841 classes (synsets)
i22kdir = '/datasets01/imagenet-22k/062717/'
i22ktarlogs = '/checkpoint/imisra/datasets/imagenet-22k/t... | 221 | 662 | 1,255 | 1,917 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import numpy as np
import sys
sys.path.insert(0, 'third_party/CenterNet2/')
sys.path.insert(0, 'third_party/Deformable-DETR')
from detic.data.tar_dataset import _TarDataset, DiskTarDataset
import pickle
import io
import gzip
import ti... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import numpy as np
import sys
sys.path.insert(0, 'third_party/CenterNet2/')
sys.path.insert(0, 'third_party/Deformable-DETR')
from detic.data.tar_dataset import _TarDataset, DiskTarDataset
import pickle
import io
import gzip
import ti... | |
35,722 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/datasets/_fetch_adult.py | 11,12 | 1,108 | fetch_adult | 95,108 | 12,108 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_adult(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
FILL_FUNC_BODY | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_adult(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
"""Load the UCI Adult da... | if not data_home:
data_home = pathlib.Path().home() / _DOWNLOAD_DIRECTORY_NAME
# For data_home see
# https://github.com/scikit-learn/scikit-learn/issues/27447
return fetch_openml(
data_id=1590,
data_home=str(data_home),
cache=cache,
as_frame=as_frame,
ret... | """Load the UCI Adult dataset (binary classification).
Read more in the :ref:`User Guide <boston_housing_data>`.
Download it if necessary.
============== ====================
Samples total 48842
Dimensionality 14
Features numeric, categorica... | 23 | 932 | 153 | 1,085 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_adult(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
FILL_FUNC_BODY | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_adult(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
"""Load the UCI Adult da... | |
35,723 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/datasets/_fetch_bank_marketing.py | 11,14 | 1,112 | fetch_bank_marketing | 99,112 | 14,112 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_bank_marketing(
*, cache=True, data_home=None, as_frame=True, return_X_y=False
):
FILL_FUNC_BOD... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_bank_marketing(
*, cache=True, data_home=None, as_frame=True, return_X_y=False
):
"""Load t... | if not data_home:
data_home = pathlib.Path().home() / _DOWNLOAD_DIRECTORY_NAME
# For data_home see
# https://github.com/scikit-learn/scikit-learn/issues/27447
return fetch_openml(
data_id=1461,
data_home=str(data_home),
cache=cache,
as_frame=as_frame,
ret... | """Load the UCI bank marketing dataset (binary classification).
Download it if necessary.
============== ====================
Samples total 45211
Dimensionality 16
Features numeric, categorical
Classes 2
======... | 23 | 951 | 153 | 1,104 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_bank_marketing(
*, cache=True, data_home=None, as_frame=True, return_X_y=False
):
FILL_FUNC_BOD... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_bank_marketing(
*, cache=True, data_home=None, as_frame=True, return_X_y=False
):
"""Load t... | |
35,724 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/datasets/_fetch_boston.py | 14,17 | 1,149 | fetch_boston | 133,149 | 17,149 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
import warnings
from sklearn.datasets import fetch_openml
from fairlearn.exceptions import DataFairnessWarning
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_boston(
*, cache=True, da... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
import warnings
from sklearn.datasets import fetch_openml
from fairlearn.exceptions import DataFairnessWarning
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_boston(
*, cache=True, da... | if warn:
msg = "You are about to use a dataset with known fairness issues."
warnings.warn(DataFairnessWarning(msg))
if not data_home:
data_home = pathlib.Path().home() / _DOWNLOAD_DIRECTORY_NAME
# For data_home see
# https://github.com/scikit-learn/scikit-learn/issues/27447
... | """Load the boston housing dataset (regression).
Download it if necessary.
============== ==============
Samples total 506
Dimensionality 13
Features real
Target real 5. - 50.
============== ==============
Source:
- ... | 39 | 1,434 | 192 | 1,626 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
import warnings
from sklearn.datasets import fetch_openml
from fairlearn.exceptions import DataFairnessWarning
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_boston(
*, cache=True, da... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
import warnings
from sklearn.datasets import fetch_openml
from fairlearn.exceptions import DataFairnessWarning
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_boston(
*, cache=True, da... | |
35,725 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/datasets/_fetch_credit_card.py | 11,12 | 1,94 | fetch_credit_card | 81,94 | 12,94 | # Copyright (c) Fairlearn Contributors.
# Licensed under the MIT License.
from pathlib import Path
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_credit_card(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
FILL_FUNC_BODY | # Copyright (c) Fairlearn Contributors.
# Licensed under the MIT License.
from pathlib import Path
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_credit_card(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
"""Load the 'Default of Credit Car... | if not data_home:
data_home = Path().home() / _DOWNLOAD_DIRECTORY_NAME
# For data_home see
# https://github.com/scikit-learn/scikit-learn/issues/27447
return fetch_openml(
data_id=42477,
data_home=str(data_home),
cache=cache,
as_frame=as_frame,
return_X_y... | """Load the 'Default of Credit Card clients' dataset (binary classification).
=============== ===============
Samples total 30000
Dimensionality 23
Features real
Classes 2
=============== ===============
Sour... | 23 | 845 | 151 | 996 | # Copyright (c) Fairlearn Contributors.
# Licensed under the MIT License.
from pathlib import Path
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_credit_card(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
FILL_FUNC_BODY | # Copyright (c) Fairlearn Contributors.
# Licensed under the MIT License.
from pathlib import Path
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_credit_card(*, cache=True, data_home=None, as_frame=True, return_X_y=False):
"""Load the 'Default of Credit Car... | |
35,726 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/datasets/_fetch_diabetes_hospital.py | 11,14 | 1,117 | fetch_diabetes_hospital | 104,117 | 14,117 | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_diabetes_hospital(
*, as_frame=True, cache=True, data_home=None, return_X_y=False
):
FILL_FUNC_BODY | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_diabetes_hospital(
*, as_frame=True, cache=True, data_home=None, return_X_y=False
):
"""Load the preprocessed Diabete... | if not data_home:
data_home = pathlib.Path().home() / _DOWNLOAD_DIRECTORY_NAME
# For data_home see
# https://github.com/scikit-learn/scikit-learn/issues/27447
return fetch_openml(
data_id=43874,
data_home=str(data_home),
cache=cache,
as_frame=as_frame,
re... | """Load the preprocessed Diabetes 130-Hospitals dataset (binary classification).
Download it if necessary.
============== ============================
Samples total 101766
Dimensionality 24
Features numeric, categorical, string
... | 23 | 1,120 | 154 | 1,274 | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_diabetes_hospital(
*, as_frame=True, cache=True, data_home=None, return_X_y=False
):
FILL_FUNC_BODY | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
import pathlib
from sklearn.datasets import fetch_openml
from ._constants import _DOWNLOAD_DIRECTORY_NAME
def fetch_diabetes_hospital(
*, as_frame=True, cache=True, data_home=None, return_X_y=False
):
"""Load the preprocessed Diabete... | |
35,729 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/metrics/_make_derived_metric.py | 96,102 | 1,158 | make_derived_metric | 154,158 | 102,158 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import functools
import inspect
from typing import Callable, List, Union
from ._metric_frame import MetricFrame
transform_options = [
"difference",
"group_min",
"group_max",
"ratio",
]
parameters_for_... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import functools
import inspect
from typing import Callable, List, Union
from ._metric_frame import MetricFrame
transform_options = [
"difference",
"group_min",
"group_max",
"ratio",
]
parameters_for_... | dm = _DerivedMetric(
metric=metric, transform=transform, sample_param_names=sample_param_names
)
return dm
| """Create a scalar returning metric function based on aggregation of a disaggregated metric.
Many higher order machine learning operations (such as hyperparameter tuning)
make use of functions which return scalar metrics. We can create such a function
for our disaggregated metrics with this function.
... | 9 | 1,575 | 44 | 1,619 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import functools
import inspect
from typing import Callable, List, Union
from ._metric_frame import MetricFrame
transform_options = [
"difference",
"group_min",
"group_max",
"ratio",
]
parameters_for_... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import functools
import inspect
from typing import Callable, List, Union
from ._metric_frame import MetricFrame
transform_options = [
"difference",
"group_min",
"group_max",
"ratio",
]
parameters_for_... | |
35,731 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/postprocessing/_interpolated_thresholder.py | 123,124 | 21,199 | _pmf_predict | InterpolatedThresholder | 139,171 | 124,171 | class InterpolatedThresholder(BaseEstimator, MetaEstimatorMixin):
r"""Binary predictor that thresholds continuous predictions of a base estimator.
At prediction time, the predictor takes as input both standard and sensitive features.
Based on the values of sensitive features, it then applies a randomized t... | class InterpolatedThresholder(BaseEstimator, MetaEstimatorMixin):
r"""Binary predictor that thresholds continuous predictions of a base estimator.
At prediction time, the predictor takes as input both standard and sensitive features.
Based on the values of sensitive features, it then applies a randomized t... | check_is_fitted(self)
base_predictions = np.array(
_get_soft_predictions(self.estimator_, X, self._predict_method)
)
(
_,
base_predictions_vector,
sensitive_feature_vector,
_,
) = _validate_and_reformat_input(
... | """Probabilistic mass function.
Parameters
----------
X : numpy.ndarray or pandas.DataFrame
Feature matrix
sensitive_features : numpy.ndarray, list, pandas.DataFrame, pandas.Series
Sensitive features to identify groups by
Returns
-------
... | 74 | 1,521 | 373 | 1,894 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
from warnings import warn
import numpy as np
from sklearn import clone
from sklearn.base import BaseEstimator, MetaEstimatorMixin
from sklearn.exceptions import NotFittedError
from sklearn.utils import check_random_sta... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
from warnings import warn
import numpy as np
from sklearn import clone
from sklearn.base import BaseEstimator, MetaEstimatorMixin
from sklearn.exceptions import NotFittedError
from sklearn.utils import check_random_sta... |
35,732 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/postprocessing/_plotting.py | 65,66 | 1,133 | _raise_if_not_threshold_optimizer | 66,74 | 66,74 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utilities for plotting curves."""
from sklearn.utils.validation import check_is_fitted
from ._constants import _MATPLOTLIB_IMPORT_ERROR_MESSAGE
from ._threshold_optimizer import ThresholdOptimizer
_debug_colors = ... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utilities for plotting curves."""
from sklearn.utils.validation import check_is_fitted
from ._constants import _MATPLOTLIB_IMPORT_ERROR_MESSAGE
from ._threshold_optimizer import ThresholdOptimizer
_debug_colors = ... | if not isinstance(obj, ThresholdOptimizer):
raise ValueError(
"Argument {} needs to be of type {}.".format(
obj.__name__, ThresholdOptimizer.__name__
)
)
| if not isinstance(obj, ThresholdOptimizer):
raise ValueError(
"Argument {} needs to be of type {}.".format(
obj.__name__, ThresholdOptimizer.__name__
)
)
| 18 | 1,390 | 67 | 1,457 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utilities for plotting curves."""
from sklearn.utils.validation import check_is_fitted
from ._constants import _MATPLOTLIB_IMPORT_ERROR_MESSAGE
from ._threshold_optimizer import ThresholdOptimizer
_debug_colors = ... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utilities for plotting curves."""
from sklearn.utils.validation import check_is_fitted
from ._constants import _MATPLOTLIB_IMPORT_ERROR_MESSAGE
from ._threshold_optimizer import ThresholdOptimizer
_debug_colors = ... | |
35,733 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/postprocessing/_threshold_operation.py | 26,28 | 5,53 | threshold | ThresholdOperation | 29,31 | 28,31 | class ThresholdOperation:
"""Represents the threshold operations that are used in postprocessing approaches.
Threshold operations simply indicate a threshold and an operator, thereby defining a function.
The function can be evaluated at arbitrary points (usually the scores returned from
unconstrained p... | class ThresholdOperation:
"""Represents the threshold operations that are used in postprocessing approaches.
Threshold operations simply indicate a threshold and an operator, thereby defining a function.
The function can be evaluated at arbitrary points (usually the scores returned from
unconstrained p... | return self._threshold
| """Return the stored threshold."""
return self._threshold
| 2 | 447 | 10 | 457 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
class ThresholdOperation:
"""Represents the threshold operations that are used in postprocessing approaches.
Threshold operations simply indicate a threshold and an operator, thereby defining a function.
T... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
class ThresholdOperation:
"""Represents the threshold operations that are used in postprocessing approaches.
Threshold operations simply indicate a threshold and an operator, thereby defining a function.
T... |
35,737 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/preprocessing/_correlation_remover.py | 116,117 | 11,129 | _more_tags | CorrelationRemover | 117,129 | 117,129 | class CorrelationRemover(BaseEstimator, TransformerMixin):
r"""
A component that filters out sensitive correlations in a dataset.
CorrelationRemover applies a linear transformation to the non-sensitive feature columns
in order to remove their correlation with the sensitive feature columns while retaini... | class CorrelationRemover(BaseEstimator, TransformerMixin):
r"""
A component that filters out sensitive correlations in a dataset.
CorrelationRemover applies a linear transformation to the non-sensitive feature columns
in order to remove their correlation with the sensitive feature columns while retaini... | return {
"_xfail_checks": {
"check_parameters_default_constructible": (
"sensitive_feature_ids has to be explicitly set to "
"instantiate this estimator"
),
"check_transformer_data_not_an_array": (
... | return {
"_xfail_checks": {
"check_parameters_default_constructible": (
"sensitive_feature_ids has to be explicitly set to "
"instantiate this estimator"
),
"check_transformer_data_not_an_array": (
... | 35 | 1,363 | 116 | 1,479 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
class CorrelationRemover(BaseE... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
class CorrelationRemover(BaseE... |
35,738 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_exponentiated_gradient/_lagrangian.py | 281,282 | 271,283 | gap | _GapResult | 282,283 | 282,283 | class _GapResult:
"""The result of a duality gap computation."""
def __init__(self, L, L_low, L_high, gamma, error):
self.L = L
self.L_low = L_low
self.L_high = L_high
self.gamma = gamma
self.error = error
def gap(self):
FILL_FUNC_BODY | class _GapResult:
"""The result of a duality gap computation."""
def __init__(self, L, L_low, L_high, gamma, error):
self.L = L
self.L_low = L_low
self.L_high = L_high
self.gamma = gamma
self.error = error
def gap(self):
FILL_FUNC_BODY | return max(self.L - self.L_low, self.L_high - self.L)
| return max(self.L - self.L_low, self.L_high - self.L)
| 7 | 103 | 26 | 129 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
from time import time
import numpy as np
import pandas as pd
import scipy.optimize as opt
from sklearn import clone
from sklearn.dummy import DummyClassifier
from fairlearn.reductions._moments import Cl... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
from time import time
import numpy as np
import pandas as pd
import scipy.optimize as opt
from sklearn import clone
from sklearn.dummy import DummyClassifier
from fairlearn.reductions._moments import Cl... |
35,740 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_grid_search/_grid_generator.py | 117,118 | 24,135 | accumulate_integer_grid | _GridGenerator | 118,135 | 118,135 | class _GridGenerator:
"""A generator of a grid of points with a bounded L1 norm."""
def __init__(
self,
grid_size,
grid_limit,
pos_basis,
neg_basis,
neg_allowed,
force_L1_norm,
grid_offset=None,
):
"""Initialize with grid generator uti... | class _GridGenerator:
"""A generator of a grid of points with a bounded L1 norm."""
def __init__(
self,
grid_size,
grid_limit,
pos_basis,
neg_basis,
neg_allowed,
force_L1_norm,
grid_offset=None,
):
"""Initialize with grid generator uti... | if index == self.dim:
self.accumulator.append(self.entry.copy())
else:
if (index == self.dim - 1) and (self.force_L1_norm):
if self.neg_allowed[index] and max_val > 0:
values = [-max_val, max_val]
else:
value... | if index == self.dim:
self.accumulator.append(self.entry.copy())
else:
if (index == self.dim - 1) and (self.force_L1_norm):
if self.neg_allowed[index] and max_val > 0:
values = [-max_val, max_val]
else:
value... | 60 | 1,091 | 219 | 1,310 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
GRID_DIMENSION_WARN_THRESHOLD = 4
GRID_DIMENSION_WARN_TEMPLATE = (
"The grid has %d dimensions. It is not recommended to ... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
GRID_DIMENSION_WARN_THRESHOLD = 4
GRID_DIMENSION_WARN_TEMPLATE = (
"The grid has %d dimensions. It is not recommended to ... |
35,742 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/bounded_group_loss.py | 160,161 | 148,170 | eval | AbsoluteLoss | 162,170 | 161,170 | class AbsoluteLoss:
"""Class to evaluate absolute loss.
Read more in the :ref:`User Guide <constraints_regression>`.
"""
def __init__(self, min_val, max_val):
self.min_val = min_val
self.max_val = max_val
self.min = 0
self.max = np.abs(max_val - min_val)
def eval(s... | class AbsoluteLoss:
"""Class to evaluate absolute loss.
Read more in the :ref:`User Guide <constraints_regression>`.
"""
def __init__(self, min_val, max_val):
self.min_val = min_val
self.max_val = max_val
self.min = 0
self.max = np.abs(max_val - min_val)
def eval(s... | return np.abs(
np.clip(y_true, self.min_val, self.max_val)
- np.clip(y_pred, self.min_val, self.max_val)
)
# Ensure that AbsoluteLoss shows up in correct place in documentation
# when it is used as a base class
| """Evaluate the absolute loss for the given set of true and predicted values."""
return np.abs(
np.clip(y_true, self.min_val, self.max_val)
- np.clip(y_pred, self.min_val, self.max_val)
)
# Ensure that AbsoluteLoss shows up in correct place in documentation
# when it is... | 30 | 160 | 91 | 251 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _GROUP_ID, _LABEL, _LOSS, _PREDICTION, LossMoment
class ConditionalLossMome... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _GROUP_ID, _LABEL, _LOSS, _PREDICTION, LossMoment
class ConditionalLossMome... |
35,743 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/bounded_group_loss.py | 68,69 | 12,105 | gamma | ConditionalLossMoment | 70,78 | 69,78 | class ConditionalLossMoment(LossMoment):
r"""A moment for constraining the mean loss or the worst-case loss by a group.
Read more in the :ref:`User Guide <bounded_group_loss>`.
Parameters
----------
loss : {SquareLoss, AbsoluteLoss}
A loss object with an `eval` method, e.g. `SquareLoss` or... | class ConditionalLossMoment(LossMoment):
r"""A moment for constraining the mean loss or the worst-case loss by a group.
Read more in the :ref:`User Guide <bounded_group_loss>`.
Parameters
----------
loss : {SquareLoss, AbsoluteLoss}
A loss object with an `eval` method, e.g. `SquareLoss` or... | self.tags[_PREDICTION] = predictor(self.X)
self.tags[_LOSS] = self.reduction_loss.eval(
self.tags[_LABEL], self.tags[_PREDICTION]
)
expect_attr = self.tags.groupby(_GROUP_ID).mean()
self._gamma_descr = str(expect_attr[[_LOSS]])
return expect_attr[_LOSS]
| """Calculate the degree to which constraints are currently violated by the predictor."""
self.tags[_PREDICTION] = predictor(self.X)
self.tags[_LOSS] = self.reduction_loss.eval(
self.tags[_LABEL], self.tags[_PREDICTION]
)
expect_attr = self.tags.groupby(_GROUP_ID).mean... | 17 | 984 | 121 | 1,105 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _GROUP_ID, _LABEL, _LOSS, _PREDICTION, LossMoment
class ConditionalLossMome... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _GROUP_ID, _LABEL, _LOSS, _PREDICTION, LossMoment
class ConditionalLossMome... |
35,744 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/bounded_group_loss.py | 140,141 | 128,148 | eval | SquareLoss | 142,148 | 141,148 | class SquareLoss:
"""Class to evaluate the square loss.
Read more in the :ref:`User Guide <constraints_regression>`.
"""
def __init__(self, min_val, max_val):
self.min_val = min_val
self.max_val = max_val
self.min = 0
self.max = (max_val - min_val) ** 2
def eval(se... | class SquareLoss:
"""Class to evaluate the square loss.
Read more in the :ref:`User Guide <constraints_regression>`.
"""
def __init__(self, min_val, max_val):
self.min_val = min_val
self.max_val = max_val
self.min = 0
self.max = (max_val - min_val) ** 2
def eval(se... | return (
np.clip(y_true, self.min_val, self.max_val)
- np.clip(y_pred, self.min_val, self.max_val)
) ** 2
| """Evaluate the square loss for the given set of true and predicted values."""
return (
np.clip(y_true, self.min_val, self.max_val)
- np.clip(y_pred, self.min_val, self.max_val)
) ** 2
| 12 | 160 | 63 | 223 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _GROUP_ID, _LABEL, _LOSS, _PREDICTION, LossMoment
class ConditionalLossMome... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _GROUP_ID, _LABEL, _LOSS, _PREDICTION, LossMoment
class ConditionalLossMome... |
35,745 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/error_rate.py | 63,64 | 17,103 | load_data | ErrorRate | 65,76 | 64,76 | class ErrorRate(ClassificationMoment):
r"""Misclassification error as a moment.
A classifier :math:`h(X)` has the misclassification error equal to
.. math::
P[h(X) \ne Y]
It is also possible to specify costs for false positives and false
negatives. The error then evaluates to
.. math::... | class ErrorRate(ClassificationMoment):
r"""Misclassification error as a moment.
A classifier :math:`h(X)` has the misclassification error equal to
.. math::
P[h(X) \ne Y]
It is also possible to specify costs for false positives and false
negatives. The error then evaluates to
.. math::... | _, y_train, sf_train, _ = _validate_and_reformat_input(
X,
y,
enforce_binary_labels=True,
sensitive_features=sensitive_features,
control_features=control_features,
)
# The following uses X so that the estimators get X untouched
... | """Load the specified data into the object."""
_, y_train, sf_train, _ = _validate_and_reformat_input(
X,
y,
enforce_binary_labels=True,
sensitive_features=sensitive_features,
control_features=control_features,
)
# The following... | 30 | 879 | 128 | 1,007 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _LABEL, ClassificationMoment
_MESSAGE_BAD_COSTS = (
"costs needs to be a... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from fairlearn.utils._input_validation import _validate_and_reformat_input
from .moment import _ALL, _LABEL, ClassificationMoment
_MESSAGE_BAD_COSTS = (
"costs needs to be a... |
35,746 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/moment.py | 92,93 | 89,98 | _moment_type | ClassificationMoment | 93,98 | 93,98 | class ClassificationMoment(Moment):
"""Moment that can be expressed as weighted classification error."""
def _moment_type(self):
FILL_FUNC_BODY | class ClassificationMoment(Moment):
"""Moment that can be expressed as weighted classification error."""
def _moment_type(self):
FILL_FUNC_BODY | return ClassificationMoment
# Ensure that ClassificationMoment shows up in correct place in documentation
# when it is used as a base class
| return ClassificationMoment
# Ensure that ClassificationMoment shows up in correct place in documentation
# when it is used as a base class
| 22 | 45 | 40 | 85 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pandas as pd
_GROUP_ID = "group_id"
_EVENT = "event"
_LABEL = "label"
_LOSS = "loss"
_PREDICTION = "pred"
_ALL = "all"
_SIGN = "sign"
class Moment:
"""Generic moment.
Our implementations of the reduct... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pandas as pd
_GROUP_ID = "group_id"
_EVENT = "event"
_LABEL = "label"
_LOSS = "loss"
_PREDICTION = "pred"
_ALL = "all"
_SIGN = "sign"
class Moment:
"""Generic moment.
Our implementations of the reduct... |
35,747 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/moment.py | 108,109 | 101,114 | _moment_type | LossMoment | 109,114 | 109,114 | class LossMoment(Moment):
"""Moment that can be expressed as weighted loss."""
def __init__(self, loss):
super().__init__()
self.reduction_loss = loss
def _moment_type(self):
FILL_FUNC_BODY | class LossMoment(Moment):
"""Moment that can be expressed as weighted loss."""
def __init__(self, loss):
super().__init__()
self.reduction_loss = loss
def _moment_type(self):
FILL_FUNC_BODY | return LossMoment
# Ensure that LossMoment shows up in correct place in documentation
# when it is used as a base class
| return LossMoment
# Ensure that LossMoment shows up in correct place in documentation
# when it is used as a base class
| 22 | 73 | 40 | 113 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pandas as pd
_GROUP_ID = "group_id"
_EVENT = "event"
_LABEL = "label"
_LOSS = "loss"
_PREDICTION = "pred"
_ALL = "all"
_SIGN = "sign"
class Moment:
"""Generic moment.
Our implementations of the reduct... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pandas as pd
_GROUP_ID = "group_id"
_EVENT = "event"
_LABEL = "label"
_LOSS = "loss"
_PREDICTION = "pred"
_ALL = "all"
_SIGN = "sign"
class Moment:
"""Generic moment.
Our implementations of the reduct... |
35,748 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/reductions/_moments/moment.py | 30,31 | 15,86 | load_data | Moment | 42,53 | 31,53 | class Moment:
"""Generic moment.
Our implementations of the reductions approach to fairness
:footcite:p:`agarwal2018reductions` make use
of :class:`Moment` objects to describe both the optimization objective
and the fairness constraints
imposed on the solution. This is an abstract class for all... | class Moment:
"""Generic moment.
Our implementations of the reductions approach to fairness
:footcite:p:`agarwal2018reductions` make use
of :class:`Moment` objects to describe both the optimization objective
and the fairness constraints
imposed on the solution. This is an abstract class for all... | assert self.data_loaded is False, "data can be loaded only once"
if sensitive_features is not None:
assert isinstance(sensitive_features, pd.Series)
self.X = X
self._y = y
self.tags = pd.DataFrame({_LABEL: y})
if sensitive_features is not None:
sel... | """Load a set of data for use by this object.
Parameters
----------
X : array
The feature array
y : :class:`pandas.Series`
The label vector
sensitive_features : :class:`pandas.Series`
The sensitive feature vector (default None)
... | 42 | 577 | 134 | 711 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pandas as pd
_GROUP_ID = "group_id"
_EVENT = "event"
_LABEL = "label"
_LOSS = "loss"
_PREDICTION = "pred"
_ALL = "all"
_SIGN = "sign"
class Moment:
"""Generic moment.
Our implementations of the reduct... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import pandas as pd
_GROUP_ID = "group_id"
_EVENT = "event"
_LABEL = "label"
_LOSS = "loss"
_PREDICTION = "pred"
_ALL = "all"
_SIGN = "sign"
class Moment:
"""Generic moment.
Our implementations of the reduct... |
35,749 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/show_versions.py | 73,74 | 1,85 | show_versions | 75,85 | 74,85 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utility methods to print system info for debugging.
Adapted from :py:func:`pandas.show_versions` and :py:func:`sklearn.show_versions`.
""" # noqa: RST304
import platform
import sys
def _get_sys_info():
"""Sy... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utility methods to print system info for debugging.
Adapted from :py:func:`pandas.show_versions` and :py:func:`sklearn.show_versions`.
""" # noqa: RST304
import platform
import sys
def _get_sys_info():
"""Sy... | sys_info = _get_sys_info()
deps_info = _get_deps_info()
print("\nSystem:")
for k, stat in sys_info.items():
print("{k:>10}: {stat}".format(k=k, stat=stat))
print("\nPython dependencies:")
for k, stat in deps_info.items():
print("{k:>13}: {stat}".format(k=k, stat=stat))
| """Print useful debugging information."""
sys_info = _get_sys_info()
deps_info = _get_deps_info()
print("\nSystem:")
for k, stat in sys_info.items():
print("{k:>10}: {stat}".format(k=k, stat=stat))
print("\nPython dependencies:")
for k, stat in deps_info.items():
print("{k:... | 25 | 481 | 134 | 615 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utility methods to print system info for debugging.
Adapted from :py:func:`pandas.show_versions` and :py:func:`sklearn.show_versions`.
""" # noqa: RST304
import platform
import sys
def _get_sys_info():
"""Sy... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Utility methods to print system info for debugging.
Adapted from :py:func:`pandas.show_versions` and :py:func:`sklearn.show_versions`.
""" # noqa: RST304
import platform
import sys
def _get_sys_info():
"""Sy... | |
35,750 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/utils/_common.py | 5,6 | 1,56 | _get_soft_predictions | 6,56 | 6,56 | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
def _get_soft_predictions(estimator, X, predict_method):
FILL_FUNC_BODY | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
def _get_soft_predictions(estimator, X, predict_method):
FILL_FUNC_BODY | r"""Return soft predictions of a classifier.
Parameters
----------
estimator : estimator
A scikit-learn compatible estimator
X : array-like
The intput for which the output is desired
predict_method : {'auto', 'predict_proba', 'decision_function', 'predict'\
}, defa... | r"""Return soft predictions of a classifier.
Parameters
----------
estimator : estimator
A scikit-learn compatible estimator
X : array-like
The intput for which the output is desired
predict_method : {'auto', 'predict_proba', 'decision_function', 'predict'\
}, defa... | 175 | 51 | 496 | 547 | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
def _get_soft_predictions(estimator, X, predict_method):
FILL_FUNC_BODY | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
def _get_soft_predictions(estimator, X, predict_method):
FILL_FUNC_BODY | |
35,751 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/fairlearn/utils/_input_manipulations.py | 9,10 | 1,38 | _convert_to_ndarray_and_squeeze | 16,27 | 10,27 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
_ARRAY_NOT_1D = "Supplied input array has more than one non-trivial dimension"
def _convert_to_ndarray_and_squeeze(target):
FILL_FUNC_BODYdef _convert_to_ndarray_1d(target):
"""Convert the inpu... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
_ARRAY_NOT_1D = "Supplied input array has more than one non-trivial dimension"
def _convert_to_ndarray_and_squeeze(target):
"""
Convert input to a `numpy.ndarray` and calls squeeze (to disp... | result = np.asarray(target)
if result.size == 0:
result = result
elif result.size > 1:
result = np.squeeze(result)
else:
result = result.reshape(1)
return result
| """
Convert input to a `numpy.ndarray` and calls squeeze (to dispose of unit length dimensions).
There is a special case for empty.
There is a special case to stop single element arrays being converted to scalars.
"""
result = np.asarray(target)
if result.size == 0:
result = result
... | 23 | 255 | 79 | 334 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
_ARRAY_NOT_1D = "Supplied input array has more than one non-trivial dimension"
def _convert_to_ndarray_and_squeeze(target):
FILL_FUNC_BODYdef _convert_to_ndarray_1d(target):
"""Convert the inpu... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import numpy as np
_ARRAY_NOT_1D = "Supplied input array has more than one non-trivial dimension"
def _convert_to_ndarray_and_squeeze(target):
"""
Convert input to a `numpy.ndarray` and calls squeeze (to disp... | |
35,753 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/scripts/_utils.py | 11,12 | 1,35 | _ensure_cwd_is_fairlearn_root_dir | 12,23 | 12,23 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
import os
_logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.INFO)
def _ensure_cwd_is_fairlearn_root_dir():
FILL_FUNC_BODYclass _LogWrapper:
def __init__(self, description):
... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
import os
_logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.INFO)
def _ensure_cwd_is_fairlearn_root_dir():
FILL_FUNC_BODYclass _LogWrapper:
def __init__(self, description):
... | # To ensure we're in the right directory that there's a fairlearn directory inside the
# current working directory as well as the presence of a README.rst file.
if not os.path.exists(os.path.join(os.getcwd(), "fairlearn")) or not os.path.exists(
os.path.join(os.getcwd(), "README.rst")
):
... | # To ensure we're in the right directory that there's a fairlearn directory inside the
# current working directory as well as the presence of a README.rst file.
if not os.path.exists(os.path.join(os.getcwd(), "fairlearn")) or not os.path.exists(
os.path.join(os.getcwd(), "README.rst")
):
... | 53 | 193 | 152 | 345 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
import os
_logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.INFO)
def _ensure_cwd_is_fairlearn_root_dir():
FILL_FUNC_BODYclass _LogWrapper:
def __init__(self, description):
... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import logging
import os
_logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.INFO)
def _ensure_cwd_is_fairlearn_root_dir():
FILL_FUNC_BODYclass _LogWrapper:
def __init__(self, description):
... | |
35,754 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/scripts/build_wheels.py | 29,30 | 1,52 | main | 30,50 | 30,50 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import argparse
import logging
import subprocess
import sys
from _utils import _ensure_cwd_is_fairlearn_root_dir, _LogWrapper
from process_readme import process_readme
_logger = logging.getLogger(__file__)
logging.bas... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import argparse
import logging
import subprocess
import sys
from _utils import _ensure_cwd_is_fairlearn_root_dir, _LogWrapper
from process_readme import process_readme
_logger = logging.getLogger(__file__)
logging.bas... | _ensure_cwd_is_fairlearn_root_dir()
parser = build_argument_parser()
args = parser.parse_args(argv)
with _LogWrapper("installation of fairlearn"):
subprocess.check_call(["pip", "install", "-e", "."])
with _LogWrapper("processing README.rst"):
process_readme("README.rst", "README.rs... | _ensure_cwd_is_fairlearn_root_dir()
parser = build_argument_parser()
args = parser.parse_args(argv)
with _LogWrapper("installation of fairlearn"):
subprocess.check_call(["pip", "install", "-e", "."])
with _LogWrapper("processing README.rst"):
process_readme("README.rst", "README.rs... | 42 | 219 | 239 | 458 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import argparse
import logging
import subprocess
import sys
from _utils import _ensure_cwd_is_fairlearn_root_dir, _LogWrapper
from process_readme import process_readme
_logger = logging.getLogger(__file__)
logging.bas... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import argparse
import logging
import subprocess
import sys
from _utils import _ensure_cwd_is_fairlearn_root_dir, _LogWrapper
from process_readme import process_readme
_logger = logging.getLogger(__file__)
logging.bas... | |
35,755 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/scripts/generate_maintainers_table.py | 24,25 | 1,48 | generate_table | 25,45 | 25,45 | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
"""
This script generates an html table of contributors, with names and avatars.
The list is generated from Fairlearn's teams on GitHub.
It's originally copied from scikit-learn and adapted for Fairlearn.
"""
from os import path
from pathlib impo... | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
"""
This script generates an html table of contributors, with names and avatars.
The list is generated from Fairlearn's teams on GitHub.
It's originally copied from scikit-learn and adapted for Fairlearn.
"""
from os import path
from pathlib impo... | lines = [
".. raw :: html\n",
" <!-- Generated by generate_maintainers_table.py -->",
' <div class="maintainers-container">',
" <style>",
" img.avatar {border-radius: 10px;}",
" </style>",
]
for alias, name in maintainers.items():
line... | lines = [
".. raw :: html\n",
" <!-- Generated by generate_maintainers_table.py -->",
' <div class="maintainers-container">',
" <style>",
" img.avatar {border-radius: 10px;}",
" </style>",
]
for alias, name in maintainers.items():
line... | 55 | 313 | 255 | 568 | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
"""
This script generates an html table of contributors, with names and avatars.
The list is generated from Fairlearn's teams on GitHub.
It's originally copied from scikit-learn and adapted for Fairlearn.
"""
from os import path
from pathlib impo... | # Copyright (c) Fairlearn contributors.
# Licensed under the MIT License.
"""
This script generates an html table of contributors, with names and avatars.
The list is generated from Fairlearn's teams on GitHub.
It's originally copied from scikit-learn and adapted for Fairlearn.
"""
from os import path
from pathlib impo... | |
35,756 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/scripts/install_requirements.py | 48,49 | 1,99 | _pin_requirements | 49,62 | 49,62 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to install the requirements files, optionally pinning versions."""
import argparse
import logging
import os
import subprocess
import sys
from _utils import _LogWrapper
_REQUIREMENTS_STEMS = ["requirements",... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to install the requirements files, optionally pinning versions."""
import argparse
import logging
import os
import subprocess
import sys
from _utils import _LogWrapper
_REQUIREMENTS_STEMS = ["requirements",... | with _LogWrapper("Pinning {0} into {1}".format(src_file, dst_file)):
_logger.debug("Reading file %s", src_file)
text_lines = []
with open(src_file, "r") as f:
text_lines = f.readlines()
result_lines = [_process_line(current_line) for current_line in text_lines]
... | with _LogWrapper("Pinning {0} into {1}".format(src_file, dst_file)):
_logger.debug("Reading file %s", src_file)
text_lines = []
with open(src_file, "r") as f:
text_lines = f.readlines()
result_lines = [_process_line(current_line) for current_line in text_lines]
... | 38 | 778 | 164 | 942 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to install the requirements files, optionally pinning versions."""
import argparse
import logging
import os
import subprocess
import sys
from _utils import _LogWrapper
_REQUIREMENTS_STEMS = ["requirements",... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to install the requirements files, optionally pinning versions."""
import argparse
import logging
import os
import subprocess
import sys
from _utils import _LogWrapper
_REQUIREMENTS_STEMS = ["requirements",... | |
35,757 | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn | /home/hieuvd/dung_repo/raw/stars_02/fairlearn_fairlearn/fairlearn/scripts/process_readme.py | 67,68 | 1,134 | _update_same_page_references | 68,83 | 68,83 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to dynamically update the ReadMe file for a particular release
Since PyPI and GitHub have slightly different ideas about markdown, we have to update
the ReadMe file when we upload to PyPI. This script makes t... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to dynamically update the ReadMe file for a particular release
Since PyPI and GitHub have slightly different ideas about markdown, we have to update
the ReadMe file when we upload to PyPI. This script makes t... | _logger.info("Starting %s", sys._getframe().f_code.co_name)
same_page_ref_pattern = re.compile(_SAME_MD_REF_PATTERN)
result = line
match = same_page_ref_pattern.search(line)
if match:
_logger.info("Matched %s", match)
for m in match.groups():
old_str = m
new_s... | _logger.info("Starting %s", sys._getframe().f_code.co_name)
same_page_ref_pattern = re.compile(_SAME_MD_REF_PATTERN)
result = line
match = same_page_ref_pattern.search(line)
if match:
_logger.info("Matched %s", match)
for m in match.groups():
old_str = m
new_s... | 38 | 1,273 | 189 | 1,462 | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to dynamically update the ReadMe file for a particular release
Since PyPI and GitHub have slightly different ideas about markdown, we have to update
the ReadMe file when we upload to PyPI. This script makes t... | # Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Script to dynamically update the ReadMe file for a particular release
Since PyPI and GitHub have slightly different ideas about markdown, we have to update
the ReadMe file when we upload to PyPI. This script makes t... | |
35,829 | /home/hieuvd/dung_repo/raw/stars_02/firmai_financial-machine-learning/financial-machine-learning | /home/hieuvd/dung_repo/raw/stars_02/firmai_financial-machine-learning/financial-machine-learning/git_status.py | 16,17 | 1,91 | get_repo_status | 17,36 | 17,36 | import os
from conf import PROJECT_ROOT_DIR
import re
import pandas as pd
from git_util import get_repo_attributes_dict, get_github_client, get_repo_path
def get_repo_list():
repo_df = pd.read_csv(os.path.join(PROJECT_ROOT_DIR, 'raw_data', 'url_list.csv'))
if 'repo_path' not in repo_df.columns:
repo_... | import os
from conf import PROJECT_ROOT_DIR
import re
import pandas as pd
from git_util import get_repo_attributes_dict, get_github_client, get_repo_path
def get_repo_list():
repo_df = pd.read_csv(os.path.join(PROJECT_ROOT_DIR, 'raw_data', 'url_list.csv'))
if 'repo_path' not in repo_df.columns:
repo_... | g = get_github_client()
repo_df = get_repo_list()
for idx, row in repo_df.iterrows():
repo_path = row['repo_path']
if not pd.isna(repo_path):
try:
print('processing [{}]'.format(repo_path))
repo = g.get_repo(repo_path)
repo_attr_di... | g = get_github_client()
repo_df = get_repo_list()
for idx, row in repo_df.iterrows():
repo_path = row['repo_path']
if not pd.isna(repo_path):
try:
print('processing [{}]'.format(repo_path))
repo = g.get_repo(repo_path)
repo_attr_di... | 47 | 857 | 229 | 1,086 | import os
from conf import PROJECT_ROOT_DIR
import re
import pandas as pd
from git_util import get_repo_attributes_dict, get_github_client, get_repo_path
def get_repo_list():
repo_df = pd.read_csv(os.path.join(PROJECT_ROOT_DIR, 'raw_data', 'url_list.csv'))
if 'repo_path' not in repo_df.columns:
repo_... | import os
from conf import PROJECT_ROOT_DIR
import re
import pandas as pd
from git_util import get_repo_attributes_dict, get_github_client, get_repo_path
def get_repo_list():
repo_df = pd.read_csv(os.path.join(PROJECT_ROOT_DIR, 'raw_data', 'url_list.csv'))
if 'repo_path' not in repo_df.columns:
repo_... | |
35,830 | /home/hieuvd/dung_repo/raw/stars_02/firmai_financial-machine-learning/financial-machine-learning | /home/hieuvd/dung_repo/raw/stars_02/firmai_financial-machine-learning/financial-machine-learning/git_util.py | 6,7 | 1,68 | get_github_client | 7,23 | 7,23 | from github import Github, Repository, GithubException
import os
import datetime
def get_github_client():
FILL_FUNC_BODYdef get_repo_path(in_url):
repo_path = None
if 'https://github.com/' in in_url:
url_query = in_url.replace('https://github.com/', '')
repo_path = '/'.join(url_query.split('/'... | from github import Github, Repository, GithubException
import os
import datetime
def get_github_client():
FILL_FUNC_BODYdef get_repo_path(in_url):
repo_path = None
if 'https://github.com/' in in_url:
url_query = in_url.replace('https://github.com/', '')
repo_path = '/'.join(url_query.split('/'... | # search for app_client and client secrets first, since this allow higher api request limit
github_app = os.environ.get('GIT_APP_ID')
if github_app is None:
github_token = os.environ.get('GIT_TOKEN')
g = Github(github_token)
else:
github_app_secret = os.environ.get('GIT_APP_SECRE... | # search for app_client and client secrets first, since this allow higher api request limit
github_app = os.environ.get('GIT_APP_ID')
if github_app is None:
github_token = os.environ.get('GIT_TOKEN')
g = Github(github_token)
else:
github_app_secret = os.environ.get('GIT_APP_SECRE... | 47 | 495 | 178 | 673 | from github import Github, Repository, GithubException
import os
import datetime
def get_github_client():
FILL_FUNC_BODYdef get_repo_path(in_url):
repo_path = None
if 'https://github.com/' in in_url:
url_query = in_url.replace('https://github.com/', '')
repo_path = '/'.join(url_query.split('/'... | from github import Github, Repository, GithubException
import os
import datetime
def get_github_client():
FILL_FUNC_BODYdef get_repo_path(in_url):
repo_path = None
if 'https://github.com/' in in_url:
url_query = in_url.replace('https://github.com/', '')
repo_path = '/'.join(url_query.split('/'... | |
35,831 | /home/hieuvd/dung_repo/raw/stars_02/firmai_financial-machine-learning/financial-machine-learning | /home/hieuvd/dung_repo/raw/stars_02/firmai_financial-machine-learning/financial-machine-learning/wiki_gen.py | 18,19 | 1,86 | get_wiki_rating | 19,26 | 19,26 | from conf import PROJECT_ROOT_DIR
import os
import pandas as pd
import numpy as np
import re
from git_status import get_repo_list
def get_wiki_status_color(input_text):
if input_text is None or input_text == 'inactive':
result_text = ":heavy_multiplication_x:"
else:
result_text = ":heavy_chec... | from conf import PROJECT_ROOT_DIR
import os
import pandas as pd
import numpy as np
import re
from git_status import get_repo_list
def get_wiki_status_color(input_text):
if input_text is None or input_text == 'inactive':
result_text = ":heavy_multiplication_x:"
else:
result_text = ":heavy_chec... | result_text = ''
if input_rating is not None and not np.isnan(input_rating):
rating = int(input_rating)
result_text = ':star:x{}'.format(rating)
return '<sub>{}</sub>'.format(result_text)
| result_text = ''
if input_rating is not None and not np.isnan(input_rating):
rating = int(input_rating)
result_text = ':star:x{}'.format(rating)
return '<sub>{}</sub>'.format(result_text)
| 19 | 1,178 | 81 | 1,259 | from conf import PROJECT_ROOT_DIR
import os
import pandas as pd
import numpy as np
import re
from git_status import get_repo_list
def get_wiki_status_color(input_text):
if input_text is None or input_text == 'inactive':
result_text = ":heavy_multiplication_x:"
else:
result_text = ":heavy_chec... | from conf import PROJECT_ROOT_DIR
import os
import pandas as pd
import numpy as np
import re
from git_status import get_repo_list
def get_wiki_status_color(input_text):
if input_text is None or input_text == 'inactive':
result_text = ":heavy_multiplication_x:"
else:
result_text = ":heavy_chec... | |
35,849 | /home/hieuvd/dung_repo/raw/stars_02/fundamentalvision_Deformable-DETR/Deformable-DETR | /home/hieuvd/dung_repo/raw/stars_02/fundamentalvision_Deformable-DETR/Deformable-DETR/datasets/panoptic_eval.py | 31,32 | 21,53 | update | PanopticEvaluator | 32,38 | 32,38 | class PanopticEvaluator(object):
def __init__(self, ann_file, ann_folder, output_dir="panoptic_eval"):
self.gt_json = ann_file
self.gt_folder = ann_folder
if utils.is_main_process():
if not os.path.exists(output_dir):
os.mkdir(output_dir)
self.output_dir =... | class PanopticEvaluator(object):
def __init__(self, ann_file, ann_folder, output_dir="panoptic_eval"):
self.gt_json = ann_file
self.gt_folder = ann_folder
if utils.is_main_process():
if not os.path.exists(output_dir):
os.mkdir(output_dir)
self.output_dir =... | for p in predictions:
with open(os.path.join(self.output_dir, p["file_name"]), "wb") as f:
f.write(p.pop("png_string"))
self.predictions += predictions
| for p in predictions:
with open(os.path.join(self.output_dir, p["file_name"]), "wb") as f:
f.write(p.pop("png_string"))
self.predictions += predictions
| 14 | 340 | 68 | 408 | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... |
35,854 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/abc.py | 51,52 | 35,60 | freeze | AbstractRouter | 53,55 | 52,55 | class AbstractRouter(ABC):
def __init__(self) -> None:
self._frozen = False
def post_init(self, app: Application) -> None:
"""Post init stage.
Not an abstract method for sake of backward compatibility,
but if the router wants to be aware of the application
it can overri... | class AbstractRouter(ABC):
def __init__(self) -> None:
self._frozen = False
def post_init(self, app: Application) -> None:
"""Post init stage.
Not an abstract method for sake of backward compatibility,
but if the router wants to be aware of the application
it can overri... | self._frozen = True
| """Freeze router."""
self._frozen = True
| 3 | 183 | 12 | 195 | import asyncio
import logging
from abc import ABC, abstractmethod
from collections.abc import Sized
from http.cookies import BaseCookie, Morsel
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
)
from multidict import... | import asyncio
import logging
from abc import ABC, abstractmethod
from collections.abc import Sized
from http.cookies import BaseCookie, Morsel
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
)
from multidict import... |
35,855 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/abc.py | 110,112 | 104,120 | request | AbstractView | 113,115 | 112,115 | class AbstractView(ABC):
"""Abstract class based view."""
def __init__(self, request: Request) -> None:
self._request = request
@property
def request(self) -> Request:
FILL_FUNC_BODY @abstractmethod
def __await__(self) -> Generator[Any, None, StreamResponse]:
"""Execute the view... | class AbstractView(ABC):
"""Abstract class based view."""
def __init__(self, request: Request) -> None:
self._request = request
@property
def request(self) -> Request:
"""Request instance."""
FILL_FUNC_BODY @abstractmethod
def __await__(self) -> Generator[Any, None, StreamRespon... | return self._request
| """Request instance."""
return self._request
| 2 | 109 | 9 | 118 | import asyncio
import logging
from abc import ABC, abstractmethod
from collections.abc import Sized
from http.cookies import BaseCookie, Morsel
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
)
from multidict import... | import asyncio
import logging
from abc import ABC, abstractmethod
from collections.abc import Sized
from http.cookies import BaseCookie, Morsel
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
)
from multidict import... |
35,856 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/base_protocol.py | 65,66 | 7,91 | connection_lost | BaseProtocol | 66,81 | 66,81 | class BaseProtocol(asyncio.Protocol):
__slots__ = (
"_loop",
"_paused",
"_drain_waiter",
"_connection_lost",
"_reading_paused",
"transport",
)
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop: asyncio.AbstractEventLoop = loop
... | class BaseProtocol(asyncio.Protocol):
__slots__ = (
"_loop",
"_paused",
"_drain_waiter",
"_connection_lost",
"_reading_paused",
"transport",
)
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop: asyncio.AbstractEventLoop = loop
... | # Wake up the writer if currently paused.
self.transport = None
if not self._paused:
return
waiter = self._drain_waiter
if waiter is None:
return
self._drain_waiter = None
if waiter.done():
return
if exc is None:
... | # Wake up the writer if currently paused.
self.transport = None
if not self._paused:
return
waiter = self._drain_waiter
if waiter is None:
return
self._drain_waiter = None
if waiter.done():
return
if exc is None:
... | 36 | 640 | 125 | 765 | import asyncio
from typing import Optional, cast
from .tcp_helpers import tcp_nodelay
class BaseProtocol(asyncio.Protocol):
__slots__ = (
"_loop",
"_paused",
"_drain_waiter",
"_connection_lost",
"_reading_paused",
"transport",
)
def __init__(self, loop: as... | import asyncio
from typing import Optional, cast
from .tcp_helpers import tcp_nodelay
class BaseProtocol(asyncio.Protocol):
__slots__ = (
"_loop",
"_paused",
"_drain_waiter",
"_connection_lost",
"_reading_paused",
"transport",
)
def __init__(self, loop: as... |
35,859 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/client.py | 1127,1128 | 1117,1145 | throw | _BaseRequestContextManager | 1128,1130 | 1128,1130 | class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]):
__slots__ = ("_coro", "_resp")
def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None:
self._coro = coro
def send(self, arg: None) -> "asyncio.Future[Any]":
return self._coro.se... | class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]):
__slots__ = ("_coro", "_resp")
def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None:
self._coro = coro
def send(self, arg: None) -> "asyncio.Future[Any]":
return self._coro.se... | self._coro.throw(arg)
| self._coro.throw(arg)
| 1 | 290 | 14 | 304 | """HTTP Client for asyncio."""
import asyncio
import base64
import hashlib
import json
import os
import sys
import traceback
import warnings
from contextlib import suppress
from types import SimpleNamespace, TracebackType
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
FrozenSet,
Gene... | """HTTP Client for asyncio."""
import asyncio
import base64
import hashlib
import json
import os
import sys
import traceback
import warnings
from contextlib import suppress
from types import SimpleNamespace, TracebackType
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
FrozenSet,
Gene... |
35,860 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/client_exceptions.py | 329,331 | 311,343 | port | ClientConnectorCertificateError | 331,333 | 331,333 | class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc]
"""Response certificate error."""
def __init__(
self, connection_key: ConnectionKey, certificate_error: Exception
) -> None:
self._conn_key = connection_key
self._certificate_error = certificate_error
... | class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc]
"""Response certificate error."""
def __init__(
self, connection_key: ConnectionKey, certificate_error: Exception
) -> None:
self._conn_key = connection_key
self._certificate_error = certificate_error
... | return self._conn_key.port
| return self._conn_key.port
| 2 | 291 | 13 | 304 | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... |
35,861 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/client_exceptions.py | 166,168 | 153,191 | os_error | ClientConnectorError | 168,170 | 168,170 | class ClientConnectorError(ClientOSError):
"""Client connector error.
Raised in :class:`aiohttp.connector.TCPConnector` if
a connection can not be established.
"""
def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None:
self._conn_key = connection_key
self... | class ClientConnectorError(ClientOSError):
"""Client connector error.
Raised in :class:`aiohttp.connector.TCPConnector` if
a connection can not be established.
"""
def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None:
self._conn_key = connection_key
self... | return self._os_error
| return self._os_error
| 2 | 366 | 11 | 377 | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... |
35,862 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/client_exceptions.py | 114,116 | 49,124 | code | ClientResponseError | 116,124 | 116,124 | class ClientResponseError(ClientError):
"""Connection error during reading response.
request_info: instance of RequestInfo
"""
def __init__(
self,
request_info: RequestInfo,
history: Tuple[ClientResponse, ...],
*,
code: Optional[int] = None,
status: Opti... | class ClientResponseError(ClientError):
"""Connection error during reading response.
request_info: instance of RequestInfo
"""
def __init__(
self,
request_info: RequestInfo,
history: Tuple[ClientResponse, ...],
*,
code: Optional[int] = None,
status: Opti... | warnings.warn(
"code property is deprecated, use status instead",
DeprecationWarning,
stacklevel=2,
)
self.status = value
| warnings.warn(
"code property is deprecated, use status instead",
DeprecationWarning,
stacklevel=2,
)
self.status = value
| 14 | 569 | 53 | 622 | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... |
35,863 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/client_exceptions.py | 275,277 | 261,283 | url | InvalidURL | 277,279 | 277,279 | class InvalidURL(ClientError, ValueError):
"""Invalid URL.
URL used for fetching is malformed, e.g. it doesn't contains host
part.
"""
# Derive from ValueError for backward compatibility
def __init__(self, url: Any) -> None:
# The type of url is not yarl.URL because the exception can ... | class InvalidURL(ClientError, ValueError):
"""Invalid URL.
URL used for fetching is malformed, e.g. it doesn't contains host
part.
"""
# Derive from ValueError for backward compatibility
def __init__(self, url: Any) -> None:
# The type of url is not yarl.URL because the exception can ... | return self.args[0]
| return self.args[0]
| 2 | 175 | 12 | 187 | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... |
35,864 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/client_exceptions.py | 212,214 | 199,222 | path | UnixClientConnectorError | 214,216 | 214,216 | class UnixClientConnectorError(ClientConnectorError):
"""Unix connector error.
Raised in :py:class:`aiohttp.connector.UnixConnector`
if connection to unix socket can not be established.
"""
def __init__(
self, path: str, connection_key: ConnectionKey, os_error: OSError
) -> None:
... | class UnixClientConnectorError(ClientConnectorError):
"""Unix connector error.
Raised in :py:class:`aiohttp.connector.UnixConnector`
if connection to unix socket can not be established.
"""
def __init__(
self, path: str, connection_key: ConnectionKey, os_error: OSError
) -> None:
... | return self._path
| return self._path
| 2 | 214 | 9 | 223 | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... | """HTTP related errors."""
import asyncio
import warnings
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from .http_parser import RawResponseMessage
from .typedefs import LooseHeaders
try:
import ssl
SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = No... |
35,868 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/connector.py | 183,185 | 98,188 | closed | Connection | 185,188 | 185,188 | class Connection:
_source_traceback = None
_transport = None
def __init__(
self,
connector: "BaseConnector",
key: "ConnectionKey",
protocol: ResponseHandler,
loop: asyncio.AbstractEventLoop,
) -> None:
self._key = key
self._connector = connector
... | class Connection:
_source_traceback = None
_transport = None
def __init__(
self,
connector: "BaseConnector",
key: "ConnectionKey",
protocol: ResponseHandler,
loop: asyncio.AbstractEventLoop,
) -> None:
self._key = key
self._connector = connector
... | return self._protocol is None or not self._protocol.is_connected()
| return self._protocol is None or not self._protocol.is_connected()
| 7 | 750 | 23 | 773 | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... |
35,869 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/connector.py | 1433,1436 | 1389,1454 | _create_connection | NamedPipeConnector | 1436,1454 | 1436,1454 | class NamedPipeConnector(BaseConnector):
"""Named pipe connector.
Only supported by the proactor event loop.
See also: https://docs.python.org/3.7/library/asyncio-eventloop.html
path - Windows named pipe path.
keepalive_timeout - (optional) Keep-alive timeout.
force_close - Set to True to forc... | class NamedPipeConnector(BaseConnector):
"""Named pipe connector.
Only supported by the proactor event loop.
See also: https://docs.python.org/3.7/library/asyncio-eventloop.html
path - Windows named pipe path.
keepalive_timeout - (optional) Keep-alive timeout.
force_close - Set to True to forc... | try:
async with ceil_timeout(timeout.sock_connect):
_, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined] # noqa: E501
self._factory, self._path
)
# the drain is required so that the connection_made is ca... | try:
async with ceil_timeout(timeout.sock_connect):
_, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined] # noqa: E501
self._factory, self._path
)
# the drain is required so that the connection_made is ca... | 87 | 453 | 231 | 684 | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... |
35,871 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/connector.py | 1373,1376 | 1338,1389 | _create_connection | UnixConnector | 1376,1389 | 1376,1389 | class UnixConnector(BaseConnector):
"""Unix socket connector.
path - Unix socket path.
keepalive_timeout - (optional) Keep-alive timeout.
force_close - Set to True to force close and do reconnect
after each request (and between redirects).
limit - The total number of simultaneous connection... | class UnixConnector(BaseConnector):
"""Unix socket connector.
path - Unix socket path.
keepalive_timeout - (optional) Keep-alive timeout.
force_close - Set to True to force close and do reconnect
after each request (and between redirects).
limit - The total number of simultaneous connection... | try:
async with ceil_timeout(timeout.sock_connect):
_, proto = await self._loop.create_unix_connection(
self._factory, self._path
)
except OSError as exc:
if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
... | try:
async with ceil_timeout(timeout.sock_connect):
_, proto = await self._loop.create_unix_connection(
self._factory, self._path
)
except OSError as exc:
if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
... | 33 | 354 | 132 | 486 | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... |
35,872 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/connector.py | 709,710 | 684,723 | next_addrs | _DNSCacheTable | 710,716 | 710,716 | class _DNSCacheTable:
def __init__(self, ttl: Optional[float] = None) -> None:
self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] = {}
self._timestamps: Dict[Tuple[str, int], float] = {}
self._ttl = ttl
def __contains__(self, host: object) -> bool:
retur... | class _DNSCacheTable:
def __init__(self, ttl: Optional[float] = None) -> None:
self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] = {}
self._timestamps: Dict[Tuple[str, int], float] = {}
self._ttl = ttl
def __contains__(self, host: object) -> bool:
retur... | loop, length = self._addrs_rr[key]
addrs = list(islice(loop, length))
# Consume one more element to shift internal state of `cycle`
next(loop)
return addrs
| loop, length = self._addrs_rr[key]
addrs = list(islice(loop, length))
# Consume one more element to shift internal state of `cycle`
next(loop)
return addrs
| 22 | 397 | 63 | 460 | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... | import asyncio
import functools
import random
import sys
import traceback
import warnings
from collections import defaultdict, deque
from contextlib import suppress
from http.cookies import SimpleCookie
from itertools import cycle, islice
from time import monotonic
from types import TracebackType
from typing import (
... |
35,874 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/cookiejar.py | 414,415 | 388,416 | filter_cookies | DummyCookieJar | 415,416 | 415,416 | class DummyCookieJar(AbstractCookieJar):
"""Implements a dummy cookie storage.
It can be used with the ClientSession when no cookie processing is needed.
"""
def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
super().__init__(loop=loop)
def __iter__(self) ->... | class DummyCookieJar(AbstractCookieJar):
"""Implements a dummy cookie storage.
It can be used with the ClientSession when no cookie processing is needed.
"""
def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
super().__init__(loop=loop)
def __iter__(self) ->... | return SimpleCookie()
| return SimpleCookie()
| 2 | 255 | 8 | 263 | import asyncio
import contextlib
import datetime
import os # noqa
import pathlib
import pickle
import re
from collections import defaultdict
from http.cookies import BaseCookie, Morsel, SimpleCookie
from typing import ( # noqa
DefaultDict,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,... | import asyncio
import contextlib
import datetime
import os # noqa
import pathlib
import pickle
import re
from collections import defaultdict
from http.cookies import BaseCookie, Morsel, SimpleCookie
from typing import ( # noqa
DefaultDict,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,... |
35,875 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/formdata.py | 43,52 | 14,173 | add_field | FormData | 52,89 | 52,89 | class FormData:
"""Helper class for form body generation.
Supports multipart/form-data and application/x-www-form-urlencoded.
"""
def __init__(
self,
fields: Iterable[Any] = (),
quote_fields: bool = True,
charset: Optional[str] = None,
) -> None:
self._write... | class FormData:
"""Helper class for form body generation.
Supports multipart/form-data and application/x-www-form-urlencoded.
"""
def __init__(
self,
fields: Iterable[Any] = (),
quote_fields: bool = True,
charset: Optional[str] = None,
) -> None:
self._write... |
if isinstance(value, io.IOBase):
self._is_multipart = True
elif isinstance(value, (bytes, bytearray, memoryview)):
if filename is None and content_transfer_encoding is None:
filename = name
type_options: MultiDict[str] = MultiDict({"name": name})
... |
if isinstance(value, io.IOBase):
self._is_multipart = True
elif isinstance(value, (bytes, bytearray, memoryview)):
if filename is None and content_transfer_encoding is None:
filename = name
type_options: MultiDict[str] = MultiDict({"name": name})
... | 139 | 1,197 | 439 | 1,636 | import io
from typing import Any, Iterable, List, Optional
from urllib.parse import urlencode
from multidict import MultiDict, MultiDictProxy
from . import hdrs, multipart, payload
from .helpers import guess_filename
from .payload import Payload
__all__ = ("FormData",)
class FormData:
"""Helper class for form ... | import io
from typing import Any, Iterable, List, Optional
from urllib.parse import urlencode
from multidict import MultiDict, MultiDictProxy
from . import hdrs, multipart, payload
from .helpers import guess_filename
from .payload import Payload
__all__ = ("FormData",)
class FormData:
"""Helper class for form ... |
35,876 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_parser.py | 885,886 | 878,895 | decompress | BrotliDecoder | 886,890 | 886,890 | class BrotliDecoder:
# Supports both 'brotlipy' and 'Brotli' packages
# since they share an import name. The top branches
# are for 'brotlipy' and bottom branches for 'Brotli'
def __init__(self) -> None:
self._obj = brotli.D... | class BrotliDecoder:
# Supports both 'brotlipy' and 'Brotli' packages
# since they share an import name. The top branches
# are for 'brotlipy' and bottom branches for 'Brotli'
def __init__(self) -> None:
self._obj = brotli.D... | if hasattr(self._obj, "decompress"):
return cast(bytes, self._obj.decompress(data))
return cast(bytes, self._obj.process(data))
| if hasattr(self._obj, "decompress"):
return cast(bytes, self._obj.decompress(data))
return cast(bytes, self._obj.process(data))
| 9 | 159 | 53 | 212 | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... |
35,877 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_parser.py | 943,944 | 860,950 | begin_http_chunk_receiving | DeflateBuffer | 944,946 | 944,946 | class DeflateBuffer:
"""DeflateStream decompress stream and feed data into specified stream."""
decompressor: Any
def __init__(self, out: StreamReader, encoding: Optional[str]) -> None:
self.out = out
self.size = 0
self.encoding = encoding
self._started_decoding = False
... | class DeflateBuffer:
"""DeflateStream decompress stream and feed data into specified stream."""
decompressor: Any
def __init__(self, out: StreamReader, encoding: Optional[str]) -> None:
self.out = out
self.size = 0
self.encoding = encoding
self._started_decoding = False
... | self.out.begin_http_chunk_receiving()
| self.out.begin_http_chunk_receiving()
| 1 | 925 | 20 | 945 | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... |
35,878 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_parser.py | 134,137 | 123,217 | parse_headers | HeadersParser | 137,217 | 137,217 | class HeadersParser:
def __init__(
self,
max_line_size: int = 8190,
max_headers: int = 32768,
max_field_size: int = 8190,
) -> None:
self.max_line_size = max_line_size
self.max_headers = max_headers
self.max_field_size = max_field_size
def parse_heade... | class HeadersParser:
def __init__(
self,
max_line_size: int = 8190,
max_headers: int = 32768,
max_field_size: int = 8190,
) -> None:
self.max_line_size = max_line_size
self.max_headers = max_headers
self.max_field_size = max_field_size
def parse_heade... | headers: CIMultiDict[str] = CIMultiDict()
raw_headers = []
lines_idx = 1
line = lines[1]
line_count = len(lines)
while line:
# Parse initial header name : value pair.
try:
bname, bvalue = line.split(b":", 1)
except Val... | headers: CIMultiDict[str] = CIMultiDict()
raw_headers = []
lines_idx = 1
line = lines[1]
line_count = len(lines)
while line:
# Parse initial header name : value pair.
try:
bname, bvalue = line.split(b":", 1)
except Val... | 188 | 158 | 775 | 933 | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... |
35,881 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_parser.py | 522,523 | 514,604 | parse_message | HttpRequestParser | 523,604 | 523,604 | class HttpRequestParser(HttpParser[RawRequestMessage]):
"""Read request status line.
Exception .http_exceptions.BadStatusLine
could be raised in case of any errors in status line.
Returns RawRequestMessage.
"""
def parse_message(self, lines: List[bytes]) -> RawRequestMessage:
FILL_FUNC_BODY | class HttpRequestParser(HttpParser[RawRequestMessage]):
"""Read request status line.
Exception .http_exceptions.BadStatusLine
could be raised in case of any errors in status line.
Returns RawRequestMessage.
"""
def parse_message(self, lines: List[bytes]) -> RawRequestMessage:
FILL_FUNC_BODY | # request line
line = lines[0].decode("utf-8", "surrogateescape")
try:
method, path, version = line.split(None, 2)
except ValueError:
raise BadStatusLine(line) from None
if len(path) > self.max_line_size:
raise LineTooLong(
"St... | # request line
line = lines[0].decode("utf-8", "surrogateescape")
try:
method, path, version = line.split(None, 2)
except ValueError:
raise BadStatusLine(line) from None
if len(path) > self.max_line_size:
raise LineTooLong(
"St... | 206 | 91 | 821 | 912 | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... |
35,882 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_parser.py | 611,612 | 604,669 | parse_message | HttpResponseParser | 612,669 | 612,669 | class HttpResponseParser(HttpParser[RawResponseMessage]):
"""Read response status line and headers.
BadStatusLine could be raised in case of any errors in status line.
Returns RawResponseMessage.
"""
def parse_message(self, lines: List[bytes]) -> RawResponseMessage:
FILL_FUNC_BODY | class HttpResponseParser(HttpParser[RawResponseMessage]):
"""Read response status line and headers.
BadStatusLine could be raised in case of any errors in status line.
Returns RawResponseMessage.
"""
def parse_message(self, lines: List[bytes]) -> RawResponseMessage:
FILL_FUNC_BODY | line = lines[0].decode("utf-8", "surrogateescape")
try:
version, status = line.split(None, 1)
except ValueError:
raise BadStatusLine(line) from None
try:
status, reason = status.split(None, 1)
except ValueError:
reason = ""
... | line = lines[0].decode("utf-8", "surrogateescape")
try:
version, status = line.split(None, 1)
except ValueError:
raise BadStatusLine(line) from None
try:
status, reason = status.split(None, 1)
except ValueError:
reason = ""
... | 114 | 84 | 447 | 531 | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... | import abc
import asyncio
import collections
import re
import string
import zlib
from contextlib import suppress
from enum import IntEnum
from typing import (
Any,
Generic,
List,
NamedTuple,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from multidict impo... |
35,883 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_writer.py | 183,184 | 1,199 | _py_serialize_headers | 184,189 | 184,189 | """Http related parsers and protocol."""
import asyncio
import zlib
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
from multidict import CIMultiDict
from .abc import AbstractStreamWriter
from .base_protocol import BaseProtocol
from .helpers import NO_EXTENSIONS
__all__ = ("StreamWr... | """Http related parsers and protocol."""
import asyncio
import zlib
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
from multidict import CIMultiDict
from .abc import AbstractStreamWriter
from .base_protocol import BaseProtocol
from .helpers import NO_EXTENSIONS
__all__ = ("StreamWr... | headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items())
line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n"
return line.encode("utf-8")
| headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items())
line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n"
return line.encode("utf-8")
| 24 | 1,777 | 87 | 1,864 | """Http related parsers and protocol."""
import asyncio
import zlib
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
from multidict import CIMultiDict
from .abc import AbstractStreamWriter
from .base_protocol import BaseProtocol
from .helpers import NO_EXTENSIONS
__all__ = ("StreamWr... | """Http related parsers and protocol."""
import asyncio
import zlib
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
from multidict import CIMultiDict
from .abc import AbstractStreamWriter
from .base_protocol import BaseProtocol
from .helpers import NO_EXTENSIONS
__all__ = ("StreamWr... | |
35,884 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/http_writer.py | 78,81 | 29,174 | write | StreamWriter | 87,121 | 81,121 | class StreamWriter(AbstractStreamWriter):
def __init__(
self,
protocol: BaseProtocol,
loop: asyncio.AbstractEventLoop,
on_chunk_sent: _T_OnChunkSent = None,
on_headers_sent: _T_OnHeadersSent = None,
) -> None:
self._protocol = protocol
self.loop = loop
... | class StreamWriter(AbstractStreamWriter):
def __init__(
self,
protocol: BaseProtocol,
loop: asyncio.AbstractEventLoop,
on_chunk_sent: _T_OnChunkSent = None,
on_headers_sent: _T_OnHeadersSent = None,
) -> None:
self._protocol = protocol
self.loop = loop
... | if self._on_chunk_sent is not None:
await self._on_chunk_sent(chunk)
if isinstance(chunk, memoryview):
if chunk.nbytes != len(chunk):
# just reshape it
chunk = chunk.cast("c")
if self._compress is not None:
chunk = self._compr... | """Writes chunk of data to a stream.
write_eof() indicates end of stream.
writer can't be used after write_eof() method being called.
write() return drain future.
"""
if self._on_chunk_sent is not None:
await self._on_chunk_sent(chunk)
if isinstance(... | 90 | 1,067 | 325 | 1,392 | """Http related parsers and protocol."""
import asyncio
import zlib
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
from multidict import CIMultiDict
from .abc import AbstractStreamWriter
from .base_protocol import BaseProtocol
from .helpers import NO_EXTENSIONS
__all__ = ("StreamWr... | """Http related parsers and protocol."""
import asyncio
import zlib
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
from multidict import CIMultiDict
from .abc import AbstractStreamWriter
from .base_protocol import BaseProtocol
from .helpers import NO_EXTENSIONS
__all__ = ("StreamWr... |
35,885 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/locks.py | 25,26 | 6,42 | wait | EventResultOrError | 26,38 | 26,38 | class EventResultOrError:
"""Event asyncio lock helper class.
Wraps the Event asyncio lock allowing either to awake the
locked Tasks without any error or raising an exception.
thanks to @vorpalsmith for the simple design.
"""
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
... | class EventResultOrError:
"""Event asyncio lock helper class.
Wraps the Event asyncio lock allowing either to awake the
locked Tasks without any error or raising an exception.
thanks to @vorpalsmith for the simple design.
"""
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
... | waiter = self._loop.create_task(self._event.wait())
self._waiters.append(waiter)
try:
val = await waiter
finally:
self._waiters.remove(waiter)
if self._exc is not None:
raise self._exc
return val
| waiter = self._loop.create_task(self._event.wait())
self._waiters.append(waiter)
try:
val = await waiter
finally:
self._waiters.remove(waiter)
if self._exc is not None:
raise self._exc
return val
| 20 | 239 | 93 | 332 | import asyncio
import collections
from typing import Any, Deque, Optional
class EventResultOrError:
"""Event asyncio lock helper class.
Wraps the Event asyncio lock allowing either to awake the
locked Tasks without any error or raising an exception.
thanks to @vorpalsmith for the simple design.
... | import asyncio
import collections
from typing import Any, Deque, Optional
class EventResultOrError:
"""Event asyncio lock helper class.
Wraps the Event asyncio lock allowing either to awake the
locked Tasks without any error or raising an exception.
thanks to @vorpalsmith for the simple design.
... |
35,887 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 437,438 | 418,449 | write | AsyncIterablePayload | 438,449 | 438,449 | class AsyncIterablePayload(Payload):
_iter: Optional[_AsyncIterator] = None
def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None:
if not isinstance(value, AsyncIterable):
raise TypeError(
"value argument must support "
"collections.ab... | class AsyncIterablePayload(Payload):
_iter: Optional[_AsyncIterator] = None
def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None:
if not isinstance(value, AsyncIterable):
raise TypeError(
"value argument must support "
"collections.ab... | if self._iter:
try:
# iter is not None check prevents rare cases
# when the case iterable is used twice
while True:
chunk = await self._iter.__anext__()
await writer.write(chunk)
except StopAsyncItera... | if self._iter:
try:
# iter is not None check prevents rare cases
# when the case iterable is used twice
while True:
chunk = await self._iter.__anext__()
await writer.write(chunk)
except StopAsyncItera... | 33 | 209 | 89 | 298 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,888 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 376,378 | 375,386 | size | BufferedReaderPayload | 378,386 | 378,386 | class BufferedReaderPayload(IOBasePayload):
@property
def size(self) -> Optional[int]:
FILL_FUNC_BODY | class BufferedReaderPayload(IOBasePayload):
@property
def size(self) -> Optional[int]:
FILL_FUNC_BODY | try:
return os.fstat(self._value.fileno()).st_size - self._value.tell()
except OSError:
# data.fileno() is not supported, e.g.
# io.BufferedReader(io.BytesIO(b'data'))
return None
| try:
return os.fstat(self._value.fileno()).st_size - self._value.tell()
except OSError:
# data.fileno() is not supported, e.g.
# io.BufferedReader(io.BytesIO(b'data'))
return None
| 17 | 40 | 84 | 124 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,889 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 367,369 | 366,375 | size | BytesIOPayload | 369,375 | 369,375 | class BytesIOPayload(IOBasePayload):
@property
def size(self) -> int:
FILL_FUNC_BODY | class BytesIOPayload(IOBasePayload):
@property
def size(self) -> int:
FILL_FUNC_BODY | position = self._value.tell()
end = self._value.seek(0, os.SEEK_END)
self._value.seek(position)
return end - position
| position = self._value.tell()
end = self._value.seek(0, os.SEEK_END)
self._value.seek(position)
return end - position
| 12 | 39 | 53 | 92 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,890 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 246,247 | 218,250 | write | BytesPayload | 247,250 | 247,250 | class BytesPayload(Payload):
def __init__(self, value: ByteString, *args: Any, **kwargs: Any) -> None:
if not isinstance(value, (bytes, bytearray, memoryview)):
raise TypeError(f"value argument must be byte-ish, not {type(value)!r}")
if "content_type" not in kwargs:
kwargs["... | class BytesPayload(Payload):
def __init__(self, value: ByteString, *args: Any, **kwargs: Any) -> None:
if not isinstance(value, (bytes, bytearray, memoryview)):
raise TypeError(f"value argument must be byte-ish, not {type(value)!r}")
if "content_type" not in kwargs:
kwargs["... | await writer.write(self._value)
| await writer.write(self._value)
| 2 | 307 | 16 | 323 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,891 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 301,302 | 286,312 | write | IOBasePayload | 302,312 | 302,312 | class IOBasePayload(Payload):
_value: IO[Any]
def __init__(
self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any
) -> None:
if "filename" not in kwargs:
kwargs["filename"] = guess_filename(value)
super().__init__(value, *args, **kwargs)
... | class IOBasePayload(Payload):
_value: IO[Any]
def __init__(
self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any
) -> None:
if "filename" not in kwargs:
kwargs["filename"] = guess_filename(value)
super().__init__(value, *args, **kwargs)
... | loop = asyncio.get_event_loop()
try:
chunk = await loop.run_in_executor(None, self._value.read, 2**16)
while chunk:
await writer.write(chunk)
chunk = await loop.run_in_executor(None, self._value.read, 2**16)
finally:
await loop.... | loop = asyncio.get_event_loop()
try:
chunk = await loop.run_in_executor(None, self._value.read, 2**16)
while chunk:
await writer.write(chunk)
chunk = await loop.run_in_executor(None, self._value.read, 2**16)
finally:
await loop.... | 24 | 187 | 124 | 311 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,892 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 179,181 | 133,218 | _binary_headers | Payload | 181,188 | 181,188 | class Payload(ABC):
_default_content_type: str = "application/octet-stream"
_size: Optional[int] = None
def __init__(
self,
value: Any,
headers: Optional[
Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]]
] = None,
content_type: Optional[str... | class Payload(ABC):
_default_content_type: str = "application/octet-stream"
_size: Optional[int] = None
def __init__(
self,
value: Any,
headers: Optional[
Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]]
] = None,
content_type: Optional[str... | return (
"".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode(
"utf-8"
)
+ b"\r\n"
)
| return (
"".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode(
"utf-8"
)
+ b"\r\n"
)
| 20 | 706 | 69 | 775 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,893 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 120,123 | 94,133 | register | PayloadRegistry | 123,133 | 123,133 | class PayloadRegistry:
"""Payload registry.
note: we need zope.interface for more efficient adapter search
"""
def __init__(self) -> None:
self._first: List[_PayloadRegistryItem] = []
self._normal: List[_PayloadRegistryItem] = []
self._last: List[_PayloadRegistryItem] = []
... | class PayloadRegistry:
"""Payload registry.
note: we need zope.interface for more efficient adapter search
"""
def __init__(self) -> None:
self._first: List[_PayloadRegistryItem] = []
self._normal: List[_PayloadRegistryItem] = []
self._last: List[_PayloadRegistryItem] = []
... | if order is Order.try_first:
self._first.append((factory, type))
elif order is Order.normal:
self._normal.append((factory, type))
elif order is Order.try_last:
self._last.append((factory, type))
else:
raise ValueError(f"Unsupported order {o... | if order is Order.try_first:
self._first.append((factory, type))
elif order is Order.normal:
self._normal.append((factory, type))
elif order is Order.try_last:
self._last.append((factory, type))
else:
raise ValueError(f"Unsupported order {o... | 23 | 268 | 100 | 368 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,894 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload.py | 343,345 | 312,366 | size | TextIOPayload | 345,350 | 345,350 | class TextIOPayload(IOBasePayload):
_value: TextIO
def __init__(
self,
value: TextIO,
*args: Any,
encoding: Optional[str] = None,
content_type: Optional[str] = None,
**kwargs: Any,
) -> None:
if encoding is None:
if content_type is None:
... | class TextIOPayload(IOBasePayload):
_value: TextIO
def __init__(
self,
value: TextIO,
*args: Any,
encoding: Optional[str] = None,
content_type: Optional[str] = None,
**kwargs: Any,
) -> None:
if encoding is None:
if content_type is None:
... | try:
return os.fstat(self._value.fileno()).st_size - self._value.tell()
except OSError:
return None
| try:
return os.fstat(self._value.fileno()).st_size - self._value.tell()
except OSError:
return None
| 9 | 430 | 46 | 476 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... |
35,895 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload_streamer.py | 74,75 | 69,76 | write | StreamPayload | 75,76 | 75,76 | @payload_type(streamer)
class StreamPayload(StreamWrapperPayload):
def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None:
super().__init__(value(), *args, **kwargs)
async def write(self, writer: AbstractStreamWriter) -> None:
FILL_FUNC_BODY | @payload_type(streamer)
class StreamPayload(StreamWrapperPayload):
def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None:
super().__init__(value(), *args, **kwargs)
async def write(self, writer: AbstractStreamWriter) -> None:
FILL_FUNC_BODY | await self._value(writer)
| await self._value(writer)
| 2 | 91 | 10 | 101 | """
Payload implemenation for coroutines as data provider.
As a simple case, you can upload data from file::
@aiohttp.streamer
async def file_sender(writer, file_name=None):
with open(file_name, 'rb') as f:
chunk = f.read(2**16)
while chunk:
await writer.write(chunk)
... | """
Payload implemenation for coroutines as data provider.
As a simple case, you can upload data from file::
@aiohttp.streamer
async def file_sender(writer, file_name=None):
with open(file_name, 'rb') as f:
chunk = f.read(2**16)
while chunk:
await writer.write(chunk)
... |
35,896 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/payload_streamer.py | 65,66 | 63,69 | write | StreamWrapperPayload | 66,69 | 66,69 | @payload_type(_stream_wrapper)
class StreamWrapperPayload(Payload):
async def write(self, writer: AbstractStreamWriter) -> None:
FILL_FUNC_BODY | @payload_type(_stream_wrapper)
class StreamWrapperPayload(Payload):
async def write(self, writer: AbstractStreamWriter) -> None:
FILL_FUNC_BODY | await self._value(writer)
| await self._value(writer)
| 2 | 49 | 14 | 63 | """
Payload implemenation for coroutines as data provider.
As a simple case, you can upload data from file::
@aiohttp.streamer
async def file_sender(writer, file_name=None):
with open(file_name, 'rb') as f:
chunk = f.read(2**16)
while chunk:
await writer.write(chunk)
... | """
Payload implemenation for coroutines as data provider.
As a simple case, you can upload data from file::
@aiohttp.streamer
async def file_sender(writer, file_name=None):
with open(file_name, 'rb') as f:
chunk = f.read(2**16)
while chunk:
await writer.write(chunk)
... |
35,897 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/resolver.py | 123,126 | 78,159 | _resolve_with_query | AsyncResolver | 126,155 | 126,155 | class AsyncResolver(AbstractResolver):
"""Use the `aiodns` package to make asynchronous DNS lookups"""
def __init__(
self,
loop: Optional[asyncio.AbstractEventLoop] = None,
*args: Any,
**kwargs: Any
) -> None:
if aiodns is None:
raise RuntimeError("Resolv... | class AsyncResolver(AbstractResolver):
"""Use the `aiodns` package to make asynchronous DNS lookups"""
def __init__(
self,
loop: Optional[asyncio.AbstractEventLoop] = None,
*args: Any,
**kwargs: Any
) -> None:
if aiodns is None:
raise RuntimeError("Resolv... | if family == socket.AF_INET6:
qtype = "AAAA"
else:
qtype = "A"
try:
resp = await self._resolver.query(host, qtype)
except aiodns.error.DNSError as exc:
msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed"
raise OSEr... | if family == socket.AF_INET6:
qtype = "AAAA"
else:
qtype = "A"
try:
resp = await self._resolver.query(host, qtype)
except aiodns.error.DNSError as exc:
msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed"
raise OSEr... | 68 | 517 | 246 | 763 | import asyncio
import socket
from typing import Any, Dict, List, Optional, Type, Union
from .abc import AbstractResolver
from .helpers import get_running_loop
__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver")
try:
import aiodns
# aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname')... | import asyncio
import socket
from typing import Any, Dict, List, Optional, Type, Union
from .abc import AbstractResolver
from .helpers import get_running_loop
__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver")
try:
import aiodns
# aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.