blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d9e0903ddfb93cb6f14dddbc29e7caf7a97d75c | [
"self.input_path = input_path\nself.output_path = output_path\npass",
"term = Terms(equation)\nprint('equation ', equation)\nterm.parse_equation(equation)\nterm.d_dx_as_terms()\nresult = term.print_equation()\nreturn result",
"term = Terms(equation)\nterm.parse_equation(equation)\nterm.integral_as_terms(constan... | <|body_start_0|>
self.input_path = input_path
self.output_path = output_path
pass
<|end_body_0|>
<|body_start_1|>
term = Terms(equation)
print('equation ', equation)
term.parse_equation(equation)
term.d_dx_as_terms()
result = term.print_equation()
... | WolframBeta | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WolframBeta:
def __init__(self, input_path, output_path):
""":param input_path: path of input query file :param output_path: path of output file storing result generated by wolfram beta"""
<|body_0|>
def d_dx(equation):
""":param equation: str :return: equation str (... | stack_v2_sparse_classes_36k_train_022100 | 11,178 | no_license | [
{
"docstring": ":param input_path: path of input query file :param output_path: path of output file storing result generated by wolfram beta",
"name": "__init__",
"signature": "def __init__(self, input_path, output_path)"
},
{
"docstring": ":param equation: str :return: equation str (differentia... | 6 | stack_v2_sparse_classes_30k_train_003940 | Implement the Python class `WolframBeta` described below.
Class description:
Implement the WolframBeta class.
Method signatures and docstrings:
- def __init__(self, input_path, output_path): :param input_path: path of input query file :param output_path: path of output file storing result generated by wolfram beta
- ... | Implement the Python class `WolframBeta` described below.
Class description:
Implement the WolframBeta class.
Method signatures and docstrings:
- def __init__(self, input_path, output_path): :param input_path: path of input query file :param output_path: path of output file storing result generated by wolfram beta
- ... | 4d69e7b604fc62760ce428df5826baf0566530cd | <|skeleton|>
class WolframBeta:
def __init__(self, input_path, output_path):
""":param input_path: path of input query file :param output_path: path of output file storing result generated by wolfram beta"""
<|body_0|>
def d_dx(equation):
""":param equation: str :return: equation str (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WolframBeta:
def __init__(self, input_path, output_path):
""":param input_path: path of input query file :param output_path: path of output file storing result generated by wolfram beta"""
self.input_path = input_path
self.output_path = output_path
pass
def d_dx(equation):... | the_stack_v2_python_sparse | python/2day/wolfram_beta_OO.py | kyongpiltae/seoul | train | 0 | |
6fd1dbbaca8dc84007b0cecde498aff826d53f26 | [
"m, _ = torch.max(input, dim=1, keepdim=True)\ny = input - m\ny = torch.exp(y)\ny_cumsum_t2h = torch.flip(torch.cumsum(torch.flip(y, dims=[1]), dim=1), dims=[1])\nfd_output = torch.log(y_cumsum_t2h) + m\nctx.save_for_backward(input, fd_output)\nreturn fd_output",
"input, fd_output = ctx.saved_tensors\nbk_output =... | <|body_start_0|>
m, _ = torch.max(input, dim=1, keepdim=True)
y = input - m
y = torch.exp(y)
y_cumsum_t2h = torch.flip(torch.cumsum(torch.flip(y, dims=[1]), dim=1), dims=[1])
fd_output = torch.log(y_cumsum_t2h) + m
ctx.save_for_backward(input, fd_output)
return fd... | LogCumsumExp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogCumsumExp:
def forward(ctx, input):
"""In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context obje... | stack_v2_sparse_classes_36k_train_022101 | 12,276 | permissive | [
{
"docstring": "In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context object that can be used to stash information for backw... | 2 | stack_v2_sparse_classes_30k_train_008209 | Implement the Python class `LogCumsumExp` described below.
Class description:
Implement the LogCumsumExp class.
Method signatures and docstrings:
- def forward(ctx, input): In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use ... | Implement the Python class `LogCumsumExp` described below.
Class description:
Implement the LogCumsumExp class.
Method signatures and docstrings:
- def forward(ctx, input): In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use ... | 4d56d5174c7ce4b15157d112083eb92e57288b04 | <|skeleton|>
class LogCumsumExp:
def forward(ctx, input):
"""In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogCumsumExp:
def forward(ctx, input):
"""In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context object that can be... | the_stack_v2_python_sparse | MultiDCP/models/loss_utils.py | qiaoliuhub/MultiDCP | train | 3 | |
c5f142fcde19f8fd33c2da6104bffa35f1732534 | [
"if not self.has_feature(request, organization):\n return Response(status=404)\nproject = self.get_project(request, organization)\nbase_filter = {'organization': organization, 'owner': request.user}\nwith transaction.atomic():\n serializer = KeyTransactionSerializer(data=request.data, context=base_filter)\n ... | <|body_start_0|>
if not self.has_feature(request, organization):
return Response(status=404)
project = self.get_project(request, organization)
base_filter = {'organization': organization, 'owner': request.user}
with transaction.atomic():
serializer = KeyTransactio... | KeyTransactionEndpoint | [
"BUSL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyTransactionEndpoint:
def post(self, request, organization):
"""Create a Key Transaction"""
<|body_0|>
def delete(self, request, organization):
"""Remove a Key transaction for a user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.has_... | stack_v2_sparse_classes_36k_train_022102 | 3,249 | permissive | [
{
"docstring": "Create a Key Transaction",
"name": "post",
"signature": "def post(self, request, organization)"
},
{
"docstring": "Remove a Key transaction for a user",
"name": "delete",
"signature": "def delete(self, request, organization)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000973 | Implement the Python class `KeyTransactionEndpoint` described below.
Class description:
Implement the KeyTransactionEndpoint class.
Method signatures and docstrings:
- def post(self, request, organization): Create a Key Transaction
- def delete(self, request, organization): Remove a Key transaction for a user | Implement the Python class `KeyTransactionEndpoint` described below.
Class description:
Implement the KeyTransactionEndpoint class.
Method signatures and docstrings:
- def post(self, request, organization): Create a Key Transaction
- def delete(self, request, organization): Remove a Key transaction for a user
<|skel... | 63d698f5294f64a8c206b4c741e2a11be1f9a9be | <|skeleton|>
class KeyTransactionEndpoint:
def post(self, request, organization):
"""Create a Key Transaction"""
<|body_0|>
def delete(self, request, organization):
"""Remove a Key transaction for a user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyTransactionEndpoint:
def post(self, request, organization):
"""Create a Key Transaction"""
if not self.has_feature(request, organization):
return Response(status=404)
project = self.get_project(request, organization)
base_filter = {'organization': organization, '... | the_stack_v2_python_sparse | src/sentry/discover/endpoints/discover_key_transactions.py | kaozdl/sentry | train | 0 | |
a7f26cd5e1f88db004c0695da4a47872837abda0 | [
"table_name = os.environ.get('CUSTOMER_RESERVATION_TABLE')\nsuper().__init__(table_name)\nself._table = self._db.Table(table_name)",
"reservation_id = str(uuid.uuid4())\nitem = {'reservationId': reservation_id, 'shopId': shop_id, 'shopName': shop_name, 'userId': user_id, 'userName': user_name, 'courseId': course_... | <|body_start_0|>
table_name = os.environ.get('CUSTOMER_RESERVATION_TABLE')
super().__init__(table_name)
self._table = self._db.Table(table_name)
<|end_body_0|>
<|body_start_1|>
reservation_id = str(uuid.uuid4())
item = {'reservationId': reservation_id, 'shopId': shop_id, 'shopNa... | RestaurantReservationInfo操作用クラス | RestaurantReservationInfo | [
"LicenseRef-scancode-unknown-license-reference",
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestaurantReservationInfo:
"""RestaurantReservationInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
<|body_0|>
def put_item(self, shop_id, shop_name, user_id, user_name, course_id, course_name, reservation_people_number, reservation_date, reservation_starttime, reservatio... | stack_v2_sparse_classes_36k_train_022103 | 2,660 | permissive | [
{
"docstring": "初期化メソッド",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "データ登録 Parameters ---------- shop_id : int ショップID shop_name : str 店舗名 user_id : str ユーザーID user_name : str ユーザー名 course_id : int コースID course_name : str コース名 reservation_people_number : int 予約人数 res... | 2 | stack_v2_sparse_classes_30k_train_014471 | Implement the Python class `RestaurantReservationInfo` described below.
Class description:
RestaurantReservationInfo操作用クラス
Method signatures and docstrings:
- def __init__(self): 初期化メソッド
- def put_item(self, shop_id, shop_name, user_id, user_name, course_id, course_name, reservation_people_number, reservation_date, r... | Implement the Python class `RestaurantReservationInfo` described below.
Class description:
RestaurantReservationInfo操作用クラス
Method signatures and docstrings:
- def __init__(self): 初期化メソッド
- def put_item(self, shop_id, shop_name, user_id, user_name, course_id, course_name, reservation_people_number, reservation_date, r... | 248ae2ed52d8325d17d2ddbbd2975068381193fe | <|skeleton|>
class RestaurantReservationInfo:
"""RestaurantReservationInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
<|body_0|>
def put_item(self, shop_id, shop_name, user_id, user_name, course_id, course_name, reservation_people_number, reservation_date, reservation_starttime, reservatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestaurantReservationInfo:
"""RestaurantReservationInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
table_name = os.environ.get('CUSTOMER_RESERVATION_TABLE')
super().__init__(table_name)
self._table = self._db.Table(table_name)
def put_item(self, shop_id, shop_name, us... | the_stack_v2_python_sparse | backend/Layer/layer/restaurant/restaurant_reservation_info.py | cvc-Fujii/line-api-use-case-reservation-Restaurant | train | 0 |
221af954ec827e037fdab8c1c32d0d14bcb7daeb | [
"if self == other:\n return self\nelif type(self) == type(other):\n return type(self)(self.vars & other.vars)\nelif isinstance(other, SymbolicSubringAcceptingVarsFunctor):\n if not self.vars & other.vars:\n return self",
"if R is not SR:\n raise NotImplementedError('This functor can only be app... | <|body_start_0|>
if self == other:
return self
elif type(self) == type(other):
return type(self)(self.vars & other.vars)
elif isinstance(other, SymbolicSubringAcceptingVarsFunctor):
if not self.vars & other.vars:
return self
<|end_body_0|>
<|b... | SymbolicSubringRejectingVarsFunctor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymbolicSubringRejectingVarsFunctor:
def merge(self, other):
"""Merge this functor with ``other`` if possible. INPUT: - ``other`` -- a functor. OUTPUT: A functor or ``None``. EXAMPLES:: sage: from sage.symbolic.subring import SymbolicSubring sage: F = SymbolicSubring(accepting_variables=... | stack_v2_sparse_classes_36k_train_022104 | 31,870 | no_license | [
{
"docstring": "Merge this functor with ``other`` if possible. INPUT: - ``other`` -- a functor. OUTPUT: A functor or ``None``. EXAMPLES:: sage: from sage.symbolic.subring import SymbolicSubring sage: F = SymbolicSubring(accepting_variables=('a',)).construction()[0] sage: G = SymbolicSubring(rejecting_variables=... | 2 | stack_v2_sparse_classes_30k_train_018366 | Implement the Python class `SymbolicSubringRejectingVarsFunctor` described below.
Class description:
Implement the SymbolicSubringRejectingVarsFunctor class.
Method signatures and docstrings:
- def merge(self, other): Merge this functor with ``other`` if possible. INPUT: - ``other`` -- a functor. OUTPUT: A functor or... | Implement the Python class `SymbolicSubringRejectingVarsFunctor` described below.
Class description:
Implement the SymbolicSubringRejectingVarsFunctor class.
Method signatures and docstrings:
- def merge(self, other): Merge this functor with ``other`` if possible. INPUT: - ``other`` -- a functor. OUTPUT: A functor or... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class SymbolicSubringRejectingVarsFunctor:
def merge(self, other):
"""Merge this functor with ``other`` if possible. INPUT: - ``other`` -- a functor. OUTPUT: A functor or ``None``. EXAMPLES:: sage: from sage.symbolic.subring import SymbolicSubring sage: F = SymbolicSubring(accepting_variables=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SymbolicSubringRejectingVarsFunctor:
def merge(self, other):
"""Merge this functor with ``other`` if possible. INPUT: - ``other`` -- a functor. OUTPUT: A functor or ``None``. EXAMPLES:: sage: from sage.symbolic.subring import SymbolicSubring sage: F = SymbolicSubring(accepting_variables=('a',)).constr... | the_stack_v2_python_sparse | sage/src/sage/symbolic/subring.py | bopopescu/geosci | train | 0 | |
185b4d11a1a457e8709c75a8c9a383bb04d928d4 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | StationGroupServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationGroupServiceServicer:
"""Missing associated documentation comment in .proto file."""
def AddStationGroup(self, request, context):
"""新增工作站组"""
<|body_0|>
def QueryStationGroupList(self, request, context):
"""查询工作站组列表"""
<|body_1|>
def QuerySta... | stack_v2_sparse_classes_36k_train_022105 | 6,004 | no_license | [
{
"docstring": "新增工作站组",
"name": "AddStationGroup",
"signature": "def AddStationGroup(self, request, context)"
},
{
"docstring": "查询工作站组列表",
"name": "QueryStationGroupList",
"signature": "def QueryStationGroupList(self, request, context)"
},
{
"docstring": "查询工作站组详情",
"name":... | 3 | stack_v2_sparse_classes_30k_train_014327 | Implement the Python class `StationGroupServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def AddStationGroup(self, request, context): 新增工作站组
- def QueryStationGroupList(self, request, context): 查询工作站组列表
- def QueryStation... | Implement the Python class `StationGroupServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def AddStationGroup(self, request, context): 新增工作站组
- def QueryStationGroupList(self, request, context): 查询工作站组列表
- def QueryStation... | 0f6fe31a27de9bcf0697c28574b97555fe36d1e1 | <|skeleton|>
class StationGroupServiceServicer:
"""Missing associated documentation comment in .proto file."""
def AddStationGroup(self, request, context):
"""新增工作站组"""
<|body_0|>
def QueryStationGroupList(self, request, context):
"""查询工作站组列表"""
<|body_1|>
def QuerySta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StationGroupServiceServicer:
"""Missing associated documentation comment in .proto file."""
def AddStationGroup(self, request, context):
"""新增工作站组"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('M... | the_stack_v2_python_sparse | lib/grpc/wesrpc/warebasic/stationGroup_pb2_grpc.py | cming091/autotest | train | 0 |
6371e98dcf4922a75fc613698a1ef95faeae619e | [
"self._engine = qr.SobolEngine(dim, scramble=True)\nself._randomize = randomize\nself._rotation_vector: torch.Tensor = None",
"numel = shape.numel()\nprobs = self._engine.draw(numel)\nif shape.numel() == 1:\n probs.squeeze_(0)\nif self._randomize:\n if self._rotation_vector is None:\n self._rotation_... | <|body_start_0|>
self._engine = qr.SobolEngine(dim, scramble=True)
self._randomize = randomize
self._rotation_vector: torch.Tensor = None
<|end_body_0|>
<|body_start_1|>
numel = shape.numel()
probs = self._engine.draw(numel)
if shape.numel() == 1:
probs.squee... | Container for QMC engines. | EngineContainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EngineContainer:
"""Container for QMC engines."""
def __init__(self, dim: int, randomize: bool):
"""Internal initializer for :class:`_EngineContainer`. Args: dim (int): dimension of sample space. randomize (bool): whether to randomize."""
<|body_0|>
def sample(self, shap... | stack_v2_sparse_classes_36k_train_022106 | 1,498 | permissive | [
{
"docstring": "Internal initializer for :class:`_EngineContainer`. Args: dim (int): dimension of sample space. randomize (bool): whether to randomize.",
"name": "__init__",
"signature": "def __init__(self, dim: int, randomize: bool)"
},
{
"docstring": "Draws samples from the QMC engine. Args: s... | 2 | stack_v2_sparse_classes_30k_train_004682 | Implement the Python class `EngineContainer` described below.
Class description:
Container for QMC engines.
Method signatures and docstrings:
- def __init__(self, dim: int, randomize: bool): Internal initializer for :class:`_EngineContainer`. Args: dim (int): dimension of sample space. randomize (bool): whether to ra... | Implement the Python class `EngineContainer` described below.
Class description:
Container for QMC engines.
Method signatures and docstrings:
- def __init__(self, dim: int, randomize: bool): Internal initializer for :class:`_EngineContainer`. Args: dim (int): dimension of sample space. randomize (bool): whether to ra... | 374afe0c8d5197219b7a30d8e51e026d001cb0f9 | <|skeleton|>
class EngineContainer:
"""Container for QMC engines."""
def __init__(self, dim: int, randomize: bool):
"""Internal initializer for :class:`_EngineContainer`. Args: dim (int): dimension of sample space. randomize (bool): whether to randomize."""
<|body_0|>
def sample(self, shap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EngineContainer:
"""Container for QMC engines."""
def __init__(self, dim: int, randomize: bool):
"""Internal initializer for :class:`_EngineContainer`. Args: dim (int): dimension of sample space. randomize (bool): whether to randomize."""
self._engine = qr.SobolEngine(dim, scramble=True)
... | the_stack_v2_python_sparse | pyfilter/inference/qmc.py | tingiskhan/pyfilter | train | 78 |
6c55739f97a19b8bc215f53911a187b02306b0ca | [
"assert isinstance(dct, dict)\ntry:\n repo_name = dct.get('repo_name')\n if repo_name is None:\n repo_name = dct['project_id']\n return cls(str(repo_name), {str(k): SimpleDep(str(v['url']), str(v['branch']), str(v['revision'])) for k, v in dct.get('deps', {}).iteritems()}, str(dct.get('recipes_path'... | <|body_start_0|>
assert isinstance(dct, dict)
try:
repo_name = dct.get('repo_name')
if repo_name is None:
repo_name = dct['project_id']
return cls(str(repo_name), {str(k): SimpleDep(str(v['url']), str(v['branch']), str(v['revision'])) for k, v in dct.g... | Represents a `recipes.cfg` file. A subset of the recipes_cfg_pb2.RepoSpec message, just enough to load the dependencies for this recipe repo (i.e. good enough for RecipeDeps' purposes). | SimpleRecipesCfg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleRecipesCfg:
"""Represents a `recipes.cfg` file. A subset of the recipes_cfg_pb2.RepoSpec message, just enough to load the dependencies for this recipe repo (i.e. good enough for RecipeDeps' purposes)."""
def from_dict(cls, dct):
"""Parses a SimpleRecipesCfg from a dict. Args: *... | stack_v2_sparse_classes_36k_train_022107 | 5,431 | permissive | [
{
"docstring": "Parses a SimpleRecipesCfg from a dict. Args: * dct (dict) - A recipes.cfg parsed as JSON (i.e. a python dict) Returns parsed SimpleRecipesCfg object.",
"name": "from_dict",
"signature": "def from_dict(cls, dct)"
},
{
"docstring": "Returns this SimpleRecipesCfg as a JSON-serializa... | 4 | null | Implement the Python class `SimpleRecipesCfg` described below.
Class description:
Represents a `recipes.cfg` file. A subset of the recipes_cfg_pb2.RepoSpec message, just enough to load the dependencies for this recipe repo (i.e. good enough for RecipeDeps' purposes).
Method signatures and docstrings:
- def from_dict(... | Implement the Python class `SimpleRecipesCfg` described below.
Class description:
Represents a `recipes.cfg` file. A subset of the recipes_cfg_pb2.RepoSpec message, just enough to load the dependencies for this recipe repo (i.e. good enough for RecipeDeps' purposes).
Method signatures and docstrings:
- def from_dict(... | 34f43c51585b6113740640659cca0ddd27289684 | <|skeleton|>
class SimpleRecipesCfg:
"""Represents a `recipes.cfg` file. A subset of the recipes_cfg_pb2.RepoSpec message, just enough to load the dependencies for this recipe repo (i.e. good enough for RecipeDeps' purposes)."""
def from_dict(cls, dct):
"""Parses a SimpleRecipesCfg from a dict. Args: *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleRecipesCfg:
"""Represents a `recipes.cfg` file. A subset of the recipes_cfg_pb2.RepoSpec message, just enough to load the dependencies for this recipe repo (i.e. good enough for RecipeDeps' purposes)."""
def from_dict(cls, dct):
"""Parses a SimpleRecipesCfg from a dict. Args: * dct (dict) -... | the_stack_v2_python_sparse | recipe_engine/internal/simple_cfg.py | luci/recipes-py | train | 27 |
816619fe3e5697345aabdad5642b18aaf7d9bc94 | [
"book_list = get_object_or_404(models.List, id=list_id)\nbook_list.raise_not_editable(request.user)\ndata = {'list': book_list, 'pending': book_list.listitem_set.filter(approved=False), 'list_form': forms.ListForm(instance=book_list)}\nreturn TemplateResponse(request, 'lists/curate.html', data)",
"book_list = get... | <|body_start_0|>
book_list = get_object_or_404(models.List, id=list_id)
book_list.raise_not_editable(request.user)
data = {'list': book_list, 'pending': book_list.listitem_set.filter(approved=False), 'list_form': forms.ListForm(instance=book_list)}
return TemplateResponse(request, 'lists... | approve or discard list suggestions | Curate | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Curate:
"""approve or discard list suggestions"""
def get(self, request, list_id):
"""display a pending list"""
<|body_0|>
def post(self, request, list_id):
"""edit a book_list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
book_list = get_obje... | stack_v2_sparse_classes_36k_train_022108 | 2,106 | no_license | [
{
"docstring": "display a pending list",
"name": "get",
"signature": "def get(self, request, list_id)"
},
{
"docstring": "edit a book_list",
"name": "post",
"signature": "def post(self, request, list_id)"
}
] | 2 | null | Implement the Python class `Curate` described below.
Class description:
approve or discard list suggestions
Method signatures and docstrings:
- def get(self, request, list_id): display a pending list
- def post(self, request, list_id): edit a book_list | Implement the Python class `Curate` described below.
Class description:
approve or discard list suggestions
Method signatures and docstrings:
- def get(self, request, list_id): display a pending list
- def post(self, request, list_id): edit a book_list
<|skeleton|>
class Curate:
"""approve or discard list sugges... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class Curate:
"""approve or discard list suggestions"""
def get(self, request, list_id):
"""display a pending list"""
<|body_0|>
def post(self, request, list_id):
"""edit a book_list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Curate:
"""approve or discard list suggestions"""
def get(self, request, list_id):
"""display a pending list"""
book_list = get_object_or_404(models.List, id=list_id)
book_list.raise_not_editable(request.user)
data = {'list': book_list, 'pending': book_list.listitem_set.fi... | the_stack_v2_python_sparse | bookwyrm/views/list/curate.py | bookwyrm-social/bookwyrm | train | 1,398 |
bc4ab6b9203592ca6f709d70ffedd28da06df1fa | [
"X_coord = target_grid.coord(axis='X')\nY_coord = target_grid.coord(axis='Y')\ntime_coord = AuxCoord(np.array(time.replace(tzinfo=timezone.utc).timestamp(), dtype=np.int64), standard_name='time', units=cf_units.Unit('seconds since 1970-01-01 00:00:00 UTC', calendar=cf_units.CALENDAR_STANDARD))\nattrs = generate_man... | <|body_start_0|>
X_coord = target_grid.coord(axis='X')
Y_coord = target_grid.coord(axis='Y')
time_coord = AuxCoord(np.array(time.replace(tzinfo=timezone.utc).timestamp(), dtype=np.int64), standard_name='time', units=cf_units.Unit('seconds since 1970-01-01 00:00:00 UTC', calendar=cf_units.CALENDA... | A plugin to evaluate local solar time. | GenerateSolarTime | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateSolarTime:
"""A plugin to evaluate local solar time."""
def _create_solar_time_cube(self, solar_time_data: ndarray, target_grid: Cube, time: datetime, new_title: Optional[str]) -> Cube:
"""Create solar time cube for the specified valid time. Args: solar_time_data: Solar time ... | stack_v2_sparse_classes_36k_train_022109 | 23,567 | permissive | [
{
"docstring": "Create solar time cube for the specified valid time. Args: solar_time_data: Solar time data. target_grid: Cube containing spatial grid over which the solar time has been calculated. time: Time associated with the local solar time. new_title: New title for the output cube attributes. If None, thi... | 2 | null | Implement the Python class `GenerateSolarTime` described below.
Class description:
A plugin to evaluate local solar time.
Method signatures and docstrings:
- def _create_solar_time_cube(self, solar_time_data: ndarray, target_grid: Cube, time: datetime, new_title: Optional[str]) -> Cube: Create solar time cube for the... | Implement the Python class `GenerateSolarTime` described below.
Class description:
A plugin to evaluate local solar time.
Method signatures and docstrings:
- def _create_solar_time_cube(self, solar_time_data: ndarray, target_grid: Cube, time: datetime, new_title: Optional[str]) -> Cube: Create solar time cube for the... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class GenerateSolarTime:
"""A plugin to evaluate local solar time."""
def _create_solar_time_cube(self, solar_time_data: ndarray, target_grid: Cube, time: datetime, new_title: Optional[str]) -> Cube:
"""Create solar time cube for the specified valid time. Args: solar_time_data: Solar time ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenerateSolarTime:
"""A plugin to evaluate local solar time."""
def _create_solar_time_cube(self, solar_time_data: ndarray, target_grid: Cube, time: datetime, new_title: Optional[str]) -> Cube:
"""Create solar time cube for the specified valid time. Args: solar_time_data: Solar time data. target_... | the_stack_v2_python_sparse | improver/generate_ancillaries/generate_derived_solar_fields.py | metoppv/improver | train | 101 |
e2086e6f4c1827f8687740c7cc1e0cf64d1b6c6f | [
"def helper(left, right):\n if left < right:\n s[left], s[right] = (s[right], s[left])\n helper(left + 1, right - 1)\nhelper(0, len(s) - 1)\nreturn s",
"left, right = (0, len(s) - 1)\nwhile left < right:\n s[left], s[right] = (s[right], s[left])\n left, right = (left + 1, right - 1)\nreturn... | <|body_start_0|>
def helper(left, right):
if left < right:
s[left], s[right] = (s[right], s[left])
helper(left + 1, right - 1)
helper(0, len(s) - 1)
return s
<|end_body_0|>
<|body_start_1|>
left, right = (0, len(s) - 1)
while left < ri... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseString_1(self, s: List[str]) -> None:
"""方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString_2(self, s):
"""方法二:双指针法(迭代) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间... | stack_v2_sparse_classes_36k_train_022110 | 1,783 | no_license | [
{
"docstring": "方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.",
"name": "reverseString_1",
"signature": "def reverseString_1(self, s: List[str]) -> None"
},
{
"docstring": "方法二:双指针法(迭代) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(1),只使... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString_1(self, s: List[str]) -> None: 方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.
- def rever... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString_1(self, s: List[str]) -> None: 方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead.
- def rever... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def reverseString_1(self, s: List[str]) -> None:
"""方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString_2(self, s):
"""方法二:双指针法(迭代) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseString_1(self, s: List[str]) -> None:
"""方法一:双指针(递归) 时间复杂度:O(N)。执行了 N/2 次的交换。 空间复杂度:O(N),递归过程中使用的堆栈空间 N/2 。 Do not return anything, modify s in-place instead."""
def helper(left, right):
if left < right:
s[left], s[right] = (s[right], s[left])
... | the_stack_v2_python_sparse | 软件开发岗刷题(华为笔试准备)/递归/reverseString.py | MaoningGuan/LeetCode | train | 3 | |
e091d03d3ea5ec4d503bd736aafba91aba0ab645 | [
"test_obj = ElectricAppliances(1, 2, 3, 4, 5, 6)\nself.assertEqual(test_obj.product_code, 1)\nself.assertEqual(test_obj.description, 2)\nself.assertEqual(test_obj.market_price, 3)\nself.assertEqual(test_obj.rental_price, 4)\nself.assertEqual(test_obj.brand, 5)\nself.assertEqual(test_obj.voltage, 6)",
"test_obj = ... | <|body_start_0|>
test_obj = ElectricAppliances(1, 2, 3, 4, 5, 6)
self.assertEqual(test_obj.product_code, 1)
self.assertEqual(test_obj.description, 2)
self.assertEqual(test_obj.market_price, 3)
self.assertEqual(test_obj.rental_price, 4)
self.assertEqual(test_obj.brand, 5)
... | Test EA class | ElectricAppliancesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliancesTest:
"""Test EA class"""
def test_init(self):
"""Test __init__()"""
<|body_0|>
def test_return_dict(self):
"""Test return as dict func"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_obj = ElectricAppliances(1, 2, 3, 4, 5... | stack_v2_sparse_classes_36k_train_022111 | 4,928 | no_license | [
{
"docstring": "Test __init__()",
"name": "test_init",
"signature": "def test_init(self)"
},
{
"docstring": "Test return as dict func",
"name": "test_return_dict",
"signature": "def test_return_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019837 | Implement the Python class `ElectricAppliancesTest` described below.
Class description:
Test EA class
Method signatures and docstrings:
- def test_init(self): Test __init__()
- def test_return_dict(self): Test return as dict func | Implement the Python class `ElectricAppliancesTest` described below.
Class description:
Test EA class
Method signatures and docstrings:
- def test_init(self): Test __init__()
- def test_return_dict(self): Test return as dict func
<|skeleton|>
class ElectricAppliancesTest:
"""Test EA class"""
def test_init(s... | 6ffd7b4ab8346076d3b6cc02ca1ebca3bf028697 | <|skeleton|>
class ElectricAppliancesTest:
"""Test EA class"""
def test_init(self):
"""Test __init__()"""
<|body_0|>
def test_return_dict(self):
"""Test return as dict func"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliancesTest:
"""Test EA class"""
def test_init(self):
"""Test __init__()"""
test_obj = ElectricAppliances(1, 2, 3, 4, 5, 6)
self.assertEqual(test_obj.product_code, 1)
self.assertEqual(test_obj.description, 2)
self.assertEqual(test_obj.market_price, 3)
... | the_stack_v2_python_sparse | students/JasneetChandok/lesson01/assignment/test_unit.py | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | train | 4 |
9ac60113e50b2b027b65a49adebdea59f22d16e5 | [
"try:\n runner_view, __ = self._get_producer(operation_type)\nexcept ValueError:\n return redirect('home')\nreturn runner_view(request, operation_type=operation_type, **kwargs)",
"try:\n __, runner_cls = self._get_producer(action_type)\nexcept ValueError:\n return redirect('home')\nreturn runner_cls()... | <|body_start_0|>
try:
runner_view, __ = self._get_producer(operation_type)
except ValueError:
return redirect('home')
return runner_view(request, operation_type=operation_type, **kwargs)
<|end_body_0|>
<|body_start_1|>
try:
__, runner_cls = self._get_... | Factory to manage scheduling of action runs. Producer stores a tuple with: - Class.as_view() for view processing - Class to execute other methods | ActionRunFactory | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionRunFactory:
"""Factory to manage scheduling of action runs. Producer stores a tuple with: - Class.as_view() for view processing - Class to execute other methods"""
def process_request(self, request: http.HttpRequest, operation_type: int, **kwargs) -> http.HttpResponse:
"""Execu... | stack_v2_sparse_classes_36k_train_022112 | 7,115 | permissive | [
{
"docstring": "Execute function to process a run request. :param request: Http Request received (get or post) :param operation_type: Type of action being run. :param kwargs: Dictionary with action :return: HttpResponse",
"name": "process_request",
"signature": "def process_request(self, request: http.H... | 2 | stack_v2_sparse_classes_30k_train_002562 | Implement the Python class `ActionRunFactory` described below.
Class description:
Factory to manage scheduling of action runs. Producer stores a tuple with: - Class.as_view() for view processing - Class to execute other methods
Method signatures and docstrings:
- def process_request(self, request: http.HttpRequest, o... | Implement the Python class `ActionRunFactory` described below.
Class description:
Factory to manage scheduling of action runs. Producer stores a tuple with: - Class.as_view() for view processing - Class to execute other methods
Method signatures and docstrings:
- def process_request(self, request: http.HttpRequest, o... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class ActionRunFactory:
"""Factory to manage scheduling of action runs. Producer stores a tuple with: - Class.as_view() for view processing - Class to execute other methods"""
def process_request(self, request: http.HttpRequest, operation_type: int, **kwargs) -> http.HttpResponse:
"""Execu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionRunFactory:
"""Factory to manage scheduling of action runs. Producer stores a tuple with: - Class.as_view() for view processing - Class to execute other methods"""
def process_request(self, request: http.HttpRequest, operation_type: int, **kwargs) -> http.HttpResponse:
"""Execute function t... | the_stack_v2_python_sparse | ontask/action/services/run_factory.py | abelardopardo/ontask_b | train | 43 |
7e9afd3c65cf321a79d63318681df430ffadeab2 | [
"last_call = last_call or ['', '']\nopts, args = self.parse_options(parameter_s, 'prn:')\ntry:\n filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)\nexcept MacroToEdit:\n print('Macro editing not yet implemented in 2-process model.')\n return\nfilename = os.path.abspath(f... | <|body_start_0|>
last_call = last_call or ['', '']
opts, args = self.parse_options(parameter_s, 'prn:')
try:
filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
except MacroToEdit:
print('Macro editing not yet implemented in 2-pro... | Kernel magics. | KernelMagics | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelMagics:
"""Kernel magics."""
def edit(self, parameter_s='', last_call=None):
"""Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs an external text editor. You will need to set the command for this editor via the ``TerminalInteractiveShe... | stack_v2_sparse_classes_36k_train_022113 | 24,015 | permissive | [
{
"docstring": "Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs an external text editor. You will need to set the command for this editor via the ``TerminalInteractiveShell.editor`` option in your configuration file before it will work. This command allows you to conv... | 6 | stack_v2_sparse_classes_30k_train_017389 | Implement the Python class `KernelMagics` described below.
Class description:
Kernel magics.
Method signatures and docstrings:
- def edit(self, parameter_s='', last_call=None): Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs an external text editor. You will need to set the... | Implement the Python class `KernelMagics` described below.
Class description:
Kernel magics.
Method signatures and docstrings:
- def edit(self, parameter_s='', last_call=None): Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs an external text editor. You will need to set the... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class KernelMagics:
"""Kernel magics."""
def edit(self, parameter_s='', last_call=None):
"""Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs an external text editor. You will need to set the command for this editor via the ``TerminalInteractiveShe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KernelMagics:
"""Kernel magics."""
def edit(self, parameter_s='', last_call=None):
"""Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs an external text editor. You will need to set the command for this editor via the ``TerminalInteractiveShell.editor`` o... | the_stack_v2_python_sparse | contrib/python/ipykernel/py3/ipykernel/zmqshell.py | catboost/catboost | train | 8,012 |
60f29405f39725e1835d6d3c98c65e40f682f986 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EdiscoverySearch()",
"from .data_source import DataSource\nfrom .data_source_scopes import DataSourceScopes\nfrom .ediscovery_add_to_review_set_operation import EdiscoveryAddToReviewSetOperation\nfrom .ediscovery_estimate_operation imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EdiscoverySearch()
<|end_body_0|>
<|body_start_1|>
from .data_source import DataSource
from .data_source_scopes import DataSourceScopes
from .ediscovery_add_to_review_set_operati... | EdiscoverySearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdiscoverySearch:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k_train_022114 | 5,246 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EdiscoverySearch",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_010386 | Implement the Python class `EdiscoverySearch` described below.
Class description:
Implement the EdiscoverySearch class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `EdiscoverySearch` described below.
Class description:
Implement the EdiscoverySearch class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EdiscoverySearch:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdiscoverySearch:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EdiscoverySearch:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Edisco... | the_stack_v2_python_sparse | msgraph/generated/models/security/ediscovery_search.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
57487a29e85277f7229d36ac6ff63518adcea0bf | [
"result = empty_result()\nresult['data'] = {'devices': []}\nwith sqla_session() as session:\n instance = session.query(Device).filter(Device.id == device_id).one_or_none()\n if instance:\n result['data']['devices'] = device_data_postprocess([instance])\n else:\n return (empty_result('error', ... | <|body_start_0|>
result = empty_result()
result['data'] = {'devices': []}
with sqla_session() as session:
instance = session.query(Device).filter(Device.id == device_id).one_or_none()
if instance:
result['data']['devices'] = device_data_postprocess([instan... | DeviceByIdApi | [
"BSD-2-Clause-Views",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceByIdApi:
def get(self, device_id):
"""Get a device from ID"""
<|body_0|>
def delete(self, device_id):
"""Delete device from ID"""
<|body_1|>
def put(self, device_id):
"""Modify device from ID"""
<|body_2|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_022115 | 46,972 | permissive | [
{
"docstring": "Get a device from ID",
"name": "get",
"signature": "def get(self, device_id)"
},
{
"docstring": "Delete device from ID",
"name": "delete",
"signature": "def delete(self, device_id)"
},
{
"docstring": "Modify device from ID",
"name": "put",
"signature": "de... | 3 | null | Implement the Python class `DeviceByIdApi` described below.
Class description:
Implement the DeviceByIdApi class.
Method signatures and docstrings:
- def get(self, device_id): Get a device from ID
- def delete(self, device_id): Delete device from ID
- def put(self, device_id): Modify device from ID | Implement the Python class `DeviceByIdApi` described below.
Class description:
Implement the DeviceByIdApi class.
Method signatures and docstrings:
- def get(self, device_id): Get a device from ID
- def delete(self, device_id): Delete device from ID
- def put(self, device_id): Modify device from ID
<|skeleton|>
clas... | d755dfed69bebe0c7bea66ad1802cba2cd89fec8 | <|skeleton|>
class DeviceByIdApi:
def get(self, device_id):
"""Get a device from ID"""
<|body_0|>
def delete(self, device_id):
"""Delete device from ID"""
<|body_1|>
def put(self, device_id):
"""Modify device from ID"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceByIdApi:
def get(self, device_id):
"""Get a device from ID"""
result = empty_result()
result['data'] = {'devices': []}
with sqla_session() as session:
instance = session.query(Device).filter(Device.id == device_id).one_or_none()
if instance:
... | the_stack_v2_python_sparse | src/cnaas_nms/api/device.py | SUNET/cnaas-nms | train | 67 | |
72c10470840e55140f4d7fd1c6cda6aef61509e6 | [
"if n == 1:\n return 0\nif n % 2 == 0:\n return self.integerReplacement(n / 2) + 1\nelse:\n add = self.integerReplacement(n + 1) + 1\n subtract = self.integerReplacement(n - 1) + 1\n return min(add, subtract)",
"def min_operations(n: int):\n if n in dp:\n return dp[n]\n if n % 2 == 0:\... | <|body_start_0|>
if n == 1:
return 0
if n % 2 == 0:
return self.integerReplacement(n / 2) + 1
else:
add = self.integerReplacement(n + 1) + 1
subtract = self.integerReplacement(n - 1) + 1
return min(add, subtract)
<|end_body_0|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerReplacement(self, n: int) -> int:
"""My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore ... | stack_v2_sparse_classes_36k_train_022116 | 1,715 | no_license | [
{
"docstring": "My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore BOTH possibilities of adding or subtracting, and take the route wi... | 2 | stack_v2_sparse_classes_30k_train_010215 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement(self, n: int) -> int: My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for a... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement(self, n: int) -> int: My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for a... | 8b11ceb675089a12a4a44f9b044dac7c3e666819 | <|skeleton|>
class Solution:
def integerReplacement(self, n: int) -> int:
"""My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def integerReplacement(self, n: int) -> int:
"""My Solution: Brute Force Solution IDEA: We explore all possibilities. Given the rules, integerReplacement(n) will converge to 1 for all integers. Thus, we can use recursion to see how many steps it will take. When odd, we explore BOTH possibili... | the_stack_v2_python_sparse | Python_Solutions/397_Integer_Replacement.py | lw75251/leetcode | train | 0 | |
ea0c3035bb232d3994599d95a3155686103e7b6f | [
"self.input_file = input_file\nself.output_file = output_file\nself.in_place = in_place",
"plant = MultibodyPlant(time_step=0.0)\nscene_graph = SceneGraph()\nplant.RegisterAsSourceForSceneGraph(scene_graph)\nparser = Parser(plant)\nparser.package_map().PopulateFromRosPackagePath()\nparser.AddModels(str(self.input... | <|body_start_0|>
self.input_file = input_file
self.output_file = output_file
self.in_place = in_place
<|end_body_0|>
<|body_start_1|>
plant = MultibodyPlant(time_step=0.0)
scene_graph = SceneGraph()
plant.RegisterAsSourceForSceneGraph(scene_graph)
parser = Parser... | Fixes specified inertias in a URDF or SDFormat input file, writing the new file contents to one of: stdout, a new file, or the original file. | InertiaFixer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InertiaFixer:
"""Fixes specified inertias in a URDF or SDFormat input file, writing the new file contents to one of: stdout, a new file, or the original file."""
def __init__(self, *, input_file: Path, output_file: Path=None, in_place: bool=False):
"""Initialize an InertiaFixer. Args... | stack_v2_sparse_classes_36k_train_022117 | 26,603 | permissive | [
{
"docstring": "Initialize an InertiaFixer. Args: input_file: the file to fix. output_file: a file to be created or overwritten with the new file contents. If None, the new contents will be written to stdout. in_place: if True, write output back to the input file.",
"name": "__init__",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_011632 | Implement the Python class `InertiaFixer` described below.
Class description:
Fixes specified inertias in a URDF or SDFormat input file, writing the new file contents to one of: stdout, a new file, or the original file.
Method signatures and docstrings:
- def __init__(self, *, input_file: Path, output_file: Path=None... | Implement the Python class `InertiaFixer` described below.
Class description:
Fixes specified inertias in a URDF or SDFormat input file, writing the new file contents to one of: stdout, a new file, or the original file.
Method signatures and docstrings:
- def __init__(self, *, input_file: Path, output_file: Path=None... | 3905758e8e99b0f2332461b1cb630907245e0572 | <|skeleton|>
class InertiaFixer:
"""Fixes specified inertias in a URDF or SDFormat input file, writing the new file contents to one of: stdout, a new file, or the original file."""
def __init__(self, *, input_file: Path, output_file: Path=None, in_place: bool=False):
"""Initialize an InertiaFixer. Args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InertiaFixer:
"""Fixes specified inertias in a URDF or SDFormat input file, writing the new file contents to one of: stdout, a new file, or the original file."""
def __init__(self, *, input_file: Path, output_file: Path=None, in_place: bool=False):
"""Initialize an InertiaFixer. Args: input_file:... | the_stack_v2_python_sparse | bindings/pydrake/multibody/_inertia_fixer.py | RobotLocomotion/drake | train | 2,904 |
fc27da7ef49611c0fca60abbda49fe7d11d60a84 | [
"if retry_on_exception is None:\n retry_on_exception = (Exception,)\n\ndef decorator(func):\n\n @functools.wraps(func)\n async def wrapper(*args, **kwargs):\n attempt = 0\n result = None\n while attempt <= stop_max_attempt_number:\n try:\n result = await func(... | <|body_start_0|>
if retry_on_exception is None:
retry_on_exception = (Exception,)
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
attempt = 0
result = None
while attempt <= stop_max_atte... | Utility class for async functions. | AsyncUtils | [
"Python-2.0",
"GPL-1.0-or-later",
"MPL-2.0",
"MIT",
"LicenseRef-scancode-python-cwi",
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"MIT-0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncUtils:
"""Utility class for async functions."""
def async_retry(stop_max_attempt_number=5, wait_fixed=1, retry_on_exception=None):
"""Decorate an async coroutine function to retry its execution when an exception is risen. :param stop_max_attempt_number: Max number of retries. :p... | stack_v2_sparse_classes_36k_train_022118 | 19,599 | permissive | [
{
"docstring": "Decorate an async coroutine function to retry its execution when an exception is risen. :param stop_max_attempt_number: Max number of retries. :param wait_fixed: Wait time (in seconds) between retries. :param retry_on_exception: Exception to retry on. :return:",
"name": "async_retry",
"s... | 3 | stack_v2_sparse_classes_30k_train_015547 | Implement the Python class `AsyncUtils` described below.
Class description:
Utility class for async functions.
Method signatures and docstrings:
- def async_retry(stop_max_attempt_number=5, wait_fixed=1, retry_on_exception=None): Decorate an async coroutine function to retry its execution when an exception is risen. ... | Implement the Python class `AsyncUtils` described below.
Class description:
Utility class for async functions.
Method signatures and docstrings:
- def async_retry(stop_max_attempt_number=5, wait_fixed=1, retry_on_exception=None): Decorate an async coroutine function to retry its execution when an exception is risen. ... | a213978a09ea7fc80855bf55c539861ea95259f9 | <|skeleton|>
class AsyncUtils:
"""Utility class for async functions."""
def async_retry(stop_max_attempt_number=5, wait_fixed=1, retry_on_exception=None):
"""Decorate an async coroutine function to retry its execution when an exception is risen. :param stop_max_attempt_number: Max number of retries. :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncUtils:
"""Utility class for async functions."""
def async_retry(stop_max_attempt_number=5, wait_fixed=1, retry_on_exception=None):
"""Decorate an async coroutine function to retry its execution when an exception is risen. :param stop_max_attempt_number: Max number of retries. :param wait_fix... | the_stack_v2_python_sparse | cli/src/pcluster/utils.py | aws/aws-parallelcluster | train | 520 |
86d9408b30c98b62b14f6b8f8fa29f27ee9af68c | [
"subject = loader.render_to_string(subject_template_name, context)\nsubject = ''.join(subject.splitlines())\nbody = loader.render_to_string(email_template_name, context)\nemail_message = EmailMultiAlternatives(subject, body, from_email, [to_email])\nif html_email_template_name is not None:\n html_email = loader.... | <|body_start_0|>
subject = loader.render_to_string(subject_template_name, context)
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_temp... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
<|body_0|>
def get_users(self, email):
"""Given an em... | stack_v2_sparse_classes_36k_train_022119 | 11,275 | no_license | [
{
"docstring": "Send a django.core.mail.EmailMultiAlternatives to `to_email`.",
"name": "send_mail",
"signature": "def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)"
},
{
"docstring": "Given an email, return matching use... | 3 | stack_v2_sparse_classes_30k_train_012633 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): Send a django.core.mail.EmailMult... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): Send a django.core.mail.EmailMult... | 144e69461f2267cc85f4565ecc37c93690257a69 | <|skeleton|>
class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
<|body_0|>
def get_users(self, email):
"""Given an em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None):
"""Send a django.core.mail.EmailMultiAlternatives to `to_email`."""
subject = loader.render_to_string(subject_template_name, context)
subjec... | the_stack_v2_python_sparse | apps/user/serializers.py | Ezhilan-ava/cosoft | train | 0 | |
b4366f722d23349d7cf676f58cdb9eb8b97f11ae | [
"mocked.return_value.is_valid_request.return_value = True\nself.course_ref.delete()\nresponse = self.client.post('/lti/', data=self.headers, follow=True)\nself.assertFalse(CourseRef.objects.filter(course=self.course).exists())\nself.assertTemplateUsed(response, 'lti/error.html')",
"request = Mock()\nrequest.sessi... | <|body_start_0|>
mocked.return_value.is_valid_request.return_value = True
self.course_ref.delete()
response = self.client.post('/lti/', data=self.headers, follow=True)
self.assertFalse(CourseRef.objects.filter(course=self.course).exists())
self.assertTemplateUsed(response, 'lti/e... | Testing CourseRef object. | TestCourseRef | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCourseRef:
"""Testing CourseRef object."""
def test_course_ref_roles(self, mocked):
"""Test different action for different roles"""
<|body_0|>
def test_create_courseref_only_lti(self, mocked):
"""Test that only LTI is allowed."""
<|body_1|>
def t... | stack_v2_sparse_classes_36k_train_022120 | 21,335 | permissive | [
{
"docstring": "Test different action for different roles",
"name": "test_course_ref_roles",
"signature": "def test_course_ref_roles(self, mocked)"
},
{
"docstring": "Test that only LTI is allowed.",
"name": "test_create_courseref_only_lti",
"signature": "def test_create_courseref_only_l... | 3 | null | Implement the Python class `TestCourseRef` described below.
Class description:
Testing CourseRef object.
Method signatures and docstrings:
- def test_course_ref_roles(self, mocked): Test different action for different roles
- def test_create_courseref_only_lti(self, mocked): Test that only LTI is allowed.
- def test_... | Implement the Python class `TestCourseRef` described below.
Class description:
Testing CourseRef object.
Method signatures and docstrings:
- def test_course_ref_roles(self, mocked): Test different action for different roles
- def test_create_courseref_only_lti(self, mocked): Test that only LTI is allowed.
- def test_... | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | <|skeleton|>
class TestCourseRef:
"""Testing CourseRef object."""
def test_course_ref_roles(self, mocked):
"""Test different action for different roles"""
<|body_0|>
def test_create_courseref_only_lti(self, mocked):
"""Test that only LTI is allowed."""
<|body_1|>
def t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCourseRef:
"""Testing CourseRef object."""
def test_course_ref_roles(self, mocked):
"""Test different action for different roles"""
mocked.return_value.is_valid_request.return_value = True
self.course_ref.delete()
response = self.client.post('/lti/', data=self.headers,... | the_stack_v2_python_sparse | mysite/lti/integration_tests.py | cjlee112/socraticqs2 | train | 8 |
49a0342226e76041a7579253595cab30357d8cd7 | [
"self.size = size\nself.processed_bytes = processed_bytes\nself.finished = size == processed_bytes\nself.time = time\nself.source_url = source_url\nself.destination_url = destination_url\nself.component_number = component_number\nself.total_components = total_components\nself.operation_name = operation_name\nself.p... | <|body_start_0|>
self.size = size
self.processed_bytes = processed_bytes
self.finished = size == processed_bytes
self.time = time
self.source_url = source_url
self.destination_url = destination_url
self.component_number = component_number
self.total_compon... | Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: size (int): Total size of file/component in bytes. processed_bytes (int): Number of bytes already operated on. finished (bool): ... | ProgressMessage | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressMessage:
"""Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: size (int): Total size of file/component in bytes. processed_bytes (int): Number of b... | stack_v2_sparse_classes_36k_train_022121 | 4,082 | permissive | [
{
"docstring": "Initializes a ProgressMessage. See attributes docstring for arguments.",
"name": "__init__",
"signature": "def __init__(self, size, processed_bytes, time, source_url, destination_url=None, component_number=None, total_components=None, operation_name=None, process_id=None, thread_id=None)... | 2 | stack_v2_sparse_classes_30k_train_012885 | Implement the Python class `ProgressMessage` described below.
Class description:
Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: size (int): Total size of file/component in by... | Implement the Python class `ProgressMessage` described below.
Class description:
Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: size (int): Total size of file/component in by... | 849d09dd7863efecbdf4072a504e1554e119f6ae | <|skeleton|>
class ProgressMessage:
"""Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: size (int): Total size of file/component in bytes. processed_bytes (int): Number of b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgressMessage:
"""Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: size (int): Total size of file/component in bytes. processed_bytes (int): Number of bytes already ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/thread_messages.py | PrateekKhatri/gcloud_cli | train | 0 |
966f16cf9face86cced12a3b07ddf0533e30961f | [
"self.agents = []\nself.network = {}\nself.history = []\nself.events_run = []\nself.eventLogDir = None\nself._variables = {}\nself.event10 = False\nself.forkbomb = False\nself.allowed_commands = ['cd', 'clear', 'echo', 'gnome', 'help', 'iplist', 'ls', 'man', 'ping', 'pscan', 'shell', 'shutdown', 'vscan', 'exploit',... | <|body_start_0|>
self.agents = []
self.network = {}
self.history = []
self.events_run = []
self.eventLogDir = None
self._variables = {}
self.event10 = False
self.forkbomb = False
self.allowed_commands = ['cd', 'clear', 'echo', 'gnome', 'help', 'ipl... | Handles Game objects. | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Handles Game objects."""
def __init__(self):
"""Create a new Game. No arguments needed, all setup happens here."""
<|body_0|>
def add_commands(self, *commands):
"""Adds commands to the allowed list."""
<|body_1|>
def spawn_agent(self, agent_... | stack_v2_sparse_classes_36k_train_022122 | 2,499 | no_license | [
{
"docstring": "Create a new Game. No arguments needed, all setup happens here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds commands to the allowed list.",
"name": "add_commands",
"signature": "def add_commands(self, *commands)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_018354 | Implement the Python class `Game` described below.
Class description:
Handles Game objects.
Method signatures and docstrings:
- def __init__(self): Create a new Game. No arguments needed, all setup happens here.
- def add_commands(self, *commands): Adds commands to the allowed list.
- def spawn_agent(self, agent_name... | Implement the Python class `Game` described below.
Class description:
Handles Game objects.
Method signatures and docstrings:
- def __init__(self): Create a new Game. No arguments needed, all setup happens here.
- def add_commands(self, *commands): Adds commands to the allowed list.
- def spawn_agent(self, agent_name... | 01236c3da46cb049e4b4b821190399cde5491522 | <|skeleton|>
class Game:
"""Handles Game objects."""
def __init__(self):
"""Create a new Game. No arguments needed, all setup happens here."""
<|body_0|>
def add_commands(self, *commands):
"""Adds commands to the allowed list."""
<|body_1|>
def spawn_agent(self, agent_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""Handles Game objects."""
def __init__(self):
"""Create a new Game. No arguments needed, all setup happens here."""
self.agents = []
self.network = {}
self.history = []
self.events_run = []
self.eventLogDir = None
self._variables = {}
... | the_stack_v2_python_sparse | src/game.py | grantHaataja/AILEE | train | 1 |
f54c54ead2fe8bec3cd518f3279194253f273d21 | [
"super(TrainingMonitor, self).__init__()\nself.figPath = figPath\nself.jsonPath = jsonPath\nself.startAt = startAt",
"self.H = {}\nif self.jsonPath is not None:\n if os.path.exists(self.jsonPath):\n self.H = json.loads(open(self.jsonPath).read())\n if self.startAt > 0:\n for k in self.... | <|body_start_0|>
super(TrainingMonitor, self).__init__()
self.figPath = figPath
self.jsonPath = jsonPath
self.startAt = startAt
<|end_body_0|>
<|body_start_1|>
self.H = {}
if self.jsonPath is not None:
if os.path.exists(self.jsonPath):
self.H ... | TrainingMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingMonitor:
def __init__(self, figPath, jsonPath, startAt=0):
"""Store the ouput path for the figure, the path to the JSON serialized file and the starting epoch Args: figPath (string): the path to the output figure that we can use to visualize loss and accuracy over time jsonPath (... | stack_v2_sparse_classes_36k_train_022123 | 3,559 | no_license | [
{
"docstring": "Store the ouput path for the figure, the path to the JSON serialized file and the starting epoch Args: figPath (string): the path to the output figure that we can use to visualize loss and accuracy over time jsonPath (string): the path to the json serialized file startAt (int, optional): the sta... | 3 | stack_v2_sparse_classes_30k_train_007889 | Implement the Python class `TrainingMonitor` described below.
Class description:
Implement the TrainingMonitor class.
Method signatures and docstrings:
- def __init__(self, figPath, jsonPath, startAt=0): Store the ouput path for the figure, the path to the JSON serialized file and the starting epoch Args: figPath (st... | Implement the Python class `TrainingMonitor` described below.
Class description:
Implement the TrainingMonitor class.
Method signatures and docstrings:
- def __init__(self, figPath, jsonPath, startAt=0): Store the ouput path for the figure, the path to the JSON serialized file and the starting epoch Args: figPath (st... | 86dcc24d03e32e3c139950c33fcf08eb7de2aeea | <|skeleton|>
class TrainingMonitor:
def __init__(self, figPath, jsonPath, startAt=0):
"""Store the ouput path for the figure, the path to the JSON serialized file and the starting epoch Args: figPath (string): the path to the output figure that we can use to visualize loss and accuracy over time jsonPath (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainingMonitor:
def __init__(self, figPath, jsonPath, startAt=0):
"""Store the ouput path for the figure, the path to the JSON serialized file and the starting epoch Args: figPath (string): the path to the output figure that we can use to visualize loss and accuracy over time jsonPath (string): the p... | the_stack_v2_python_sparse | DeepLearning/pyimagesearch/callbacks/trainingmonitor.py | KaidDuong/ComputerVision_Learn | train | 0 | |
a3033e66590f05ed4405877394789beb87892ace | [
"cache = collections.defaultdict(collections.deque)\nfor i, ch in enumerate(t):\n cache[ch].append(i)\nprev = -1\nfor ch in s:\n positions = cache[ch]\n valid = False\n while positions:\n i = positions.popleft()\n if i > prev:\n prev = i\n valid = True\n br... | <|body_start_0|>
cache = collections.defaultdict(collections.deque)
for i, ch in enumerate(t):
cache[ch].append(i)
prev = -1
for ch in s:
positions = cache[ch]
valid = False
while positions:
i = positions.popleft()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isSubsequence_simple(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cache = collections.defa... | stack_v2_sparse_classes_36k_train_022124 | 1,128 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isSubsequence_simple",
"signature": "def isSubsequence_simple(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
- def isSubsequence_simple(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
- def isSubsequence_simple(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solution:... | d2cbd0aabff2f0b617d34a59b62771f6764adf95 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isSubsequence_simple(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
cache = collections.defaultdict(collections.deque)
for i, ch in enumerate(t):
cache[ch].append(i)
prev = -1
for ch in s:
positions = cache[ch]
valid... | the_stack_v2_python_sparse | 392.判断子序列.py | ChenghaoZHU/LeetCode | train | 0 | |
5c60d785931e3ded631f928274b04f364c560cc2 | [
"super().__init__(dist_sync_on_step=dist_sync_on_step)\nself.threshold = threshold\nself.length = length\nself.reduce_dims = reduce_dims\nself.add_state('hits', default=torch.zeros(length), dist_reduce_fx='sum')\nself.add_state('false_alarms', default=torch.zeros(length), dist_reduce_fx='sum')\nself.add_state('miss... | <|body_start_0|>
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.threshold = threshold
self.length = length
self.reduce_dims = reduce_dims
self.add_state('hits', default=torch.zeros(length), dist_reduce_fx='sum')
self.add_state('false_alarms', default=torch.zer... | Critical Success Index metric. | CSI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSI:
"""Critical Success Index metric."""
def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False):
"""Initilize metric."""
<|body_0|>
def update(self, preds: torch.Tensor, target: torch.Tensor):
"""Update calculations."""
... | stack_v2_sparse_classes_36k_train_022125 | 4,694 | permissive | [
{
"docstring": "Initilize metric.",
"name": "__init__",
"signature": "def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False)"
},
{
"docstring": "Update calculations.",
"name": "update",
"signature": "def update(self, preds: torch.Tensor, target: torch.Te... | 3 | stack_v2_sparse_classes_30k_train_016396 | Implement the Python class `CSI` described below.
Class description:
Critical Success Index metric.
Method signatures and docstrings:
- def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False): Initilize metric.
- def update(self, preds: torch.Tensor, target: torch.Tensor): Update calc... | Implement the Python class `CSI` described below.
Class description:
Critical Success Index metric.
Method signatures and docstrings:
- def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False): Initilize metric.
- def update(self, preds: torch.Tensor, target: torch.Tensor): Update calc... | 655e7dc62f28f142521d3abb7221e4b6860452a4 | <|skeleton|>
class CSI:
"""Critical Success Index metric."""
def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False):
"""Initilize metric."""
<|body_0|>
def update(self, preds: torch.Tensor, target: torch.Tensor):
"""Update calculations."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSI:
"""Critical Success Index metric."""
def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False):
"""Initilize metric."""
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.threshold = threshold
self.length = length
self.re... | the_stack_v2_python_sparse | metrics/cat_scores.py | fmidev/lagrangian-convolutional-neural-network | train | 9 |
e3db6896b45e6b217b8e89c212759539974c17d0 | [
"IMAGE_SIZE = [1920, 1080]\nwith self.subTest(i='1 Channel Image'):\n pass\nwith self.subTest(i='3 Channel [0, 1] Image'):\n pass\nwith self.subTest(i='3 Channel {0..255} Image'):\n color_image = np.ones(shape=(*IMAGE_SIZE, 3), dtype='uint8')\n result = mif(color_image)\n self.assertIn(result, [True,... | <|body_start_0|>
IMAGE_SIZE = [1920, 1080]
with self.subTest(i='1 Channel Image'):
pass
with self.subTest(i='3 Channel [0, 1] Image'):
pass
with self.subTest(i='3 Channel {0..255} Image'):
color_image = np.ones(shape=(*IMAGE_SIZE, 3), dtype='uint8')
... | Testing module.in_frame functionality. | TestModuleInFrame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestModuleInFrame:
"""Testing module.in_frame functionality."""
def test_params(self):
"""Verify can handle range of input types. Parameters ---------- image: ndarray Image to classify."""
<|body_0|>
def test_return(self):
"""Verify returns only expected output t... | stack_v2_sparse_classes_36k_train_022126 | 14,920 | permissive | [
{
"docstring": "Verify can handle range of input types. Parameters ---------- image: ndarray Image to classify.",
"name": "test_params",
"signature": "def test_params(self)"
},
{
"docstring": "Verify returns only expected output types. Returns ------- bool",
"name": "test_return",
"signa... | 2 | stack_v2_sparse_classes_30k_train_009914 | Implement the Python class `TestModuleInFrame` described below.
Class description:
Testing module.in_frame functionality.
Method signatures and docstrings:
- def test_params(self): Verify can handle range of input types. Parameters ---------- image: ndarray Image to classify.
- def test_return(self): Verify returns o... | Implement the Python class `TestModuleInFrame` described below.
Class description:
Testing module.in_frame functionality.
Method signatures and docstrings:
- def test_params(self): Verify can handle range of input types. Parameters ---------- image: ndarray Image to classify.
- def test_return(self): Verify returns o... | 91a6f3f2f621205a500a7d5e13effbd7ba29cc24 | <|skeleton|>
class TestModuleInFrame:
"""Testing module.in_frame functionality."""
def test_params(self):
"""Verify can handle range of input types. Parameters ---------- image: ndarray Image to classify."""
<|body_0|>
def test_return(self):
"""Verify returns only expected output t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestModuleInFrame:
"""Testing module.in_frame functionality."""
def test_params(self):
"""Verify can handle range of input types. Parameters ---------- image: ndarray Image to classify."""
IMAGE_SIZE = [1920, 1080]
with self.subTest(i='1 Channel Image'):
pass
w... | the_stack_v2_python_sparse | vision/unit_tests/test_module.py | MissouriMRR/IARC-2020 | train | 12 |
507a15912ad9c24046dd421af77c99a5a373220c | [
"commands = [TDWUtils.create_empty_room(12, 12)]\nx = -2\nfor i in range(5):\n commands.append(self.get_add_object(object_id=i, model_name='iron_box', position={'x': x, 'y': 0, 'z': 0}))\n x += 0.66\ncommands.extend(TDWUtils.create_avatar(position={'x': 2, 'y': 0.9, 'z': 0.88}, look_at=TDWUtils.VECTOR3_ZERO))... | <|body_start_0|>
commands = [TDWUtils.create_empty_room(12, 12)]
x = -2
for i in range(5):
commands.append(self.get_add_object(object_id=i, model_name='iron_box', position={'x': x, 'y': 0, 'z': 0}))
x += 0.66
commands.extend(TDWUtils.create_avatar(position={'x': 2... | Occlusion | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Occlusion:
def run(self) -> None:
"""Create a scene with a row of objects and an avatar. Get occlusion data. Put a wall in front of the objects and get occlusion data again."""
<|body_0|>
def parse_resp(resp: List[bytes]) -> None:
"""Parse the output data and print t... | stack_v2_sparse_classes_36k_train_022127 | 2,474 | permissive | [
{
"docstring": "Create a scene with a row of objects and an avatar. Get occlusion data. Put a wall in front of the objects and get occlusion data again.",
"name": "run",
"signature": "def run(self) -> None"
},
{
"docstring": "Parse the output data and print the occlusion. :param resp: The respon... | 2 | stack_v2_sparse_classes_30k_val_000886 | Implement the Python class `Occlusion` described below.
Class description:
Implement the Occlusion class.
Method signatures and docstrings:
- def run(self) -> None: Create a scene with a row of objects and an avatar. Get occlusion data. Put a wall in front of the objects and get occlusion data again.
- def parse_resp... | Implement the Python class `Occlusion` described below.
Class description:
Implement the Occlusion class.
Method signatures and docstrings:
- def run(self) -> None: Create a scene with a row of objects and an avatar. Get occlusion data. Put a wall in front of the objects and get occlusion data again.
- def parse_resp... | 9df96fba455b327bb360d8dd5886d8754046c690 | <|skeleton|>
class Occlusion:
def run(self) -> None:
"""Create a scene with a row of objects and an avatar. Get occlusion data. Put a wall in front of the objects and get occlusion data again."""
<|body_0|>
def parse_resp(resp: List[bytes]) -> None:
"""Parse the output data and print t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Occlusion:
def run(self) -> None:
"""Create a scene with a row of objects and an avatar. Get occlusion data. Put a wall in front of the objects and get occlusion data again."""
commands = [TDWUtils.create_empty_room(12, 12)]
x = -2
for i in range(5):
commands.append... | the_stack_v2_python_sparse | Python/example_controllers/visual_perception/occlusion.py | threedworld-mit/tdw | train | 427 | |
dafeb5ffc6685f724a581d5e9d23054b7d161d71 | [
"self.bbox_roi_extractor = build_roi_extractor(bbox_roi_extractor)\nif bbox_head.type == 'Shared2FCBBoxHead':\n bbox_head.type = 'CustomConvFCBBoxHead'\nself.bbox_head = build_head(bbox_head)",
"rois = bbox2roi([res.bboxes for res in sampling_results])\nbbox_results = self._bbox_forward(x, rois)\nlabels, label... | <|body_start_0|>
self.bbox_roi_extractor = build_roi_extractor(bbox_roi_extractor)
if bbox_head.type == 'Shared2FCBBoxHead':
bbox_head.type = 'CustomConvFCBBoxHead'
self.bbox_head = build_head(bbox_head)
<|end_body_0|>
<|body_start_1|>
rois = bbox2roi([res.bboxes for res in ... | CustomROIHead class for OTX. | CustomRoIHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomRoIHead:
"""CustomROIHead class for OTX."""
def init_bbox_head(self, bbox_roi_extractor, bbox_head):
"""Initialize ``bbox_head``."""
<|body_0|>
def _bbox_forward_train(self, x, sampling_results, gt_bboxes, gt_labels, img_metas):
"""Run forward function and ... | stack_v2_sparse_classes_36k_train_022128 | 8,559 | permissive | [
{
"docstring": "Initialize ``bbox_head``.",
"name": "init_bbox_head",
"signature": "def init_bbox_head(self, bbox_roi_extractor, bbox_head)"
},
{
"docstring": "Run forward function and calculate loss for box head in training.",
"name": "_bbox_forward_train",
"signature": "def _bbox_forwa... | 2 | stack_v2_sparse_classes_30k_train_015456 | Implement the Python class `CustomRoIHead` described below.
Class description:
CustomROIHead class for OTX.
Method signatures and docstrings:
- def init_bbox_head(self, bbox_roi_extractor, bbox_head): Initialize ``bbox_head``.
- def _bbox_forward_train(self, x, sampling_results, gt_bboxes, gt_labels, img_metas): Run ... | Implement the Python class `CustomRoIHead` described below.
Class description:
CustomROIHead class for OTX.
Method signatures and docstrings:
- def init_bbox_head(self, bbox_roi_extractor, bbox_head): Initialize ``bbox_head``.
- def _bbox_forward_train(self, x, sampling_results, gt_bboxes, gt_labels, img_metas): Run ... | 80454808b38727e358e8b880043eeac0f18152fb | <|skeleton|>
class CustomRoIHead:
"""CustomROIHead class for OTX."""
def init_bbox_head(self, bbox_roi_extractor, bbox_head):
"""Initialize ``bbox_head``."""
<|body_0|>
def _bbox_forward_train(self, x, sampling_results, gt_bboxes, gt_labels, img_metas):
"""Run forward function and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomRoIHead:
"""CustomROIHead class for OTX."""
def init_bbox_head(self, bbox_roi_extractor, bbox_head):
"""Initialize ``bbox_head``."""
self.bbox_roi_extractor = build_roi_extractor(bbox_roi_extractor)
if bbox_head.type == 'Shared2FCBBoxHead':
bbox_head.type = 'Cust... | the_stack_v2_python_sparse | src/otx/algorithms/detection/adapters/mmdet/models/heads/custom_roi_head.py | openvinotoolkit/training_extensions | train | 397 |
a71af808ac01df99bf508b1e0b0dd115058a219a | [
"notifications = NotificationHandler(request.user.profile.uuid).get(request.query_params.get('notification_type'))\nserialized_notifications = self.serializer_class(notifications, many=True)\nreturn Response(status=status.HTTP_200_OK, data=serialized_notifications.data)",
"notification_uuids = request.data.get('n... | <|body_start_0|>
notifications = NotificationHandler(request.user.profile.uuid).get(request.query_params.get('notification_type'))
serialized_notifications = self.serializer_class(notifications, many=True)
return Response(status=status.HTTP_200_OK, data=serialized_notifications.data)
<|end_body_... | Handle notifications for profile. | NotificationView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationView:
"""Handle notifications for profile."""
def get(self, request, *args, **kwargs):
"""Retrieve list of notifications for an user."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Mark all notifications read."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_022129 | 1,585 | no_license | [
{
"docstring": "Retrieve list of notifications for an user.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Mark all notifications read.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000096 | Implement the Python class `NotificationView` described below.
Class description:
Handle notifications for profile.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Retrieve list of notifications for an user.
- def post(self, request, *args, **kwargs): Mark all notifications read. | Implement the Python class `NotificationView` described below.
Class description:
Handle notifications for profile.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Retrieve list of notifications for an user.
- def post(self, request, *args, **kwargs): Mark all notifications read.
<|skele... | 02bfc05a87462c288d0bc2b4c1f5269668961960 | <|skeleton|>
class NotificationView:
"""Handle notifications for profile."""
def get(self, request, *args, **kwargs):
"""Retrieve list of notifications for an user."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Mark all notifications read."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationView:
"""Handle notifications for profile."""
def get(self, request, *args, **kwargs):
"""Retrieve list of notifications for an user."""
notifications = NotificationHandler(request.user.profile.uuid).get(request.query_params.get('notification_type'))
serialized_notific... | the_stack_v2_python_sparse | notification/views/v1.py | Sunrit07/rozprava-backend | train | 0 |
191ae048e7a87117916fc2381069fa64e52b37d3 | [
"if config_path is not None:\n self.config_path = config_path\nif config_environment is not None:\n self.config_environment = config_environment\nif not hasattr(self, 'action_map'):\n self.action_map = {}\n self.load_config()",
"for config_filename in glob.glob('%s/actions_*.conf' % self.config_path) ... | <|body_start_0|>
if config_path is not None:
self.config_path = config_path
if config_environment is not None:
self.config_environment = config_environment
if not hasattr(self, 'action_map'):
self.action_map = {}
self.load_config()
<|end_body_0|>
... | Start/stop services and functions using configuration data defined in conf/actions_<topic>.conf | ActionHandler | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionHandler:
"""Start/stop services and functions using configuration data defined in conf/actions_<topic>.conf"""
def __init__(self, config_path=None, config_environment=None):
"""Initialize action handler to start system functions :param config_path: full path of configuration da... | stack_v2_sparse_classes_36k_train_022130 | 24,050 | permissive | [
{
"docstring": "Initialize action handler to start system functions :param config_path: full path of configuration data :param config_environment: environment to use (if possible) :return:",
"name": "__init__",
"signature": "def __init__(self, config_path=None, config_environment=None)"
},
{
"do... | 6 | stack_v2_sparse_classes_30k_train_013939 | Implement the Python class `ActionHandler` described below.
Class description:
Start/stop services and functions using configuration data defined in conf/actions_<topic>.conf
Method signatures and docstrings:
- def __init__(self, config_path=None, config_environment=None): Initialize action handler to start system fu... | Implement the Python class `ActionHandler` described below.
Class description:
Start/stop services and functions using configuration data defined in conf/actions_<topic>.conf
Method signatures and docstrings:
- def __init__(self, config_path=None, config_environment=None): Initialize action handler to start system fu... | a0634d180325f6afe3be7f514b4470e47ff5eb75 | <|skeleton|>
class ActionHandler:
"""Start/stop services and functions using configuration data defined in conf/actions_<topic>.conf"""
def __init__(self, config_path=None, config_environment=None):
"""Initialize action handler to start system functions :param config_path: full path of configuration da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionHandler:
"""Start/stop services and functions using configuration data defined in conf/actions_<topic>.conf"""
def __init__(self, config_path=None, config_environment=None):
"""Initialize action handler to start system functions :param config_path: full path of configuration data :param con... | the_stack_v2_python_sparse | src/opnsense/service/modules/processhandler.py | ass-a2s/opnsense-core | train | 2 |
b18156591ffa6a2e2378d6b77eb15b079ccba36c | [
"try:\n\n def generate(vo):\n for exception in list_exceptions(vo=vo):\n yield (dumps(exception, cls=APIEncoder) + '\\n')\n return try_stream(generate(vo=request.environ.get('vo')))\nexcept LifetimeExceptionNotFound as error:\n return generate_http_error_flask(404, 'LifetimeExceptionNotFo... | <|body_start_0|>
try:
def generate(vo):
for exception in list_exceptions(vo=vo):
yield (dumps(exception, cls=APIEncoder) + '\n')
return try_stream(generate(vo=request.environ.get('vo')))
except LifetimeExceptionNotFound as error:
r... | REST APIs for Lifetime Model exception. | LifetimeException | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LifetimeException:
"""REST APIs for Lifetime Model exception."""
def get(self):
"""Retrieve all exceptions. .. :quickref: LifetimeException; Get all exceptions. :resheader Content-Type: application/x-json-stream :status 200: OK. :status 401: Invalid Auth Token. :status 404: Lifetime ... | stack_v2_sparse_classes_36k_train_022131 | 8,648 | permissive | [
{
"docstring": "Retrieve all exceptions. .. :quickref: LifetimeException; Get all exceptions. :resheader Content-Type: application/x-json-stream :status 200: OK. :status 401: Invalid Auth Token. :status 404: Lifetime Exception Not Found. :status 406: Not Acceptable. :status 500: Internal Error.",
"name": "g... | 2 | stack_v2_sparse_classes_30k_train_014407 | Implement the Python class `LifetimeException` described below.
Class description:
REST APIs for Lifetime Model exception.
Method signatures and docstrings:
- def get(self): Retrieve all exceptions. .. :quickref: LifetimeException; Get all exceptions. :resheader Content-Type: application/x-json-stream :status 200: OK... | Implement the Python class `LifetimeException` described below.
Class description:
REST APIs for Lifetime Model exception.
Method signatures and docstrings:
- def get(self): Retrieve all exceptions. .. :quickref: LifetimeException; Get all exceptions. :resheader Content-Type: application/x-json-stream :status 200: OK... | bf33d9441d3b4ff160a392eed56724f635a03fe6 | <|skeleton|>
class LifetimeException:
"""REST APIs for Lifetime Model exception."""
def get(self):
"""Retrieve all exceptions. .. :quickref: LifetimeException; Get all exceptions. :resheader Content-Type: application/x-json-stream :status 200: OK. :status 401: Invalid Auth Token. :status 404: Lifetime ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LifetimeException:
"""REST APIs for Lifetime Model exception."""
def get(self):
"""Retrieve all exceptions. .. :quickref: LifetimeException; Get all exceptions. :resheader Content-Type: application/x-json-stream :status 200: OK. :status 401: Invalid Auth Token. :status 404: Lifetime Exception Not... | the_stack_v2_python_sparse | lib/rucio/web/rest/flaskapi/v1/lifetime_exceptions.py | viveknigam3003/rucio | train | 1 |
dcb3401a9110b7c3383f2bb9d596bd8f0e54e97d | [
"outputs = sorted(StreamAlertOutput.get_all_outputs().keys())\ngenerate_skeleton_parser = generate_subparser(subparser, 'generate-skeleton', description=cls.description, help=cls.description, subcommand=True)\ngenerate_skeleton_parser.add_argument('--services', choices=outputs, nargs='+', metavar='SERVICE', default... | <|body_start_0|>
outputs = sorted(StreamAlertOutput.get_all_outputs().keys())
generate_skeleton_parser = generate_subparser(subparser, 'generate-skeleton', description=cls.description, help=cls.description, subcommand=True)
generate_skeleton_parser.add_argument('--services', choices=outputs, nar... | OutputGenerateSkeletonSubCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputGenerateSkeletonSubCommand:
def setup_subparser(cls, subparser):
"""Add generate-skeleton subparser to the output subparser"""
<|body_0|>
def handler(cls, options, config):
"""Generate a skeleton file for use with set-from-file Args: options (argparse.Namespace... | stack_v2_sparse_classes_36k_train_022132 | 19,044 | permissive | [
{
"docstring": "Add generate-skeleton subparser to the output subparser",
"name": "setup_subparser",
"signature": "def setup_subparser(cls, subparser)"
},
{
"docstring": "Generate a skeleton file for use with set-from-file Args: options (argparse.Namespace): Basically a namedtuple with the servi... | 2 | stack_v2_sparse_classes_30k_train_016767 | Implement the Python class `OutputGenerateSkeletonSubCommand` described below.
Class description:
Implement the OutputGenerateSkeletonSubCommand class.
Method signatures and docstrings:
- def setup_subparser(cls, subparser): Add generate-skeleton subparser to the output subparser
- def handler(cls, options, config): ... | Implement the Python class `OutputGenerateSkeletonSubCommand` described below.
Class description:
Implement the OutputGenerateSkeletonSubCommand class.
Method signatures and docstrings:
- def setup_subparser(cls, subparser): Add generate-skeleton subparser to the output subparser
- def handler(cls, options, config): ... | 75ba140d2e1aa6e903313d88326920adcb8bff45 | <|skeleton|>
class OutputGenerateSkeletonSubCommand:
def setup_subparser(cls, subparser):
"""Add generate-skeleton subparser to the output subparser"""
<|body_0|>
def handler(cls, options, config):
"""Generate a skeleton file for use with set-from-file Args: options (argparse.Namespace... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputGenerateSkeletonSubCommand:
def setup_subparser(cls, subparser):
"""Add generate-skeleton subparser to the output subparser"""
outputs = sorted(StreamAlertOutput.get_all_outputs().keys())
generate_skeleton_parser = generate_subparser(subparser, 'generate-skeleton', description=cl... | the_stack_v2_python_sparse | streamalert_cli/outputs/handler.py | avmi/streamalert | train | 0 | |
bd9b63ac9c6e5868d247f8e088d91c7f31fe7e8a | [
"self.path_entry = path_entry\nif path_entry.index('http://') != 0:\n raise ImportError()\nreturn",
"if is_package(self.path_entry, fullname):\n return HttpImportLoader(self.path_entry)\ntarget = _create_full_path(self.path_entry, fullname)\nif _exist_url(target):\n return HttpImportLoader(self.path_entr... | <|body_start_0|>
self.path_entry = path_entry
if path_entry.index('http://') != 0:
raise ImportError()
return
<|end_body_0|>
<|body_start_1|>
if is_package(self.path_entry, fullname):
return HttpImportLoader(self.path_entry)
target = _create_full_path(sel... | ファインダのサンプルクラス | HttpImportFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpImportFinder:
"""ファインダのサンプルクラス"""
def __init__(self, path_entry):
"""sys.path_hooks に設定された場合、sys.pathの各エントリがpath_entryに入って呼び出されます"""
<|body_0|>
def find_module(self, fullname, path=None):
"""fullname のパッケージやモジュールを見つけたらローダーを返すメソッド"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_022133 | 6,586 | no_license | [
{
"docstring": "sys.path_hooks に設定された場合、sys.pathの各エントリがpath_entryに入って呼び出されます",
"name": "__init__",
"signature": "def __init__(self, path_entry)"
},
{
"docstring": "fullname のパッケージやモジュールを見つけたらローダーを返すメソッド",
"name": "find_module",
"signature": "def find_module(self, fullname, path=None)"
... | 2 | stack_v2_sparse_classes_30k_train_004488 | Implement the Python class `HttpImportFinder` described below.
Class description:
ファインダのサンプルクラス
Method signatures and docstrings:
- def __init__(self, path_entry): sys.path_hooks に設定された場合、sys.pathの各エントリがpath_entryに入って呼び出されます
- def find_module(self, fullname, path=None): fullname のパッケージやモジュールを見つけたらローダーを返すメソッド | Implement the Python class `HttpImportFinder` described below.
Class description:
ファインダのサンプルクラス
Method signatures and docstrings:
- def __init__(self, path_entry): sys.path_hooks に設定された場合、sys.pathの各エントリがpath_entryに入って呼び出されます
- def find_module(self, fullname, path=None): fullname のパッケージやモジュールを見つけたらローダーを返すメソッド
<|skele... | 4abd1a1339387d4d234b57f2e4f3f274b2a1ab0f | <|skeleton|>
class HttpImportFinder:
"""ファインダのサンプルクラス"""
def __init__(self, path_entry):
"""sys.path_hooks に設定された場合、sys.pathの各エントリがpath_entryに入って呼び出されます"""
<|body_0|>
def find_module(self, fullname, path=None):
"""fullname のパッケージやモジュールを見つけたらローダーを返すメソッド"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpImportFinder:
"""ファインダのサンプルクラス"""
def __init__(self, path_entry):
"""sys.path_hooks に設定された場合、sys.pathの各エントリがpath_entryに入って呼び出されます"""
self.path_entry = path_entry
if path_entry.index('http://') != 0:
raise ImportError()
return
def find_module(self, full... | the_stack_v2_python_sparse | perfect_python/Part2/09/http_loader1.py | Machi427/python | train | 1 |
f9ea6e43b6e0c4e2f4f7ef3a04fa22646aaf301c | [
"kSums = [0] * (len(nums) - k + 1)\nkSums[0] = sum(nums[:k])\nfor i in range(1, len(kSums)):\n kSums[i] = kSums[i - 1] - nums[i - 1] + nums[i + k - 1]\nleft, right = ([0] * len(kSums), [0] * len(kSums))\nbest = kSums[0]\nfor i in range(1, len(left)):\n if kSums[i] > best:\n left[i] = i\n best = ... | <|body_start_0|>
kSums = [0] * (len(nums) - k + 1)
kSums[0] = sum(nums[:k])
for i in range(1, len(kSums)):
kSums[i] = kSums[i - 1] - nums[i - 1] + nums[i + k - 1]
left, right = ([0] * len(kSums), [0] * len(kSums))
best = kSums[0]
for i in range(1, len(left)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
"""Idea: for each choice of middle index `mid`, find the index on the left with max k-sums and the index on the right with max k-sums. If these three indices give three subarrays with larger sum, update. Ti... | stack_v2_sparse_classes_36k_train_022134 | 4,102 | no_license | [
{
"docstring": "Idea: for each choice of middle index `mid`, find the index on the left with max k-sums and the index on the right with max k-sums. If these three indices give three subarrays with larger sum, update. Time: O(N) Space: O(N) Issue: Hard to generalize to arbitrary number of subarrays.",
"name"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: Idea: for each choice of middle index `mid`, find the index on the left with max k-sums and the index on t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: Idea: for each choice of middle index `mid`, find the index on the left with max k-sums and the index on t... | 791fc1b43beef89d668788de6d12f5c643431b8f | <|skeleton|>
class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
"""Idea: for each choice of middle index `mid`, find the index on the left with max k-sums and the index on the right with max k-sums. If these three indices give three subarrays with larger sum, update. Ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
"""Idea: for each choice of middle index `mid`, find the index on the left with max k-sums and the index on the right with max k-sums. If these three indices give three subarrays with larger sum, update. Time: O(N) Space... | the_stack_v2_python_sparse | 689.maximum-sum-of-3-non-overlapping-subarrays.py | Code-Wen/LeetCode_Notes | train | 1 | |
7d48adcef57975aa222c5d194a39d816c2b412ef | [
"self.capacity = capacity\nself.queue = queue.Queue()\nself.value = {}\nself.num = {}",
"if self.num[key] > 0:\n self.queue.put(key)\n return self.value[key]\nelse:\n return -1",
"self.queue.put(key)\nself.value[key] = value\nif key in self.num:\n self.num[key] += 1\nelse:\n self.num[key] = 1\nse... | <|body_start_0|>
self.capacity = capacity
self.queue = queue.Queue()
self.value = {}
self.num = {}
<|end_body_0|>
<|body_start_1|>
if self.num[key] > 0:
self.queue.put(key)
return self.value[key]
else:
return -1
<|end_body_1|>
<|body_... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_022135 | 994 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_002548 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | af3faf95c53cb97d0ffa9a93367e27926c0b17ba | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.queue = queue.Queue()
self.value = {}
self.num = {}
def get(self, key):
""":type key: int :rtype: int"""
if self.num[key] > 0:
self.queue.put... | the_stack_v2_python_sparse | 101-150/146.py | ccfarm/leetcode | train | 0 | |
16834b9bdca42b9ba29c235702527a5d2ad97465 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.bttn1 = Button(self, text='I do nothing!')\nself.bttn1.grid()\nself.bttn2 = Button(self)\nself.bttn2.grid()\nself.bttn2.configure(text='Me too')\nself.bttn3 = Button(self)\nself.bttn3.grid()\nself.bttn3['text'] = 'Same here!'"
... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.bttn1 = Button(self, text='I do nothing!')
self.bttn1.grid()
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.configure... | A GUI Application with three buttons | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""A GUI Application with three buttons"""
def __init__(self, master):
"""Initialise the frame"""
<|body_0|>
def create_widgets(self):
"""Create three buttons that do nothing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(App... | stack_v2_sparse_classes_36k_train_022136 | 1,388 | no_license | [
{
"docstring": "Initialise the frame",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create three buttons that do nothing",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010595 | Implement the Python class `Application` described below.
Class description:
A GUI Application with three buttons
Method signatures and docstrings:
- def __init__(self, master): Initialise the frame
- def create_widgets(self): Create three buttons that do nothing | Implement the Python class `Application` described below.
Class description:
A GUI Application with three buttons
Method signatures and docstrings:
- def __init__(self, master): Initialise the frame
- def create_widgets(self): Create three buttons that do nothing
<|skeleton|>
class Application:
"""A GUI Applicat... | 4dbb438ebea00c083194ffcd6d285dc43ebe554b | <|skeleton|>
class Application:
"""A GUI Application with three buttons"""
def __init__(self, master):
"""Initialise the frame"""
<|body_0|>
def create_widgets(self):
"""Create three buttons that do nothing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""A GUI Application with three buttons"""
def __init__(self, master):
"""Initialise the frame"""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create three buttons that do nothing"""
... | the_stack_v2_python_sparse | Python 31 Programs/Ch 10/Lazy Buttons 2.py | kayyali18/Python | train | 0 |
b0bda04516fc4c5dd05634cec49a9023808ee634 | [
"super().__init__(attacker, defender, enemy=enemy)\nself._surf = Drawable(join('moves', 'surf.png'), (0 if not self._enemy else 130, 48 if not self._enemy else 0), (0, 1 if not self._enemy else 0))\nif self._enemy:\n self._surf._image.set_colorkey(self._surf._image.get_at((111, 63)))\nself._fps = 20\nSoundManage... | <|body_start_0|>
super().__init__(attacker, defender, enemy=enemy)
self._surf = Drawable(join('moves', 'surf.png'), (0 if not self._enemy else 130, 48 if not self._enemy else 0), (0, 1 if not self._enemy else 0))
if self._enemy:
self._surf._image.set_colorkey(self._surf._image.get_at... | Surf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Surf:
def __init__(self, attacker, defender, enemy=False):
"""Creates the surf animation. The move extends MoveBase but overwrites most of the logic."""
<|body_0|>
def update(self, ticks):
"""Updates the surf animation. Essentially it moves the surf png diagonally an... | stack_v2_sparse_classes_36k_train_022137 | 3,467 | no_license | [
{
"docstring": "Creates the surf animation. The move extends MoveBase but overwrites most of the logic.",
"name": "__init__",
"signature": "def __init__(self, attacker, defender, enemy=False)"
},
{
"docstring": "Updates the surf animation. Essentially it moves the surf png diagonally anf fill in... | 2 | stack_v2_sparse_classes_30k_train_000008 | Implement the Python class `Surf` described below.
Class description:
Implement the Surf class.
Method signatures and docstrings:
- def __init__(self, attacker, defender, enemy=False): Creates the surf animation. The move extends MoveBase but overwrites most of the logic.
- def update(self, ticks): Updates the surf a... | Implement the Python class `Surf` described below.
Class description:
Implement the Surf class.
Method signatures and docstrings:
- def __init__(self, attacker, defender, enemy=False): Creates the surf animation. The move extends MoveBase but overwrites most of the logic.
- def update(self, ticks): Updates the surf a... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class Surf:
def __init__(self, attacker, defender, enemy=False):
"""Creates the surf animation. The move extends MoveBase but overwrites most of the logic."""
<|body_0|>
def update(self, ticks):
"""Updates the surf animation. Essentially it moves the surf png diagonally an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Surf:
def __init__(self, attacker, defender, enemy=False):
"""Creates the surf animation. The move extends MoveBase but overwrites most of the logic."""
super().__init__(attacker, defender, enemy=enemy)
self._surf = Drawable(join('moves', 'surf.png'), (0 if not self._enemy else 130, 48... | the_stack_v2_python_sparse | pokered/modules/animations/moves/surf.py | surranc20/pokered | train | 44 | |
2c756749c31d3474e2fee1e57144fd8977fdb2e9 | [
"web.header('X-Frame-Options', 'SAMEORIGIN')\nweb.header('X-Content-Type-Options', 'nosniff')\nweb.header('X-XSS-Protection', '1')\nif not session.validate_session():\n raise web.seeother('/login')\nelse:\n module_infos = model.get_new_modules()\n return RENDER.deleteModule(module_infos)",
"web.header('X... | <|body_start_0|>
web.header('X-Frame-Options', 'SAMEORIGIN')
web.header('X-Content-Type-Options', 'nosniff')
web.header('X-XSS-Protection', '1')
if not session.validate_session():
raise web.seeother('/login')
else:
module_infos = model.get_new_modules()
... | This class handles the display of the Delete Module page and the deletion of a module | DeleteMod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteMod:
"""This class handles the display of the Delete Module page and the deletion of a module"""
def GET(self):
"""Handles the display of the Delete Module page"""
<|body_0|>
def POST(self):
"""Handles the deletion of a module"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_022138 | 2,323 | permissive | [
{
"docstring": "Handles the display of the Delete Module page",
"name": "GET",
"signature": "def GET(self)"
},
{
"docstring": "Handles the deletion of a module",
"name": "POST",
"signature": "def POST(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015580 | Implement the Python class `DeleteMod` described below.
Class description:
This class handles the display of the Delete Module page and the deletion of a module
Method signatures and docstrings:
- def GET(self): Handles the display of the Delete Module page
- def POST(self): Handles the deletion of a module | Implement the Python class `DeleteMod` described below.
Class description:
This class handles the display of the Delete Module page and the deletion of a module
Method signatures and docstrings:
- def GET(self): Handles the display of the Delete Module page
- def POST(self): Handles the deletion of a module
<|skelet... | 02b52871a34f580b779ede08750f2d4e887bcf65 | <|skeleton|>
class DeleteMod:
"""This class handles the display of the Delete Module page and the deletion of a module"""
def GET(self):
"""Handles the display of the Delete Module page"""
<|body_0|>
def POST(self):
"""Handles the deletion of a module"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteMod:
"""This class handles the display of the Delete Module page and the deletion of a module"""
def GET(self):
"""Handles the display of the Delete Module page"""
web.header('X-Frame-Options', 'SAMEORIGIN')
web.header('X-Content-Type-Options', 'nosniff')
web.header(... | the_stack_v2_python_sparse | components/handlers/delete_module.py | nus-mtp/cs-modify | train | 1 |
b8ca3a9810671e895dceb3912f4dec792b361b20 | [
"for t in types:\n yield (t + ' ' + location)\n yield (location + ' ' + t)",
"aliases = [court.name]\nif court.court_type is None:\n logger.warning('No court type: %s' % court)\n return court\ntype_info = settings.COURT_TYPES.get_type(court.court_type)\nlocation_levels = type_info['levels']\ntype_alia... | <|body_start_0|>
for t in types:
yield (t + ' ' + location)
yield (location + ' ' + t)
<|end_body_0|>
<|body_start_1|>
aliases = [court.name]
if court.court_type is None:
logger.warning('No court type: %s' % court)
return court
type_info =... | Aliases should make it easier to find matching courts (e.g. Court.objects.get(aliases__contains=...)) | ProcessingStep | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessingStep:
"""Aliases should make it easier to find matching courts (e.g. Court.objects.get(aliases__contains=...))"""
def combine_type_location(self, types, location):
"""Combine type and location in both orders (AG Aachen + Aachen AG)"""
<|body_0|>
def process(sel... | stack_v2_sparse_classes_36k_train_022139 | 2,514 | permissive | [
{
"docstring": "Combine type and location in both orders (AG Aachen + Aachen AG)",
"name": "combine_type_location",
"signature": "def combine_type_location(self, types, location)"
},
{
"docstring": "Generates all possible aliases for court names AG Aachen Aachen AG Aachener AG",
"name": "pro... | 2 | null | Implement the Python class `ProcessingStep` described below.
Class description:
Aliases should make it easier to find matching courts (e.g. Court.objects.get(aliases__contains=...))
Method signatures and docstrings:
- def combine_type_location(self, types, location): Combine type and location in both orders (AG Aache... | Implement the Python class `ProcessingStep` described below.
Class description:
Aliases should make it easier to find matching courts (e.g. Court.objects.get(aliases__contains=...))
Method signatures and docstrings:
- def combine_type_location(self, types, location): Combine type and location in both orders (AG Aache... | 298953d762733e17d4c2d0e8a88c3bd7c414057a | <|skeleton|>
class ProcessingStep:
"""Aliases should make it easier to find matching courts (e.g. Court.objects.get(aliases__contains=...))"""
def combine_type_location(self, types, location):
"""Combine type and location in both orders (AG Aachen + Aachen AG)"""
<|body_0|>
def process(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessingStep:
"""Aliases should make it easier to find matching courts (e.g. Court.objects.get(aliases__contains=...))"""
def combine_type_location(self, types, location):
"""Combine type and location in both orders (AG Aachen + Aachen AG)"""
for t in types:
yield (t + ' ' +... | the_stack_v2_python_sparse | oldp/apps/courts/processing/processing_steps/set_aliases.py | openlegaldata/oldp | train | 80 |
1494ae30acc66a9ea3084f2e0b6ae3a59855fe07 | [
"ret = BaseResponse()\ntry:\n course_id = int(request.data.get('courseid'))\n policy_id = int(request.data.get('policyid'))\n course = models.Course.objects.get(id=course_id)\n price_policy_list = course.price_policy.all()\n price_policy_dict = {}\n for price_policy_item in price_policy_list:\n ... | <|body_start_0|>
ret = BaseResponse()
try:
course_id = int(request.data.get('courseid'))
policy_id = int(request.data.get('policyid'))
course = models.Course.objects.get(id=course_id)
price_policy_list = course.price_policy.all()
price_policy_d... | ShoppingCarViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShoppingCarViewSet:
def post(self, request, *args, **kwargs):
"""将课程添加到购物车 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""删除购物车中的课程 :param request: :param args: :param kwargs: :return:"""
<|bo... | stack_v2_sparse_classes_36k_train_022140 | 5,522 | no_license | [
{
"docstring": "将课程添加到购物车 :param request: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "删除购物车中的课程 :param request: :param args: :param kwargs: :return:",
"name": "delete",
"signature": "def delete(self, re... | 4 | stack_v2_sparse_classes_30k_train_004696 | Implement the Python class `ShoppingCarViewSet` described below.
Class description:
Implement the ShoppingCarViewSet class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): 将课程添加到购物车 :param request: :param args: :param kwargs: :return:
- def delete(self, request, *args, **kwargs): 删除购物车中的... | Implement the Python class `ShoppingCarViewSet` described below.
Class description:
Implement the ShoppingCarViewSet class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): 将课程添加到购物车 :param request: :param args: :param kwargs: :return:
- def delete(self, request, *args, **kwargs): 删除购物车中的... | 0d1fb870a59e21526481c4718a6a17ef2494e726 | <|skeleton|>
class ShoppingCarViewSet:
def post(self, request, *args, **kwargs):
"""将课程添加到购物车 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""删除购物车中的课程 :param request: :param args: :param kwargs: :return:"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShoppingCarViewSet:
def post(self, request, *args, **kwargs):
"""将课程添加到购物车 :param request: :param args: :param kwargs: :return:"""
ret = BaseResponse()
try:
course_id = int(request.data.get('courseid'))
policy_id = int(request.data.get('policyid'))
c... | the_stack_v2_python_sparse | s9day112/s9luffycity/api/views/shoppingcar.py | qiu957919102/oldboy | train | 0 | |
75779c0159c421b457bd4f99ec9d5305540c45d7 | [
"formatted_name = get_formatted_name('janis', 'joplin')\nself.assertEqual(formatted_name, 'Janis Joplin')\npass",
"formatted_name = get_formatted_name('Lucas', 'Guerra', 'Gabriel')\nself.assertEqual(formatted_name, 'Lucas Gabriel Guerra')\npass"
] | <|body_start_0|>
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
pass
<|end_body_0|>
<|body_start_1|>
formatted_name = get_formatted_name('Lucas', 'Guerra', 'Gabriel')
self.assertEqual(formatted_name, 'Lucas Gabriel Guerra'... | Tests for 'name_function.py'. | NamesTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamesTestCase:
"""Tests for 'name_function.py'."""
def test_name_lastname(self):
"""Do names like 'Janis Joplin' work?"""
<|body_0|>
def test_middle_name(self):
"""uso de segundo nombre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
formatted_n... | stack_v2_sparse_classes_36k_train_022141 | 629 | no_license | [
{
"docstring": "Do names like 'Janis Joplin' work?",
"name": "test_name_lastname",
"signature": "def test_name_lastname(self)"
},
{
"docstring": "uso de segundo nombre",
"name": "test_middle_name",
"signature": "def test_middle_name(self)"
}
] | 2 | null | Implement the Python class `NamesTestCase` described below.
Class description:
Tests for 'name_function.py'.
Method signatures and docstrings:
- def test_name_lastname(self): Do names like 'Janis Joplin' work?
- def test_middle_name(self): uso de segundo nombre | Implement the Python class `NamesTestCase` described below.
Class description:
Tests for 'name_function.py'.
Method signatures and docstrings:
- def test_name_lastname(self): Do names like 'Janis Joplin' work?
- def test_middle_name(self): uso de segundo nombre
<|skeleton|>
class NamesTestCase:
"""Tests for 'nam... | 0678e8d884e0641d592a3a457db11cc2085c8b27 | <|skeleton|>
class NamesTestCase:
"""Tests for 'name_function.py'."""
def test_name_lastname(self):
"""Do names like 'Janis Joplin' work?"""
<|body_0|>
def test_middle_name(self):
"""uso de segundo nombre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NamesTestCase:
"""Tests for 'name_function.py'."""
def test_name_lastname(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
pass
def test_middle_name(self):
"... | the_stack_v2_python_sparse | src/testing.py | lucasguerra91/some-python | train | 0 |
9db3af66e6a769fdc0583bbc1813493fe6d89895 | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_unique_id = f'yale_smart_alarm-{description.key}'",
"if TYPE_CHECKING:\n assert self.coordinator.yale, 'Connection to API is missing'\nawait self.hass.async_add_executor_job(self.coordinator.yale.trigger_panic_button)"
] | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f'yale_smart_alarm-{description.key}'
<|end_body_0|>
<|body_start_1|>
if TYPE_CHECKING:
assert self.coordinator.yale, 'Connection to API is missing'
await self... | A Panic button for Yale Smart Alarm. | YalePanicButton | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YalePanicButton:
"""A Panic button for Yale Smart Alarm."""
def __init__(self, coordinator: YaleDataUpdateCoordinator, description: ButtonEntityDescription) -> None:
"""Initialize the plug switch."""
<|body_0|>
async def async_press(self) -> None:
"""Press the bu... | stack_v2_sparse_classes_36k_train_022142 | 1,815 | permissive | [
{
"docstring": "Initialize the plug switch.",
"name": "__init__",
"signature": "def __init__(self, coordinator: YaleDataUpdateCoordinator, description: ButtonEntityDescription) -> None"
},
{
"docstring": "Press the button.",
"name": "async_press",
"signature": "async def async_press(self... | 2 | stack_v2_sparse_classes_30k_train_020149 | Implement the Python class `YalePanicButton` described below.
Class description:
A Panic button for Yale Smart Alarm.
Method signatures and docstrings:
- def __init__(self, coordinator: YaleDataUpdateCoordinator, description: ButtonEntityDescription) -> None: Initialize the plug switch.
- async def async_press(self) ... | Implement the Python class `YalePanicButton` described below.
Class description:
A Panic button for Yale Smart Alarm.
Method signatures and docstrings:
- def __init__(self, coordinator: YaleDataUpdateCoordinator, description: ButtonEntityDescription) -> None: Initialize the plug switch.
- async def async_press(self) ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class YalePanicButton:
"""A Panic button for Yale Smart Alarm."""
def __init__(self, coordinator: YaleDataUpdateCoordinator, description: ButtonEntityDescription) -> None:
"""Initialize the plug switch."""
<|body_0|>
async def async_press(self) -> None:
"""Press the bu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YalePanicButton:
"""A Panic button for Yale Smart Alarm."""
def __init__(self, coordinator: YaleDataUpdateCoordinator, description: ButtonEntityDescription) -> None:
"""Initialize the plug switch."""
super().__init__(coordinator)
self.entity_description = description
self.... | the_stack_v2_python_sparse | homeassistant/components/yale_smart_alarm/button.py | home-assistant/core | train | 35,501 |
99d9f4d25f842c3f114c6eace0c1c3fe77e6af4d | [
"if base_url.endswith('/'):\n base_url = base_url[:-1]\nself.base_url = base_url\nself.verbose = verbose\nself.headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}",
"output = {}\nif url_path.startswith('/'):\n url_path = url_path[1:]\nquery_dict = filter_params or {}\nquery_string =... | <|body_start_0|>
if base_url.endswith('/'):
base_url = base_url[:-1]
self.base_url = base_url
self.verbose = verbose
self.headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
<|end_body_0|>
<|body_start_1|>
output = {}
if url_path.star... | RemoteJSONReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteJSONReader:
def __init__(self, base_url, verbose=False):
"""Initialization. :param base_url: Remote server base url (host:port/root_path). :type base_url: str :param verbose: Flag to get (show) logs. :type verbose: bool"""
<|body_0|>
def get(self, url_path, filter_para... | stack_v2_sparse_classes_36k_train_022143 | 4,997 | no_license | [
{
"docstring": "Initialization. :param base_url: Remote server base url (host:port/root_path). :type base_url: str :param verbose: Flag to get (show) logs. :type verbose: bool",
"name": "__init__",
"signature": "def __init__(self, base_url, verbose=False)"
},
{
"docstring": "Get data from the de... | 2 | stack_v2_sparse_classes_30k_train_002992 | Implement the Python class `RemoteJSONReader` described below.
Class description:
Implement the RemoteJSONReader class.
Method signatures and docstrings:
- def __init__(self, base_url, verbose=False): Initialization. :param base_url: Remote server base url (host:port/root_path). :type base_url: str :param verbose: Fl... | Implement the Python class `RemoteJSONReader` described below.
Class description:
Implement the RemoteJSONReader class.
Method signatures and docstrings:
- def __init__(self, base_url, verbose=False): Initialization. :param base_url: Remote server base url (host:port/root_path). :type base_url: str :param verbose: Fl... | a23537c7230dd86531e597839f3ea3752e990e68 | <|skeleton|>
class RemoteJSONReader:
def __init__(self, base_url, verbose=False):
"""Initialization. :param base_url: Remote server base url (host:port/root_path). :type base_url: str :param verbose: Flag to get (show) logs. :type verbose: bool"""
<|body_0|>
def get(self, url_path, filter_para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteJSONReader:
def __init__(self, base_url, verbose=False):
"""Initialization. :param base_url: Remote server base url (host:port/root_path). :type base_url: str :param verbose: Flag to get (show) logs. :type verbose: bool"""
if base_url.endswith('/'):
base_url = base_url[:-1]
... | the_stack_v2_python_sparse | core/providers/panda.py | PanDAWMS/InVEx | train | 3 | |
a0136f176b762c86bd3915de10a5ac47cac1e8cb | [
"self.schema = generic_ast_graphs.build_ast_graph_schema(self.ast_spec)\nself.edge_types = sorted({graph_edge_util.SAME_IDENTIFIER_EDGE_TYPE, *graph_edge_util.PROGRAM_GRAPH_EDGE_TYPES, *graph_edge_util.schema_edge_types(self.schema), *graph_edge_util.nth_child_edge_types(EDGE_NTH_CHILD_MAX)})\nself.builder = automa... | <|body_start_0|>
self.schema = generic_ast_graphs.build_ast_graph_schema(self.ast_spec)
self.edge_types = sorted({graph_edge_util.SAME_IDENTIFIER_EDGE_TYPE, *graph_edge_util.PROGRAM_GRAPH_EDGE_TYPES, *graph_edge_util.schema_edge_types(self.schema), *graph_edge_util.nth_child_edge_types(EDGE_NTH_CHILD_MA... | Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List of all edge types produced by the encoding. Ge... | ExampleEncodingInfo | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleEncodingInfo:
"""Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List... | stack_v2_sparse_classes_36k_train_022144 | 8,664 | permissive | [
{
"docstring": "Populates non-init fields based on `ast_spec`.",
"name": "__post_init__",
"signature": "def __post_init__(self)"
},
{
"docstring": "Builds an ExampleEncodingInfo object from files. Args: ast_spec_path: Path to a text file containing an AST spec definition. Format is expected to b... | 2 | null | Implement the Python class `ExampleEncodingInfo` described below.
Class description:
Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Ge... | Implement the Python class `ExampleEncodingInfo` described below.
Class description:
Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Ge... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ExampleEncodingInfo:
"""Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleEncodingInfo:
"""Keeps track of objects needed to encode and decode examples. Attributes: ast_spec: AST spec defining how to encode an AST. token_encoder: Subword encoder for encoding syntax tokens. schema: Automaton schema for the produced graphs. Generated automatically. edge_types: List of all edge ... | the_stack_v2_python_sparse | gfsa/datasets/var_misuse/example_definition.py | Jimmy-INL/google-research | train | 1 |
dd505beeab289a88129187e103c67ad510c5a85f | [
"if path is None:\n outpath = os.path.dirname(os.path.abspath(configfile))\nelse:\n outpath = path\nself.config = Configuration(configfile, outpath=path)\nself.pixel = pixel\nself.nside = nside",
"if not self.config.galfile_pixelized:\n raise ValueError('Code only runs with pixelized galfile.')\nself.con... | <|body_start_0|>
if path is None:
outpath = os.path.dirname(os.path.abspath(configfile))
else:
outpath = path
self.config = Configuration(configfile, outpath=path)
self.pixel = pixel
self.nside = nside
<|end_body_0|>
<|body_start_1|>
if not self.c... | Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs. | RunZScanPixelTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunZScanPixelTask:
"""Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `i... | stack_v2_sparse_classes_36k_train_022145 | 10,033 | permissive | [
{
"docstring": "Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int` Healpix pixel to run on. nside: `int` Healpix nside associated with pixel. path: `str`, optional Output path. Default is None, use same absolute path as configfile. percolation_mask... | 2 | stack_v2_sparse_classes_30k_train_007596 | Implement the Python class `RunZScanPixelTask` described below.
Class description:
Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs.
Method signatures and docstrings:
- def __init__(self, configfile, pixel, nside, path=None): Instantiate a RunZScanPixelTask. Parameters ----------... | Implement the Python class `RunZScanPixelTask` described below.
Class description:
Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs.
Method signatures and docstrings:
- def __init__(self, configfile, pixel, nside, path=None): Instantiate a RunZScanPixelTask. Parameters ----------... | d3a8b432c2f3a20aa518a7781c0f2aa315624855 | <|skeleton|>
class RunZScanPixelTask:
"""Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunZScanPixelTask:
"""Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int` Healpix p... | the_stack_v2_python_sparse | redmapper/pipeline/redmappertask.py | erykoff/redmapper | train | 20 |
080f763229dc6df2d2a54807ffab2b120f726c4e | [
"super(PointWiseFeedForward, self).__init__()\nself.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout1 = torch.nn.Dropout(p=dropout_rate)\nself.relu = torch.nn.ReLU()\nself.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout2 = torch.nn.Dropout(p=dropout_r... | <|body_start_0|>
super(PointWiseFeedForward, self).__init__()
self.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)
self.dropout1 = torch.nn.Dropout(p=dropout_rate)
self.relu = torch.nn.ReLU()
self.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=... | PointWise forward Module. Args: torch ([type]): [description] | PointWiseFeedForward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def for... | stack_v2_sparse_classes_36k_train_022146 | 15,823 | permissive | [
{
"docstring": "Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.",
"name": "__init__",
"signature": "def __init__(self, hidden_units, dropout_rate)"
},
{
"docstring": "Forward function. Args: inputs ([type]): [description] Returns: [typ... | 2 | stack_v2_sparse_classes_30k_train_000087 | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module. Args: torch ([type]): [description]
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([... | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module. Args: torch ([type]): [description]
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointWiseFeedForward:
"""PointWise forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
super(PointWiseFeedForward, self).__... | the_stack_v2_python_sparse | beta_rec/models/tisasrec.py | beta-team/beta-recsys | train | 156 |
f1903ce22940930c3bb3a416f3ca6bfdb9c767e6 | [
"if not isinstance(key, ccnpy.crypto.AesGcmKey):\n raise TypeError('key must be ccnpy.crypto.AesGcmKey')\nself._key = key\nself._key_number = key_number",
"if not isinstance(node, ccnpy.flic.Node):\n raise TypeError('node must be ccnpy.flic.Node')\nplaintext = node.serialized_value()\niv = self._key.nonce()... | <|body_start_0|>
if not isinstance(key, ccnpy.crypto.AesGcmKey):
raise TypeError('key must be ccnpy.crypto.AesGcmKey')
self._key = key
self._key_number = key_number
<|end_body_0|>
<|body_start_1|>
if not isinstance(node, ccnpy.flic.Node):
raise TypeError('node mu... | The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node. | PresharedKey | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresharedKey:
"""The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node."""
def __init__(self, key, key_number):
""":param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference ... | stack_v2_sparse_classes_36k_train_022147 | 6,382 | permissive | [
{
"docstring": ":param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference the key",
"name": "__init__",
"signature": "def __init__(self, key, key_number)"
},
{
"docstring": ":param node: A ccnpy.flic.Node :return: (security_ctx, encrypted_node, auth_tag)",
"name": ... | 5 | stack_v2_sparse_classes_30k_train_005508 | Implement the Python class `PresharedKey` described below.
Class description:
The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node.
Method signatures and docstrings:
- def __init__(self, key, key_number): :param key: A ccnpy.crypto.A... | Implement the Python class `PresharedKey` described below.
Class description:
The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node.
Method signatures and docstrings:
- def __init__(self, key, key_number): :param key: A ccnpy.crypto.A... | 20d982e2e3845818fde7f3facdc8cbcdff323dbb | <|skeleton|>
class PresharedKey:
"""The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node."""
def __init__(self, key, key_number):
""":param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PresharedKey:
"""The PresharedKey algorithm. Typically, you will use `PresharedKey.create_manifest(...)` to create a Manifest TLV out of a ccnpy.flic.Node."""
def __init__(self, key, key_number):
""":param key: A ccnpy.crypto.AesGcmKey :param key_number: An integer used to reference the key"""
... | the_stack_v2_python_sparse | ccnpy/flic/presharedkey/PresharedKey.py | mmosko/ccnpy | train | 1 |
8574490d445dad691dc8876ff62e146d544c468d | [
"def Node():\n return defaultdict(Node)\nself.root = Node()",
"self.dict = dict\nfor word in dict:\n cur = self.root\n for w in word:\n cur = cur[w]\n cur['#'] = True",
"def f(d, wd, modified):\n if len(wd) == 0 and d.get('#') and modified:\n return True\n for i, s in enumerate(w... | <|body_start_0|>
def Node():
return defaultdict(Node)
self.root = Node()
<|end_body_0|>
<|body_start_1|>
self.dict = dict
for word in dict:
cur = self.root
for w in word:
cur = cur[w]
cur['#'] = True
<|end_body_1|>
<|body_... | MagicDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def buildDict(self, dict):
"""Build a dictionary through a list of words :type dict: List[str] :rtype: None"""
<|body_1|>
def search(self, word):
"""Return... | stack_v2_sparse_classes_36k_train_022148 | 2,930 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Build a dictionary through a list of words :type dict: List[str] :rtype: None",
"name": "buildDict",
"signature": "def buildDict(self, dict)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_006858 | Implement the Python class `MagicDictionary` described below.
Class description:
Implement the MagicDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def buildDict(self, dict): Build a dictionary through a list of words :type dict: List[str] :rtype: None
... | Implement the Python class `MagicDictionary` described below.
Class description:
Implement the MagicDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def buildDict(self, dict): Build a dictionary through a list of words :type dict: List[str] :rtype: None
... | 69cf9087d5ef48aef9126c8279502488e36f97e3 | <|skeleton|>
class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def buildDict(self, dict):
"""Build a dictionary through a list of words :type dict: List[str] :rtype: None"""
<|body_1|>
def search(self, word):
"""Return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
def Node():
return defaultdict(Node)
self.root = Node()
def buildDict(self, dict):
"""Build a dictionary through a list of words :type dict: List[str] :rtype: None"""
self.d... | the_stack_v2_python_sparse | 676.实现一个魔法字典.py | kailunfan/lcode | train | 0 | |
cc39b4804d0a5c96522215b848e7987b7c9e4866 | [
"self.team_member_position = company_info_models.CompanyMemberPosition.objects.create(title='Team')\nself.team_member_position.sites.add(Site.objects.get_current())\nself.investor_position = company_info_models.CompanyMemberPosition.objects.create(title='Investors')\nself.investor_position.sites.add(Site.objects.ge... | <|body_start_0|>
self.team_member_position = company_info_models.CompanyMemberPosition.objects.create(title='Team')
self.team_member_position.sites.add(Site.objects.get_current())
self.investor_position = company_info_models.CompanyMemberPosition.objects.create(title='Investors')
self.in... | Set up the team model test cases. | TeamModelTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamModelTestCase:
"""Set up the team model test cases."""
def setUp(self):
"""Create Team Member Models"""
<|body_0|>
def test_team_member_models(self):
"""Test that the Team Member Models were created with the correct positions"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_022149 | 1,971 | no_license | [
{
"docstring": "Create Team Member Models",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the Team Member Models were created with the correct positions",
"name": "test_team_member_models",
"signature": "def test_team_member_models(self)"
}
] | 2 | null | Implement the Python class `TeamModelTestCase` described below.
Class description:
Set up the team model test cases.
Method signatures and docstrings:
- def setUp(self): Create Team Member Models
- def test_team_member_models(self): Test that the Team Member Models were created with the correct positions | Implement the Python class `TeamModelTestCase` described below.
Class description:
Set up the team model test cases.
Method signatures and docstrings:
- def setUp(self): Create Team Member Models
- def test_team_member_models(self): Test that the Team Member Models were created with the correct positions
<|skeleton|... | 9219e6c5a49eecd1c66dd1b518640c5d678acab6 | <|skeleton|>
class TeamModelTestCase:
"""Set up the team model test cases."""
def setUp(self):
"""Create Team Member Models"""
<|body_0|>
def test_team_member_models(self):
"""Test that the Team Member Models were created with the correct positions"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamModelTestCase:
"""Set up the team model test cases."""
def setUp(self):
"""Create Team Member Models"""
self.team_member_position = company_info_models.CompanyMemberPosition.objects.create(title='Team')
self.team_member_position.sites.add(Site.objects.get_current())
se... | the_stack_v2_python_sparse | tunobase/corporate/company_info/tests.py | unomena/tunobase | train | 0 |
25d5eb8293e3e062bbb6e32fd6097bfb6cac583c | [
"if tmp_target == 0:\n res.append(copy.deepcopy(possible))\n return\nfor i in range(start, len(candidates)):\n if tmp_target >= candidates[i]:\n possible.append(candidates[i])\n self.combination(candidates, tmp_target - candidates[i], i, possible, res)\n possible.pop()",
"possible = ... | <|body_start_0|>
if tmp_target == 0:
res.append(copy.deepcopy(possible))
return
for i in range(start, len(candidates)):
if tmp_target >= candidates[i]:
possible.append(candidates[i])
self.combination(candidates, tmp_target - candidates[... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combination(self, candidates, tmp_target, start, possible, res):
"""candidates是输入数组 tmp_target是临时需要组合的数 start是开始遍历的下标 possible是一个可能的组合方案 res是最后的解集"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: i... | stack_v2_sparse_classes_36k_train_022150 | 1,038 | permissive | [
{
"docstring": "candidates是输入数组 tmp_target是临时需要组合的数 start是开始遍历的下标 possible是一个可能的组合方案 res是最后的解集",
"name": "combination",
"signature": "def combination(self, candidates, tmp_target, start, possible, res)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_val_000216 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combination(self, candidates, tmp_target, start, possible, res): candidates是输入数组 tmp_target是临时需要组合的数 start是开始遍历的下标 possible是一个可能的组合方案 res是最后的解集
- def combinationSum(self, can... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combination(self, candidates, tmp_target, start, possible, res): candidates是输入数组 tmp_target是临时需要组合的数 start是开始遍历的下标 possible是一个可能的组合方案 res是最后的解集
- def combinationSum(self, can... | 8f65a583912d22861bd6c8182ef044893062cca8 | <|skeleton|>
class Solution:
def combination(self, candidates, tmp_target, start, possible, res):
"""candidates是输入数组 tmp_target是临时需要组合的数 start是开始遍历的下标 possible是一个可能的组合方案 res是最后的解集"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combination(self, candidates, tmp_target, start, possible, res):
"""candidates是输入数组 tmp_target是临时需要组合的数 start是开始遍历的下标 possible是一个可能的组合方案 res是最后的解集"""
if tmp_target == 0:
res.append(copy.deepcopy(possible))
return
for i in range(start, len(candidate... | the_stack_v2_python_sparse | Python/039-combination-sum.py | yangjietadie/Algorithms-LeetCode | train | 0 | |
538a88b28cb8897e8d2856e1a86945dfdc48fce0 | [
"ns = len(s)\nnp = len(p)\ndp = [[False] * (np + 1) for _ in range(ns + 1)]\ndp[0][0] = True\nfor i in range(np):\n if p[i] == '*' and dp[0][i - 1]:\n dp[0][i + 1] = True\nfor i in range(1, ns + 1):\n for j in range(1, np + 1):\n if p[j - 1] == s[i - 1] or p[j - 1] == '.':\n dp[i][j] ... | <|body_start_0|>
ns = len(s)
np = len(p)
dp = [[False] * (np + 1) for _ in range(ns + 1)]
dp[0][0] = True
for i in range(np):
if p[i] == '*' and dp[0][i - 1]:
dp[0][i + 1] = True
for i in range(1, ns + 1):
for j in range(1, np + 1):... | 给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010"""
def isMatch(self, s: str, p: str) -> bool:
... | stack_v2_sparse_classes_36k_train_022151 | 4,476 | permissive | [
{
"docstring": "dp[i][j] 表示 s 的前 i 个是否能被 p 的前 j 个匹配 p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1] If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1]; If p.charAt(j) == '*': here are two sub conditions: //in this case, a* only counts as empty, otherwise is not match - if p.charAt(j-1) != s.charAt(i) : dp[i][... | 2 | stack_v2_sparse_classes_30k_train_020181 | Implement the Python class `Solution` described below.
Class description:
给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010
Method signatures... | Implement the Python class `Solution` described below.
Class description:
给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010
Method signatures... | 9f49766a2b375a6c65f7bfa96df513875ddd772d | <|skeleton|>
class Solution:
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010"""
def isMatch(self, s: str, p: str) -> bool:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 '.' 匹配任意单个字符。 '*' 匹配零个或多个前面的元素。 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 * 参考: https://blog.csdn.net/hk2291976/article/details/51165010"""
def isMatch(self, s: str, p: str) -> bool:
"""dp[i][j]... | the_stack_v2_python_sparse | Leetcode/10.isMatch.py | Song2017/Leetcode_python | train | 1 |
1fff6fd672cf5378a72e036f7925bc9aedeb68af | [
"json_data = json.dumps(data)\nbytes_out = json_data.encode('utf-8')\nself.sock.sendall(encodemsg(bytes_out))",
"bytes_in = self.decoder.decode()\nif not bytes_in:\n return None\njson_data = bytes_in.decode('utf-8')\nreturn json.loads(json_data)"
] | <|body_start_0|>
json_data = json.dumps(data)
bytes_out = json_data.encode('utf-8')
self.sock.sendall(encodemsg(bytes_out))
<|end_body_0|>
<|body_start_1|>
bytes_in = self.decoder.decode()
if not bytes_in:
return None
json_data = bytes_in.decode('utf-8')
... | Application-level communication protocol. We encode the payload dictionary as JSON, then encode the text as utf-8. The resulting bytes are stuffed into a message using the `unpythonic.net.msg` low-level message protocol. This format was chosen instead of pickle to ensure the client and server can talk to each other reg... | ApplevelProtocolMixin | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplevelProtocolMixin:
"""Application-level communication protocol. We encode the payload dictionary as JSON, then encode the text as utf-8. The resulting bytes are stuffed into a message using the `unpythonic.net.msg` low-level message protocol. This format was chosen instead of pickle to ensure... | stack_v2_sparse_classes_36k_train_022152 | 2,472 | permissive | [
{
"docstring": "Send a message using the application-level protocol. data: dict-like.",
"name": "_send",
"signature": "def _send(self, data)"
},
{
"docstring": "Receive a message using the application-level protocol. Returns a dict-like, or `None` if the decoder's message source signaled EOF. Bl... | 2 | stack_v2_sparse_classes_30k_train_009084 | Implement the Python class `ApplevelProtocolMixin` described below.
Class description:
Application-level communication protocol. We encode the payload dictionary as JSON, then encode the text as utf-8. The resulting bytes are stuffed into a message using the `unpythonic.net.msg` low-level message protocol. This format... | Implement the Python class `ApplevelProtocolMixin` described below.
Class description:
Application-level communication protocol. We encode the payload dictionary as JSON, then encode the text as utf-8. The resulting bytes are stuffed into a message using the `unpythonic.net.msg` low-level message protocol. This format... | 4f85957bf64e1b786da0679eade3fe602793ceee | <|skeleton|>
class ApplevelProtocolMixin:
"""Application-level communication protocol. We encode the payload dictionary as JSON, then encode the text as utf-8. The resulting bytes are stuffed into a message using the `unpythonic.net.msg` low-level message protocol. This format was chosen instead of pickle to ensure... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplevelProtocolMixin:
"""Application-level communication protocol. We encode the payload dictionary as JSON, then encode the text as utf-8. The resulting bytes are stuffed into a message using the `unpythonic.net.msg` low-level message protocol. This format was chosen instead of pickle to ensure the client a... | the_stack_v2_python_sparse | unpythonic/net/common.py | Technologicat/unpythonic | train | 81 |
32cd70a184febc8e40a164aea7b6e6ba851c92bf | [
"if related_user and (not user.local or user == related_user):\n return\nnotification = cls.objects.filter(user=user, **kwargs).first()\nif not notification:\n notification = cls.objects.create(user=user, **kwargs)\nif related_user:\n notification.related_users.add(related_user)\nnotification.read = False\... | <|body_start_0|>
if related_user and (not user.local or user == related_user):
return
notification = cls.objects.filter(user=user, **kwargs).first()
if not notification:
notification = cls.objects.create(user=user, **kwargs)
if related_user:
notificati... | you've been tagged, liked, followed, etc | Notification | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Notification:
"""you've been tagged, liked, followed, etc"""
def notify(cls, user, related_user, **kwargs):
"""Create a notification"""
<|body_0|>
def notify_list_item(cls, user, list_item):
"""Group the notifications around the list items, not the user"""
... | stack_v2_sparse_classes_36k_train_022153 | 11,017 | no_license | [
{
"docstring": "Create a notification",
"name": "notify",
"signature": "def notify(cls, user, related_user, **kwargs)"
},
{
"docstring": "Group the notifications around the list items, not the user",
"name": "notify_list_item",
"signature": "def notify_list_item(cls, user, list_item)"
... | 3 | null | Implement the Python class `Notification` described below.
Class description:
you've been tagged, liked, followed, etc
Method signatures and docstrings:
- def notify(cls, user, related_user, **kwargs): Create a notification
- def notify_list_item(cls, user, list_item): Group the notifications around the list items, n... | Implement the Python class `Notification` described below.
Class description:
you've been tagged, liked, followed, etc
Method signatures and docstrings:
- def notify(cls, user, related_user, **kwargs): Create a notification
- def notify_list_item(cls, user, list_item): Group the notifications around the list items, n... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class Notification:
"""you've been tagged, liked, followed, etc"""
def notify(cls, user, related_user, **kwargs):
"""Create a notification"""
<|body_0|>
def notify_list_item(cls, user, list_item):
"""Group the notifications around the list items, not the user"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Notification:
"""you've been tagged, liked, followed, etc"""
def notify(cls, user, related_user, **kwargs):
"""Create a notification"""
if related_user and (not user.local or user == related_user):
return
notification = cls.objects.filter(user=user, **kwargs).first()
... | the_stack_v2_python_sparse | bookwyrm/models/notification.py | bookwyrm-social/bookwyrm | train | 1,398 |
0467959ed285c0e2fba78b57a9a690185cbf87ea | [
"list_tuple = []\nfor user in LoopUser.objects.all().order_by('name_en'):\n list_tuple.append((user.user_id, user.name_en + '-' + str(user.phone_number) + ' (' + str(user.user_id) + ')'))\nreturn list_tuple",
"if self.value():\n return queryset.filter(user_created__id=self.value())\nelse:\n return querys... | <|body_start_0|>
list_tuple = []
for user in LoopUser.objects.all().order_by('name_en'):
list_tuple.append((user.user_id, user.name_en + '-' + str(user.phone_number) + ' (' + str(user.user_id) + ')'))
return list_tuple
<|end_body_0|>
<|body_start_1|>
if self.value():
... | UserListFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.""... | stack_v2_sparse_classes_36k_train_022154 | 25,233 | no_license | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | null | Implement the Python class `UserListFilter` described below.
Class description:
Implement the UserListFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query... | Implement the Python class `UserListFilter` described below.
Class description:
Implement the UserListFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query... | 0b5a62bc34158a8223f166910e349b730475f99d | <|skeleton|>
class UserListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
list... | the_stack_v2_python_sparse | loop/admin.py | digitalgreenorg/dg | train | 14 | |
6c5f4e722c2330d64587a7db185f7bdac3c2cc83 | [
"assert target.n_work_blocks == 1, '\\nTargeted outlier rejection requires a target Ih_table with nblocks = 1'\nself._target_Ih_table_block = target.blocked_data_list[0]\nself._target_Ih_table_block.calc_Ih()\nsuper().__init__(Ih_table, zmax)",
"Ih_table = self._Ih_table_block\ntarget = self._target_Ih_table_bloc... | <|body_start_0|>
assert target.n_work_blocks == 1, '\nTargeted outlier rejection requires a target Ih_table with nblocks = 1'
self._target_Ih_table_block = target.blocked_data_list[0]
self._target_Ih_table_block.calc_Ih()
super().__init__(Ih_table, zmax)
<|end_body_0|>
<|body_start_1|>
... | Implementation of an outlier rejection algorithm against a target. This algorithm requires a target Ih_table in addition to an Ih_table for the dataset under investigation. Normalised deviations are calculated from the intensity values in the target table. | TargetedOutlierRejection | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetedOutlierRejection:
"""Implementation of an outlier rejection algorithm against a target. This algorithm requires a target Ih_table in addition to an Ih_table for the dataset under investigation. Normalised deviations are calculated from the intensity values in the target table."""
def... | stack_v2_sparse_classes_36k_train_022155 | 17,042 | permissive | [
{
"docstring": "Set a target Ih_table and run the outlier rejection.",
"name": "__init__",
"signature": "def __init__(self, Ih_table, zmax, target)"
},
{
"docstring": "Add indices (w.r.t. the Ih_table data) to self._outlier_indices.",
"name": "_do_outlier_rejection",
"signature": "def _d... | 2 | null | Implement the Python class `TargetedOutlierRejection` described below.
Class description:
Implementation of an outlier rejection algorithm against a target. This algorithm requires a target Ih_table in addition to an Ih_table for the dataset under investigation. Normalised deviations are calculated from the intensity ... | Implement the Python class `TargetedOutlierRejection` described below.
Class description:
Implementation of an outlier rejection algorithm against a target. This algorithm requires a target Ih_table in addition to an Ih_table for the dataset under investigation. Normalised deviations are calculated from the intensity ... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class TargetedOutlierRejection:
"""Implementation of an outlier rejection algorithm against a target. This algorithm requires a target Ih_table in addition to an Ih_table for the dataset under investigation. Normalised deviations are calculated from the intensity values in the target table."""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetedOutlierRejection:
"""Implementation of an outlier rejection algorithm against a target. This algorithm requires a target Ih_table in addition to an Ih_table for the dataset under investigation. Normalised deviations are calculated from the intensity values in the target table."""
def __init__(sel... | the_stack_v2_python_sparse | src/dials/algorithms/scaling/outlier_rejection.py | dials/dials | train | 71 |
f8c979dc2a86bdba5795c04bcda89b43fb15d39c | [
"if not is_exe(exe_path):\n msg = '{0} is not an executable'.format(exe_path)\n raise NotExecutableError(msg)\nself._exe_path = exe_path",
"assert lreads != rreads\nself.__build_cmd(lreads, rreads, threads, outdir, prefix)\nif dry_run:\n return self._cmd\nif not os.path.exists(self._outdirname):\n os.... | <|body_start_0|>
if not is_exe(exe_path):
msg = '{0} is not an executable'.format(exe_path)
raise NotExecutableError(msg)
self._exe_path = exe_path
<|end_body_0|>
<|body_start_1|>
assert lreads != rreads
self.__build_cmd(lreads, rreads, threads, outdir, prefix)
... | class for working with paired end read assembly tool Flash | Flash | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flash:
"""class for working with paired end read assembly tool Flash"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, lreads, rreads, threads, outdir, prefix, dry_run=False):
"""Run Flash to merge passed read... | stack_v2_sparse_classes_36k_train_022156 | 3,856 | permissive | [
{
"docstring": "Instantiate with location of executable",
"name": "__init__",
"signature": "def __init__(self, exe_path)"
},
{
"docstring": "Run Flash to merge passed read files - lreads - forward reads - rreads - reverse reads - threads - number of threads for flash to use - outdir - output dir... | 3 | stack_v2_sparse_classes_30k_train_010818 | Implement the Python class `Flash` described below.
Class description:
class for working with paired end read assembly tool Flash
Method signatures and docstrings:
- def __init__(self, exe_path): Instantiate with location of executable
- def run(self, lreads, rreads, threads, outdir, prefix, dry_run=False): Run Flash... | Implement the Python class `Flash` described below.
Class description:
class for working with paired end read assembly tool Flash
Method signatures and docstrings:
- def __init__(self, exe_path): Instantiate with location of executable
- def run(self, lreads, rreads, threads, outdir, prefix, dry_run=False): Run Flash... | a3c64198aad3709a5c4d969f48ae0af11fdc25db | <|skeleton|>
class Flash:
"""class for working with paired end read assembly tool Flash"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, lreads, rreads, threads, outdir, prefix, dry_run=False):
"""Run Flash to merge passed read... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Flash:
"""class for working with paired end read assembly tool Flash"""
def __init__(self, exe_path):
"""Instantiate with location of executable"""
if not is_exe(exe_path):
msg = '{0} is not an executable'.format(exe_path)
raise NotExecutableError(msg)
self... | the_stack_v2_python_sparse | metapy/pycits/flash.py | peterthorpe5/public_scripts | train | 35 |
a7892dc12a88394e2821ea3c611baf18cad1862b | [
"_, self._tts_service = split_entity_id(config[CONF_TTS_SERVICE])\nself._media_player = config[CONF_MEDIA_PLAYER]\nself._language = config.get(ATTR_LANGUAGE)",
"_LOGGER.debug(\"%s '%s' on %s\", self._tts_service, message, self._media_player)\ndata = {ATTR_MESSAGE: message, ATTR_ENTITY_ID: self._media_player}\nif ... | <|body_start_0|>
_, self._tts_service = split_entity_id(config[CONF_TTS_SERVICE])
self._media_player = config[CONF_MEDIA_PLAYER]
self._language = config.get(ATTR_LANGUAGE)
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug("%s '%s' on %s", self._tts_service, message, self._media_player)
... | The TTS Notification Service. | TTSNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TTSNotificationService:
"""The TTS Notification Service."""
def __init__(self, config):
"""Initialize the service."""
<|body_0|>
async def async_send_message(self, message='', **kwargs):
"""Call TTS service to speak the notification."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_022157 | 1,836 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Call TTS service to speak the notification.",
"name": "async_send_message",
"signature": "async def async_send_message(self, message='', **kwargs)"
}
] | 2 | null | Implement the Python class `TTSNotificationService` described below.
Class description:
The TTS Notification Service.
Method signatures and docstrings:
- def __init__(self, config): Initialize the service.
- async def async_send_message(self, message='', **kwargs): Call TTS service to speak the notification. | Implement the Python class `TTSNotificationService` described below.
Class description:
The TTS Notification Service.
Method signatures and docstrings:
- def __init__(self, config): Initialize the service.
- async def async_send_message(self, message='', **kwargs): Call TTS service to speak the notification.
<|skele... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class TTSNotificationService:
"""The TTS Notification Service."""
def __init__(self, config):
"""Initialize the service."""
<|body_0|>
async def async_send_message(self, message='', **kwargs):
"""Call TTS service to speak the notification."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TTSNotificationService:
"""The TTS Notification Service."""
def __init__(self, config):
"""Initialize the service."""
_, self._tts_service = split_entity_id(config[CONF_TTS_SERVICE])
self._media_player = config[CONF_MEDIA_PLAYER]
self._language = config.get(ATTR_LANGUAGE)
... | the_stack_v2_python_sparse | homeassistant/components/tts/notify.py | BenWoodford/home-assistant | train | 11 |
5000fda8105ff72aaead8c4dcdafe2f7327ebf73 | [
"\"\"\" Corner Cases \"\"\"\nif list is None or len(list) == 0 or (len(list) == 1 and target not in list):\n return 0\nstart, end = (0, len(list) - 1)\nfirst_index = self.search_first(list, start, end, target)\nif first_index == -1:\n return 0\nlast_index = self.search_last(list, start, end, target)\nreturn l... | <|body_start_0|>
""" Corner Cases """
if list is None or len(list) == 0 or (len(list) == 1 and target not in list):
return 0
start, end = (0, len(list) - 1)
first_index = self.search_first(list, start, end, target)
if first_index == -1:
return 0
la... | 解题思路:sorted list + locate target => binary search; 用两次binary search 来找first and last existence of that element; total_occurrence = last_index - first_index + 1 Time: O(logn) Space: O(1) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""解题思路:sorted list + locate target => binary search; 用两次binary search 来找first and last existence of that element; total_occurrence = last_index - first_index + 1 Time: O(logn) Space: O(1)"""
def totalOccurrence(self, list, target):
"""input: int[] list, int target return: ... | stack_v2_sparse_classes_36k_train_022158 | 2,676 | no_license | [
{
"docstring": "input: int[] list, int target return: int",
"name": "totalOccurrence",
"signature": "def totalOccurrence(self, list, target)"
},
{
"docstring": "helper function to search the first index of element in list :param l: :param start: :param end: :param t: :return:",
"name": "sear... | 3 | stack_v2_sparse_classes_30k_train_021129 | Implement the Python class `Solution` described below.
Class description:
解题思路:sorted list + locate target => binary search; 用两次binary search 来找first and last existence of that element; total_occurrence = last_index - first_index + 1 Time: O(logn) Space: O(1)
Method signatures and docstrings:
- def totalOccurrence(se... | Implement the Python class `Solution` described below.
Class description:
解题思路:sorted list + locate target => binary search; 用两次binary search 来找first and last existence of that element; total_occurrence = last_index - first_index + 1 Time: O(logn) Space: O(1)
Method signatures and docstrings:
- def totalOccurrence(se... | c34b55bb42dc44a9026a902f6afcc018b4154662 | <|skeleton|>
class Solution:
"""解题思路:sorted list + locate target => binary search; 用两次binary search 来找first and last existence of that element; total_occurrence = last_index - first_index + 1 Time: O(logn) Space: O(1)"""
def totalOccurrence(self, list, target):
"""input: int[] list, int target return: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""解题思路:sorted list + locate target => binary search; 用两次binary search 来找first and last existence of that element; total_occurrence = last_index - first_index + 1 Time: O(logn) Space: O(1)"""
def totalOccurrence(self, list, target):
"""input: int[] list, int target return: int"""
... | the_stack_v2_python_sparse | Algorithm/Total Occurrence - Lai.py | superpigBB/Happy-Coding | train | 0 |
1a1f487c8c78374555209bfbe45d42956e7372c1 | [
"from collections import defaultdict\nfreq = defaultdict(int)\nleft = res = 0\nright = -1\nwhile left < len(s):\n if right + 1 < len(s) and freq[s[right + 1]] == 0:\n right += 1\n freq[s[right]] += 1\n else:\n freq[s[left]] -= 1\n left += 1\n res = max(res, right - left + 1)\nre... | <|body_start_0|>
from collections import defaultdict
freq = defaultdict(int)
left = res = 0
right = -1
while left < len(s):
if right + 1 < len(s) and freq[s[right + 1]] == 0:
right += 1
freq[s[right]] += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""滑动过程:滑动窗口两边界均是闭的,最开始滑动窗口里没有元素,即 left=0,right=-1 res用来存储最常窗口的长度,初始为0,移动窗口,窗口向右判断下一个元素是否已存在于 窗口内,如果不存在,则将该元素加入到窗口中,即 right+1,左边界不动,如果窗口内已经存在该元素 则将该元素加入到窗口中,即right+1,同时将窗口左边界移到窗口中已存在的元素的位置,即 left+1 知道窗口中重复的元素的位置为止,同时将窗口左边界移到窗口中... | stack_v2_sparse_classes_36k_train_022159 | 3,872 | no_license | [
{
"docstring": "滑动过程:滑动窗口两边界均是闭的,最开始滑动窗口里没有元素,即 left=0,right=-1 res用来存储最常窗口的长度,初始为0,移动窗口,窗口向右判断下一个元素是否已存在于 窗口内,如果不存在,则将该元素加入到窗口中,即 right+1,左边界不动,如果窗口内已经存在该元素 则将该元素加入到窗口中,即right+1,同时将窗口左边界移到窗口中已存在的元素的位置,即 left+1 知道窗口中重复的元素的位置为止,同时将窗口左边界移到窗口中已经存在的元素为止, 即left+1直到窗口中重复元素的位置为止,重复上述步骤,在窗口滑动的过程中,每得到一个新的窗口 都将与res中的值比较,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s: str) -> int: 滑动过程:滑动窗口两边界均是闭的,最开始滑动窗口里没有元素,即 left=0,right=-1 res用来存储最常窗口的长度,初始为0,移动窗口,窗口向右判断下一个元素是否已存在于 窗口内,如果不存在,则将该元素加入到窗口中,即 right+1,左边界不... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s: str) -> int: 滑动过程:滑动窗口两边界均是闭的,最开始滑动窗口里没有元素,即 left=0,right=-1 res用来存储最常窗口的长度,初始为0,移动窗口,窗口向右判断下一个元素是否已存在于 窗口内,如果不存在,则将该元素加入到窗口中,即 right+1,左边界不... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""滑动过程:滑动窗口两边界均是闭的,最开始滑动窗口里没有元素,即 left=0,right=-1 res用来存储最常窗口的长度,初始为0,移动窗口,窗口向右判断下一个元素是否已存在于 窗口内,如果不存在,则将该元素加入到窗口中,即 right+1,左边界不动,如果窗口内已经存在该元素 则将该元素加入到窗口中,即right+1,同时将窗口左边界移到窗口中已存在的元素的位置,即 left+1 知道窗口中重复的元素的位置为止,同时将窗口左边界移到窗口中... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""滑动过程:滑动窗口两边界均是闭的,最开始滑动窗口里没有元素,即 left=0,right=-1 res用来存储最常窗口的长度,初始为0,移动窗口,窗口向右判断下一个元素是否已存在于 窗口内,如果不存在,则将该元素加入到窗口中,即 right+1,左边界不动,如果窗口内已经存在该元素 则将该元素加入到窗口中,即right+1,同时将窗口左边界移到窗口中已存在的元素的位置,即 left+1 知道窗口中重复的元素的位置为止,同时将窗口左边界移到窗口中已经存在的元素为止, 即le... | the_stack_v2_python_sparse | LeetCode_practice/0003_lengthOfLongestSubstring.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
74fa173d6a5761ccb915e0f878c486d17a9e8bee | [
"left, right = (0, len(nums) - 1)\nwhile left <= right:\n mid = left + (right - left) // 2\n if mid < len(nums) - 1 and nums[mid] < nums[mid + 1]:\n left = mid + 1\n else:\n right = mid - 1\nreturn left",
"left, right = (0, len(nums) - 1)\nwhile left < right:\n mid = left + right >> 1\n ... | <|body_start_0|>
left, right = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if mid < len(nums) - 1 and nums[mid] < nums[mid + 1]:
left = mid + 1
else:
right = mid - 1
return left
<|end_body_0|>
<|bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_v2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (0, len(nums) - 1)
... | stack_v2_sparse_classes_36k_train_022160 | 1,806 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement",
"signature": "def findPeakElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement_v2",
"signature": "def findPeakElement_v2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_v2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_v2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_v2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
left, right = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if mid < len(nums) - 1 and nums[mid] < nums[mid + 1]:
left = mid + 1
... | the_stack_v2_python_sparse | src/lt_162.py | oxhead/CodingYourWay | train | 0 | |
ff81283a9bc4217662025b1889a121a47da752d4 | [
"self.wall = []\nself.wall_lst = []\nself.empty_lst = []\nself.map = call_parse()\nself.mc_gyver = McGyver(13, 13)\nself.murdock = Murdock(1, 1)\nself.lst_obj = []\nself.append_obj()\nprint(self.lst_obj)",
"obj = self.random_position()\nneedle = Object(obj[0][0], obj[0][1])\nether = Object(obj[1][0], obj[1][1])\n... | <|body_start_0|>
self.wall = []
self.wall_lst = []
self.empty_lst = []
self.map = call_parse()
self.mc_gyver = McGyver(13, 13)
self.murdock = Murdock(1, 1)
self.lst_obj = []
self.append_obj()
print(self.lst_obj)
<|end_body_0|>
<|body_start_1|>
... | creation of the maze | Maze | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Maze:
"""creation of the maze"""
def __init__(self):
"""positioning elements of the maze"""
<|body_0|>
def append_obj(self):
"""positioning inventory objects"""
<|body_1|>
def random_position(self):
"""positioning of walls and empty spaces"""... | stack_v2_sparse_classes_36k_train_022161 | 1,733 | no_license | [
{
"docstring": "positioning elements of the maze",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "positioning inventory objects",
"name": "append_obj",
"signature": "def append_obj(self)"
},
{
"docstring": "positioning of walls and empty spaces",
"na... | 3 | stack_v2_sparse_classes_30k_train_004151 | Implement the Python class `Maze` described below.
Class description:
creation of the maze
Method signatures and docstrings:
- def __init__(self): positioning elements of the maze
- def append_obj(self): positioning inventory objects
- def random_position(self): positioning of walls and empty spaces | Implement the Python class `Maze` described below.
Class description:
creation of the maze
Method signatures and docstrings:
- def __init__(self): positioning elements of the maze
- def append_obj(self): positioning inventory objects
- def random_position(self): positioning of walls and empty spaces
<|skeleton|>
cla... | f83cec2e5c49662fd9f19534d015b8a3ec836808 | <|skeleton|>
class Maze:
"""creation of the maze"""
def __init__(self):
"""positioning elements of the maze"""
<|body_0|>
def append_obj(self):
"""positioning inventory objects"""
<|body_1|>
def random_position(self):
"""positioning of walls and empty spaces"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Maze:
"""creation of the maze"""
def __init__(self):
"""positioning elements of the maze"""
self.wall = []
self.wall_lst = []
self.empty_lst = []
self.map = call_parse()
self.mc_gyver = McGyver(13, 13)
self.murdock = Murdock(1, 1)
self.lst_o... | the_stack_v2_python_sparse | maze.py | donkansigui/OCR_P3 | train | 0 |
51ef069cb38f78f5308fda858cfe01d649064a2b | [
"super(LoCoBotGripper, self).__init__(configs=configs)\nself._gripper_state_lock = threading.RLock()\nself._gripper_state = None\nself.wait_time = wait_time\nself.pub_gripper_close = rospy.Publisher(self.configs.GRIPPER.ROSTOPIC_GRIPPER_CLOSE, Empty, queue_size=1)\nself.pub_gripper_open = rospy.Publisher(self.confi... | <|body_start_0|>
super(LoCoBotGripper, self).__init__(configs=configs)
self._gripper_state_lock = threading.RLock()
self._gripper_state = None
self.wait_time = wait_time
self.pub_gripper_close = rospy.Publisher(self.configs.GRIPPER.ROSTOPIC_GRIPPER_CLOSE, Empty, queue_size=1)
... | Interface for gripper | LoCoBotGripper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoCoBotGripper:
"""Interface for gripper"""
def __init__(self, configs, wait_time=3):
"""The constructor for LoCoBotGripper class. :param configs: configurations for gripper :param wait_time: waiting time for opening/closing gripper :type configs: YACS CfgNode :type wait_time: float"... | stack_v2_sparse_classes_36k_train_022162 | 3,311 | permissive | [
{
"docstring": "The constructor for LoCoBotGripper class. :param configs: configurations for gripper :param wait_time: waiting time for opening/closing gripper :type configs: YACS CfgNode :type wait_time: float",
"name": "__init__",
"signature": "def __init__(self, configs, wait_time=3)"
},
{
"d... | 6 | null | Implement the Python class `LoCoBotGripper` described below.
Class description:
Interface for gripper
Method signatures and docstrings:
- def __init__(self, configs, wait_time=3): The constructor for LoCoBotGripper class. :param configs: configurations for gripper :param wait_time: waiting time for opening/closing gr... | Implement the Python class `LoCoBotGripper` described below.
Class description:
Interface for gripper
Method signatures and docstrings:
- def __init__(self, configs, wait_time=3): The constructor for LoCoBotGripper class. :param configs: configurations for gripper :param wait_time: waiting time for opening/closing gr... | b334b60842271d9d8f4ed7a97bc4e5efe8bb72d6 | <|skeleton|>
class LoCoBotGripper:
"""Interface for gripper"""
def __init__(self, configs, wait_time=3):
"""The constructor for LoCoBotGripper class. :param configs: configurations for gripper :param wait_time: waiting time for opening/closing gripper :type configs: YACS CfgNode :type wait_time: float"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoCoBotGripper:
"""Interface for gripper"""
def __init__(self, configs, wait_time=3):
"""The constructor for LoCoBotGripper class. :param configs: configurations for gripper :param wait_time: waiting time for opening/closing gripper :type configs: YACS CfgNode :type wait_time: float"""
su... | the_stack_v2_python_sparse | src/pyrobot/locobot/gripper.py | facebookresearch/pyrobot | train | 2,314 |
a416b86ff83ecb463976c984fce39daf1025bf30 | [
"user_id = request.user.id\norder = Order.objects.filter(user_id=user_id)\nserializer = OrderSerializer(order, many=True)\nreturn Response({'result': serializer.data, 'message': 'Done', 'status': True}, status=status.HTTP_200_OK)",
"data = request.data\naddress_id = request.query_params['address_id']\ndata['user'... | <|body_start_0|>
user_id = request.user.id
order = Order.objects.filter(user_id=user_id)
serializer = OrderSerializer(order, many=True)
return Response({'result': serializer.data, 'message': 'Done', 'status': True}, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
data... | OrderApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderApi:
def details(self, request, *args, **kwargs):
"""list user orders"""
<|body_0|>
def create_order(self, request):
"""create order takes address_id as query parameter to be inserted while creating the order"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_022163 | 1,654 | no_license | [
{
"docstring": "list user orders",
"name": "details",
"signature": "def details(self, request, *args, **kwargs)"
},
{
"docstring": "create order takes address_id as query parameter to be inserted while creating the order",
"name": "create_order",
"signature": "def create_order(self, requ... | 2 | stack_v2_sparse_classes_30k_train_018470 | Implement the Python class `OrderApi` described below.
Class description:
Implement the OrderApi class.
Method signatures and docstrings:
- def details(self, request, *args, **kwargs): list user orders
- def create_order(self, request): create order takes address_id as query parameter to be inserted while creating th... | Implement the Python class `OrderApi` described below.
Class description:
Implement the OrderApi class.
Method signatures and docstrings:
- def details(self, request, *args, **kwargs): list user orders
- def create_order(self, request): create order takes address_id as query parameter to be inserted while creating th... | 51f87a1ceddde427028f7229efcbe6abd730c655 | <|skeleton|>
class OrderApi:
def details(self, request, *args, **kwargs):
"""list user orders"""
<|body_0|>
def create_order(self, request):
"""create order takes address_id as query parameter to be inserted while creating the order"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderApi:
def details(self, request, *args, **kwargs):
"""list user orders"""
user_id = request.user.id
order = Order.objects.filter(user_id=user_id)
serializer = OrderSerializer(order, many=True)
return Response({'result': serializer.data, 'message': 'Done', 'status': ... | the_stack_v2_python_sparse | orders/api/views.py | mofahmi99/e_commerce | train | 0 | |
65002aace760765a89473ed2c043414b53aea129 | [
"self.processed_policies = self.process_policies(policies)\nppa = PysbPreassembler(self.statements)\nppa.replace_activities()\nif reverse_effects:\n ppa.add_reverse_effects()\nself.statements = ppa.statements\nif policies is not None:\n global_policies = self.policies\n if isinstance(policies, basestring):... | <|body_start_0|>
self.processed_policies = self.process_policies(policies)
ppa = PysbPreassembler(self.statements)
ppa.replace_activities()
if reverse_effects:
ppa.add_reverse_effects()
self.statements = ppa.statements
if policies is not None:
glob... | KamiAssembler | [
"BSD-2-Clause",
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KamiAssembler:
def make_model(self, policies=None, initial_conditions=True, reverse_effects=False):
"""Assemble the Kami model from the collected INDRA Statements. This method assembles a Kami model from the set of INDRA Statements. The assembled model is both returned and set as the ass... | stack_v2_sparse_classes_36k_train_022164 | 13,903 | permissive | [
{
"docstring": "Assemble the Kami model from the collected INDRA Statements. This method assembles a Kami model from the set of INDRA Statements. The assembled model is both returned and set as the assembler's model argument. Parameters ---------- policies : Optional[Union[str, dict]] A string or dictionary of ... | 3 | stack_v2_sparse_classes_30k_train_008615 | Implement the Python class `KamiAssembler` described below.
Class description:
Implement the KamiAssembler class.
Method signatures and docstrings:
- def make_model(self, policies=None, initial_conditions=True, reverse_effects=False): Assemble the Kami model from the collected INDRA Statements. This method assembles ... | Implement the Python class `KamiAssembler` described below.
Class description:
Implement the KamiAssembler class.
Method signatures and docstrings:
- def make_model(self, policies=None, initial_conditions=True, reverse_effects=False): Assemble the Kami model from the collected INDRA Statements. This method assembles ... | 6d6ca1174792b6c5a05cbf3afcb9f138fabcec6a | <|skeleton|>
class KamiAssembler:
def make_model(self, policies=None, initial_conditions=True, reverse_effects=False):
"""Assemble the Kami model from the collected INDRA Statements. This method assembles a Kami model from the set of INDRA Statements. The assembled model is both returned and set as the ass... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KamiAssembler:
def make_model(self, policies=None, initial_conditions=True, reverse_effects=False):
"""Assemble the Kami model from the collected INDRA Statements. This method assembles a Kami model from the set of INDRA Statements. The assembled model is both returned and set as the assembler's model... | the_stack_v2_python_sparse | indra/assemblers/kami/assembler.py | sorgerlab/indra | train | 158 | |
9957ec17cc4db5fbca2c2e9e4f48c31d8c24b27e | [
"factory = None\nif holiday == Holiday.CHRISTMAS:\n factory = ChristmasFactory\nif holiday == Holiday.HALLOWEEN:\n factory = HalloweenFactory\nif holiday == Holiday.EASTER:\n factory = EasterFactory\nif factory is None or factory.get_instance() is None:\n raise TypeError('Invalid Holiday Type!')\nreturn... | <|body_start_0|>
factory = None
if holiday == Holiday.CHRISTMAS:
factory = ChristmasFactory
if holiday == Holiday.HALLOWEEN:
factory = HalloweenFactory
if holiday == Holiday.EASTER:
factory = EasterFactory
if factory is None or factory.get_inst... | FactoryMapping would map the holiday to the appropriate factory class. | FactoryMapping | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryMapping:
"""FactoryMapping would map the holiday to the appropriate factory class."""
def map_to_factory(holiday: Holiday) -> FestiveSeasonFactory:
"""Returns the factory class base on the specific holiday."""
<|body_0|>
def map_attributes(order: dict) -> dict:
... | stack_v2_sparse_classes_36k_train_022165 | 2,339 | no_license | [
{
"docstring": "Returns the factory class base on the specific holiday.",
"name": "map_to_factory",
"signature": "def map_to_factory(holiday: Holiday) -> FestiveSeasonFactory"
},
{
"docstring": "Maps all the attributes into specific enums type or boolean or number, and return the dict after mapp... | 3 | stack_v2_sparse_classes_30k_train_005843 | Implement the Python class `FactoryMapping` described below.
Class description:
FactoryMapping would map the holiday to the appropriate factory class.
Method signatures and docstrings:
- def map_to_factory(holiday: Holiday) -> FestiveSeasonFactory: Returns the factory class base on the specific holiday.
- def map_att... | Implement the Python class `FactoryMapping` described below.
Class description:
FactoryMapping would map the holiday to the appropriate factory class.
Method signatures and docstrings:
- def map_to_factory(holiday: Holiday) -> FestiveSeasonFactory: Returns the factory class base on the specific holiday.
- def map_att... | c1736d33d0535502c65de86affe1c4ea151c09cb | <|skeleton|>
class FactoryMapping:
"""FactoryMapping would map the holiday to the appropriate factory class."""
def map_to_factory(holiday: Holiday) -> FestiveSeasonFactory:
"""Returns the factory class base on the specific holiday."""
<|body_0|>
def map_attributes(order: dict) -> dict:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactoryMapping:
"""FactoryMapping would map the holiday to the appropriate factory class."""
def map_to_factory(holiday: Holiday) -> FestiveSeasonFactory:
"""Returns the factory class base on the specific holiday."""
factory = None
if holiday == Holiday.CHRISTMAS:
fact... | the_stack_v2_python_sparse | Assignments/Assignment2/factory_mapping.py | Bmeimei/3532_A01075487 | train | 1 |
8d772396131565177312237141b44fe60eec4fe6 | [
"po = LoginPage(self.driver)\npo.open()\npo.login_action(13727086330, 'qwe123')\npo2 = CodPrintPage(self.driver)\npo2.to_codprint_link()\npo2.breedname_search_case()\nself.assertEqual(po2.result_batch_no(), 'ZZ2018053100006')\nfunction.insert_img(self.driver, 'codeprint_search_result.png')",
"po = LoginPage(self.... | <|body_start_0|>
po = LoginPage(self.driver)
po.open()
po.login_action(13727086330, 'qwe123')
po2 = CodPrintPage(self.driver)
po2.to_codprint_link()
po2.breedname_search_case()
self.assertEqual(po2.result_batch_no(), 'ZZ2018053100006')
function.insert_img(... | 赋码打印页面测试 | CodePrintTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodePrintTest:
"""赋码打印页面测试"""
def test_codeprint_search(self):
"""测试搜索功能"""
<|body_0|>
def test_codeprint(self):
"""赋码打印接口测试"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
po = LoginPage(self.driver)
po.open()
po.login_action(13... | stack_v2_sparse_classes_36k_train_022166 | 1,789 | no_license | [
{
"docstring": "测试搜索功能",
"name": "test_codeprint_search",
"signature": "def test_codeprint_search(self)"
},
{
"docstring": "赋码打印接口测试",
"name": "test_codeprint",
"signature": "def test_codeprint(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009174 | Implement the Python class `CodePrintTest` described below.
Class description:
赋码打印页面测试
Method signatures and docstrings:
- def test_codeprint_search(self): 测试搜索功能
- def test_codeprint(self): 赋码打印接口测试 | Implement the Python class `CodePrintTest` described below.
Class description:
赋码打印页面测试
Method signatures and docstrings:
- def test_codeprint_search(self): 测试搜索功能
- def test_codeprint(self): 赋码打印接口测试
<|skeleton|>
class CodePrintTest:
"""赋码打印页面测试"""
def test_codeprint_search(self):
"""测试搜索功能"""
... | 5913459fcb00d2013f195e814c752bc2af09b2ff | <|skeleton|>
class CodePrintTest:
"""赋码打印页面测试"""
def test_codeprint_search(self):
"""测试搜索功能"""
<|body_0|>
def test_codeprint(self):
"""赋码打印接口测试"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodePrintTest:
"""赋码打印页面测试"""
def test_codeprint_search(self):
"""测试搜索功能"""
po = LoginPage(self.driver)
po.open()
po.login_action(13727086330, 'qwe123')
po2 = CodPrintPage(self.driver)
po2.to_codprint_link()
po2.breedname_search_case()
self.... | the_stack_v2_python_sparse | sy54315/test_case/codeprint_case.py | baozha2003/Sy54315_test | train | 0 |
56fb6cd8a74996931c872731685247cf68c183fa | [
"super(MultiHeadedAttention, self).__init__()\nassert n_feat % n_head == 0\nself.d_k = n_feat // n_head\nself.h = n_head\nself.linear_q = nn.Linear(n_feat, n_feat, bias=True)\nself.linear_kv = nn.Linear(n_feat, n_feat, bias=True)\nself.linear_out = nn.Linear(n_feat, n_feat, bias=True)\nself.attn = None\nself.dropou... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert n_feat % n_head == 0
self.d_k = n_feat // n_head
self.h = n_head
self.linear_q = nn.Linear(n_feat, n_feat, bias=True)
self.linear_kv = nn.Linear(n_feat, n_feat, bias=True)
self.linear_out = nn.Li... | Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. | MultiHeadedAttention | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
"""Construct an MultiHeadedAttention object."""
<|body_... | stack_v2_sparse_classes_36k_train_022167 | 7,675 | permissive | [
{
"docstring": "Construct an MultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate)"
},
{
"docstring": "Transform query, key and value. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor (#batc... | 4 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
Method signatures and docstrings:
- def __init__(self, n_head, n_feat, dropout_rate): Con... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
Method signatures and docstrings:
- def __init__(self, n_head, n_feat, dropout_rate): Con... | e2f834dd60e7939672c1795b4ac62e89ad0bca49 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
"""Construct an MultiHeadedAttention object."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
"""Construct an MultiHeadedAttention object."""
super(MultiHeadedAtt... | the_stack_v2_python_sparse | speech/conformer/pytorch/src/layers/attention.py | graphcore/examples | train | 311 |
482542497663e061ab2177f1218180cc5546846f | [
"super().define(spec)\nspec.expose_inputs(SimAnnealingWorkChain)\nspec.expose_inputs(Cp2kBindingEnergyWorkChain, exclude=['structure', 'molecule'])\nspec.outline(cls.run_sim_annealing, cls.run_cp2k_binding_energy, cls.return_results)\nspec.expose_outputs(SimAnnealingWorkChain, namespace='ff')\nspec.expose_outputs(C... | <|body_start_0|>
super().define(spec)
spec.expose_inputs(SimAnnealingWorkChain)
spec.expose_inputs(Cp2kBindingEnergyWorkChain, exclude=['structure', 'molecule'])
spec.outline(cls.run_sim_annealing, cls.run_cp2k_binding_energy, cls.return_results)
spec.expose_outputs(SimAnnealingW... | A workchain that combines SimAnnealing & Cp2kBindingEnergy | BindingSiteWorkChain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BindingSiteWorkChain:
"""A workchain that combines SimAnnealing & Cp2kBindingEnergy"""
def define(cls, spec):
"""Define workflow specification."""
<|body_0|>
def run_sim_annealing(self):
"""Run SimAnnealing"""
<|body_1|>
def run_cp2k_binding_energy(s... | stack_v2_sparse_classes_36k_train_022168 | 2,438 | permissive | [
{
"docstring": "Define workflow specification.",
"name": "define",
"signature": "def define(cls, spec)"
},
{
"docstring": "Run SimAnnealing",
"name": "run_sim_annealing",
"signature": "def run_sim_annealing(self)"
},
{
"docstring": "Pass the ouptput molecule's geometry to Cp2kBin... | 4 | stack_v2_sparse_classes_30k_train_003374 | Implement the Python class `BindingSiteWorkChain` described below.
Class description:
A workchain that combines SimAnnealing & Cp2kBindingEnergy
Method signatures and docstrings:
- def define(cls, spec): Define workflow specification.
- def run_sim_annealing(self): Run SimAnnealing
- def run_cp2k_binding_energy(self)... | Implement the Python class `BindingSiteWorkChain` described below.
Class description:
A workchain that combines SimAnnealing & Cp2kBindingEnergy
Method signatures and docstrings:
- def define(cls, spec): Define workflow specification.
- def run_sim_annealing(self): Run SimAnnealing
- def run_cp2k_binding_energy(self)... | 6bf08fa42e545dadf889ea8095d7fcdd8d1be15c | <|skeleton|>
class BindingSiteWorkChain:
"""A workchain that combines SimAnnealing & Cp2kBindingEnergy"""
def define(cls, spec):
"""Define workflow specification."""
<|body_0|>
def run_sim_annealing(self):
"""Run SimAnnealing"""
<|body_1|>
def run_cp2k_binding_energy(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BindingSiteWorkChain:
"""A workchain that combines SimAnnealing & Cp2kBindingEnergy"""
def define(cls, spec):
"""Define workflow specification."""
super().define(spec)
spec.expose_inputs(SimAnnealingWorkChain)
spec.expose_inputs(Cp2kBindingEnergyWorkChain, exclude=['struct... | the_stack_v2_python_sparse | aiida_lsmo/workchains/binding_site.py | lsmo-epfl/aiida-lsmo | train | 3 |
aac2fa9f8cd5c2eb57b0670cb2cb08a7f9438b05 | [
"super(PorcupineDemo, self).__init__()\nself._library_path = library_path\nself._model_file_path = model_file_path\nself._keyword_file_paths = keyword_file_paths\nself._sensitivity = float(sensitivity)\nself._input_device_index = input_device_index\nself._output_path = output_path\nif self._output_path is not None:... | <|body_start_0|>
super(PorcupineDemo, self).__init__()
self._library_path = library_path
self._model_file_path = model_file_path
self._keyword_file_paths = keyword_file_paths
self._sensitivity = float(sensitivity)
self._input_device_index = input_device_index
self... | Demo class for wake word detection (aka Porcupine) library. It creates an input audio stream from a microphone, monitors it, and upon detecting the specified wake word(s) prints the detection time and index of wake word on console. It optionally saves the recorded audio into a file for further review. | PorcupineDemo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PorcupineDemo:
"""Demo class for wake word detection (aka Porcupine) library. It creates an input audio stream from a microphone, monitors it, and upon detecting the specified wake word(s) prints the detection time and index of wake word on console. It optionally saves the recorded audio into a f... | stack_v2_sparse_classes_36k_train_022169 | 7,336 | permissive | [
{
"docstring": "Constructor. :param library_path: Absolute path to Porcupine's dynamic library. :param model_file_path: Absolute path to the model parameter file. :param keyword_file_paths: List of absolute paths to keyword files. :param sensitivity: Sensitivity parameter. For more information refer to 'include... | 3 | null | Implement the Python class `PorcupineDemo` described below.
Class description:
Demo class for wake word detection (aka Porcupine) library. It creates an input audio stream from a microphone, monitors it, and upon detecting the specified wake word(s) prints the detection time and index of wake word on console. It optio... | Implement the Python class `PorcupineDemo` described below.
Class description:
Demo class for wake word detection (aka Porcupine) library. It creates an input audio stream from a microphone, monitors it, and upon detecting the specified wake word(s) prints the detection time and index of wake word on console. It optio... | 0e8eae0f01487f15589c0daa2cf7ca3c6f3b8ad3 | <|skeleton|>
class PorcupineDemo:
"""Demo class for wake word detection (aka Porcupine) library. It creates an input audio stream from a microphone, monitors it, and upon detecting the specified wake word(s) prints the detection time and index of wake word on console. It optionally saves the recorded audio into a f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PorcupineDemo:
"""Demo class for wake word detection (aka Porcupine) library. It creates an input audio stream from a microphone, monitors it, and upon detecting the specified wake word(s) prints the detection time and index of wake word on console. It optionally saves the recorded audio into a file for furth... | the_stack_v2_python_sparse | chapter_7_design/porcupine/wake_porcupine.py | jim-schwoebel/voicebook | train | 363 |
a6492be33e952fb31b6901fba5e39764e532bec5 | [
"self.zoneType = zoneType\nif number is None:\n number = 1\nself.number = number\nConditionalEffect.__init__(self, HasCards(self.zoneType), thenEffects)",
"zone = context.loadZone(self.zoneType)\ncards = zone[:self.number]\nevent = CardsEvent(cards, zone, context)\ncoroutine = ConditionalEffect.performEffects(... | <|body_start_0|>
self.zoneType = zoneType
if number is None:
number = 1
self.number = number
ConditionalEffect.__init__(self, HasCards(self.zoneType), thenEffects)
<|end_body_0|>
<|body_start_1|>
zone = context.loadZone(self.zoneType)
cards = zone[:self.numbe... | Represents an effect to Look at the top Card of a zone | LookAtTop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookAtTop:
"""Represents an effect to Look at the top Card of a zone"""
def __init__(self, zoneType, thenEffects, number=None):
"""Initialize the Effect with the zone to look at"""
<|body_0|>
def performEffects(self, context):
"""Perform the Game Effect"""
... | stack_v2_sparse_classes_36k_train_022170 | 1,028 | no_license | [
{
"docstring": "Initialize the Effect with the zone to look at",
"name": "__init__",
"signature": "def __init__(self, zoneType, thenEffects, number=None)"
},
{
"docstring": "Perform the Game Effect",
"name": "performEffects",
"signature": "def performEffects(self, context)"
}
] | 2 | null | Implement the Python class `LookAtTop` described below.
Class description:
Represents an effect to Look at the top Card of a zone
Method signatures and docstrings:
- def __init__(self, zoneType, thenEffects, number=None): Initialize the Effect with the zone to look at
- def performEffects(self, context): Perform the ... | Implement the Python class `LookAtTop` described below.
Class description:
Represents an effect to Look at the top Card of a zone
Method signatures and docstrings:
- def __init__(self, zoneType, thenEffects, number=None): Initialize the Effect with the zone to look at
- def performEffects(self, context): Perform the ... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class LookAtTop:
"""Represents an effect to Look at the top Card of a zone"""
def __init__(self, zoneType, thenEffects, number=None):
"""Initialize the Effect with the zone to look at"""
<|body_0|>
def performEffects(self, context):
"""Perform the Game Effect"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LookAtTop:
"""Represents an effect to Look at the top Card of a zone"""
def __init__(self, zoneType, thenEffects, number=None):
"""Initialize the Effect with the zone to look at"""
self.zoneType = zoneType
if number is None:
number = 1
self.number = number
... | the_stack_v2_python_sparse | src/Game/Effects/look_at_top.py | dfwarden/DeckBuilding | train | 0 |
f479d0c043e81307d4dad56f088843eb3c85a051 | [
"while True and (not self.server.shutdown_flag):\n raw = self.request.recv(1024)\n if not raw:\n break\n raw = bytearray(raw)\n self.handle_raw_line(raw)",
"try:\n self.request.sendall(event.create_response())\nexcept Exception as exp:\n _LOGGER.error('Exception caught while responding to... | <|body_start_0|>
while True and (not self.server.shutdown_flag):
raw = self.request.recv(1024)
if not raw:
break
raw = bytearray(raw)
self.handle_raw_line(raw)
<|end_body_0|>
<|body_start_1|>
try:
self.request.sendall(event.cre... | Class for TCP Handling. | SIATCPHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SIATCPHandler:
"""Class for TCP Handling."""
def handle(self) -> None:
"""Overwritten method for the RequestHandler."""
<|body_0|>
def respond(self, event: SIAEvent) -> None:
"""Respond to the event."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_022171 | 2,823 | permissive | [
{
"docstring": "Overwritten method for the RequestHandler.",
"name": "handle",
"signature": "def handle(self) -> None"
},
{
"docstring": "Respond to the event.",
"name": "respond",
"signature": "def respond(self, event: SIAEvent) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_val_001162 | Implement the Python class `SIATCPHandler` described below.
Class description:
Class for TCP Handling.
Method signatures and docstrings:
- def handle(self) -> None: Overwritten method for the RequestHandler.
- def respond(self, event: SIAEvent) -> None: Respond to the event. | Implement the Python class `SIATCPHandler` described below.
Class description:
Class for TCP Handling.
Method signatures and docstrings:
- def handle(self) -> None: Overwritten method for the RequestHandler.
- def respond(self, event: SIAEvent) -> None: Respond to the event.
<|skeleton|>
class SIATCPHandler:
"""... | c5394b7e2911d154b0aac5600cd57878ec7094ac | <|skeleton|>
class SIATCPHandler:
"""Class for TCP Handling."""
def handle(self) -> None:
"""Overwritten method for the RequestHandler."""
<|body_0|>
def respond(self, event: SIAEvent) -> None:
"""Respond to the event."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SIATCPHandler:
"""Class for TCP Handling."""
def handle(self) -> None:
"""Overwritten method for the RequestHandler."""
while True and (not self.server.shutdown_flag):
raw = self.request.recv(1024)
if not raw:
break
raw = bytearray(raw)
... | the_stack_v2_python_sparse | src/pysiaalarm/sync/handler.py | mach0gr/pysiaalarm | train | 1 |
d158a7f9f2641e6ccb36c672e550d541b8dfb087 | [
"super(AXI4StreamChannel, self).__init__(glbl, data_width)\nvmax = 2 ** data_width\nself.valid = Signal(bool(0))\nself.data = Signal(intbv(vmax - 1)[data_width:])\nself.accept = Signal(bool(1))",
"sti = upstream\nclock, reset = (self.clock, self.reset)\naccept = Signal(bool(1))\n\n@always_comb\ndef beh_acc():\n ... | <|body_start_0|>
super(AXI4StreamChannel, self).__init__(glbl, data_width)
vmax = 2 ** data_width
self.valid = Signal(bool(0))
self.data = Signal(intbv(vmax - 1)[data_width:])
self.accept = Signal(bool(1))
<|end_body_0|>
<|body_start_1|>
sti = upstream
clock, res... | AXI4StreamChannel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AXI4StreamChannel:
def __init__(self, glbl, data_width=32):
"""Interface for AXI4 streaming protocol"""
<|body_0|>
def register(self, upstream):
"""register the upstream interface Register the upstream interface to this interface (this (self) is the downstream interf... | stack_v2_sparse_classes_36k_train_022172 | 4,412 | permissive | [
{
"docstring": "Interface for AXI4 streaming protocol",
"name": "__init__",
"signature": "def __init__(self, glbl, data_width=32)"
},
{
"docstring": "register the upstream interface Register the upstream interface to this interface (this (self) is the downstream interface).",
"name": "regist... | 2 | null | Implement the Python class `AXI4StreamChannel` described below.
Class description:
Implement the AXI4StreamChannel class.
Method signatures and docstrings:
- def __init__(self, glbl, data_width=32): Interface for AXI4 streaming protocol
- def register(self, upstream): register the upstream interface Register the upst... | Implement the Python class `AXI4StreamChannel` described below.
Class description:
Implement the AXI4StreamChannel class.
Method signatures and docstrings:
- def __init__(self, glbl, data_width=32): Interface for AXI4 streaming protocol
- def register(self, upstream): register the upstream interface Register the upst... | 47edf23d975c3b04e8d4d0399137ead7580e0ef2 | <|skeleton|>
class AXI4StreamChannel:
def __init__(self, glbl, data_width=32):
"""Interface for AXI4 streaming protocol"""
<|body_0|>
def register(self, upstream):
"""register the upstream interface Register the upstream interface to this interface (this (self) is the downstream interf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AXI4StreamChannel:
def __init__(self, glbl, data_width=32):
"""Interface for AXI4 streaming protocol"""
super(AXI4StreamChannel, self).__init__(glbl, data_width)
vmax = 2 ** data_width
self.valid = Signal(bool(0))
self.data = Signal(intbv(vmax - 1)[data_width:])
... | the_stack_v2_python_sparse | rhea/system/stream/axi4st.py | Vikram9866/rhea | train | 1 | |
a15f63dd362349fca5197bf65413ea649ea3f6d0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Quota()",
"from .storage_plan_information import StoragePlanInformation\nfrom .storage_plan_information import StoragePlanInformation\nfields: Dict[str, Callable[[Any], None]] = {'deleted': lambda n: setattr(self, 'deleted', n.get_int_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Quota()
<|end_body_0|>
<|body_start_1|>
from .storage_plan_information import StoragePlanInformation
from .storage_plan_information import StoragePlanInformation
fields: Dict[str... | Quota | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quota:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Quota"""
... | stack_v2_sparse_classes_36k_train_022173 | 3,964 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Quota",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse_n... | 3 | null | Implement the Python class `Quota` described below.
Class description:
Implement the Quota class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | Implement the Python class `Quota` described below.
Class description:
Implement the Quota class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Quota:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Quota"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Quota:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Quota"""
if not pars... | the_stack_v2_python_sparse | msgraph/generated/models/quota.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0fb5f5cd9dcb6d1d0e5aae56dba831fdc3c5a320 | [
"admin_password = 'oldslice129690TuG72Bgj2'\nresponse = self.server_behaviors.create_active_server(admin_pass=admin_password)\nserver = response.entity\nself.resources.add(server.id, self.servers_client.delete_server)\nself.assertEqual(admin_password, server.admin_pass)\nremote_client = self.server_behaviors.get_re... | <|body_start_0|>
admin_password = 'oldslice129690TuG72Bgj2'
response = self.server_behaviors.create_active_server(admin_pass=admin_password)
server = response.entity
self.resources.add(server.id, self.servers_client.delete_server)
self.assertEqual(admin_password, server.admin_pas... | ServersTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServersTest:
def test_create_server_with_admin_password(self):
"""Creates a server with an admin password to be used as root's password. This will set the server that is created with the root password of oldslice129690TuG72Bgj2. Calls cloudcafe's server behaviors get remote instance clie... | stack_v2_sparse_classes_36k_train_022174 | 7,533 | permissive | [
{
"docstring": "Creates a server with an admin password to be used as root's password. This will set the server that is created with the root password of oldslice129690TuG72Bgj2. Calls cloudcafe's server behaviors get remote instance client with the password to validate that it can authenticate wth password. Th... | 3 | null | Implement the Python class `ServersTest` described below.
Class description:
Implement the ServersTest class.
Method signatures and docstrings:
- def test_create_server_with_admin_password(self): Creates a server with an admin password to be used as root's password. This will set the server that is created with the r... | Implement the Python class `ServersTest` described below.
Class description:
Implement the ServersTest class.
Method signatures and docstrings:
- def test_create_server_with_admin_password(self): Creates a server with an admin password to be used as root's password. This will set the server that is created with the r... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class ServersTest:
def test_create_server_with_admin_password(self):
"""Creates a server with an admin password to be used as root's password. This will set the server that is created with the root password of oldslice129690TuG72Bgj2. Calls cloudcafe's server behaviors get remote instance clie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServersTest:
def test_create_server_with_admin_password(self):
"""Creates a server with an admin password to be used as root's password. This will set the server that is created with the root password of oldslice129690TuG72Bgj2. Calls cloudcafe's server behaviors get remote instance client with the pa... | the_stack_v2_python_sparse | cloudroast/compute/api/servers/test_servers.py | RULCSoft/cloudroast | train | 1 | |
992658b84677062ff4b79b224b1df0f0bd5719f8 | [
"if node[u'type'] == NodeType.DUT:\n adj_mac0, adj_mac1, if_pci0, if_pci1 = L3fwdTest.get_adj_mac(nodes, node, if1, if2)\n list_cores = [int(item) for item in lcores_list.split(u',')]\n nb_cores = int(nb_cores)\n index = 0\n port_config = ''\n for port in range(0, 2):\n for queue in range(0... | <|body_start_0|>
if node[u'type'] == NodeType.DUT:
adj_mac0, adj_mac1, if_pci0, if_pci1 = L3fwdTest.get_adj_mac(nodes, node, if1, if2)
list_cores = [int(item) for item in lcores_list.split(u',')]
nb_cores = int(nb_cores)
index = 0
port_config = ''
... | Test the DPDK l3fwd performance. | L3fwdTest | [
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L3fwdTest:
"""Test the DPDK l3fwd performance."""
def start_l3fwd(nodes, node, if1, if2, lcores_list, nb_cores, queue_nums, jumbo_frames):
"""Execute the l3fwd on the dut_node. :param nodes: All the nodes info in the topology file. :param node: DUT node. :param if1: The test link int... | stack_v2_sparse_classes_36k_train_022175 | 6,295 | permissive | [
{
"docstring": "Execute the l3fwd on the dut_node. :param nodes: All the nodes info in the topology file. :param node: DUT node. :param if1: The test link interface 1. :param if2: The test link interface 2. :param lcores_list: The lcore list string for the l3fwd routing :param nb_cores: The cores number for the... | 3 | stack_v2_sparse_classes_30k_train_017728 | Implement the Python class `L3fwdTest` described below.
Class description:
Test the DPDK l3fwd performance.
Method signatures and docstrings:
- def start_l3fwd(nodes, node, if1, if2, lcores_list, nb_cores, queue_nums, jumbo_frames): Execute the l3fwd on the dut_node. :param nodes: All the nodes info in the topology f... | Implement the Python class `L3fwdTest` described below.
Class description:
Test the DPDK l3fwd performance.
Method signatures and docstrings:
- def start_l3fwd(nodes, node, if1, if2, lcores_list, nb_cores, queue_nums, jumbo_frames): Execute the l3fwd on the dut_node. :param nodes: All the nodes info in the topology f... | 2156583b4e66f2c3c35903c854b1823b76a4e9a6 | <|skeleton|>
class L3fwdTest:
"""Test the DPDK l3fwd performance."""
def start_l3fwd(nodes, node, if1, if2, lcores_list, nb_cores, queue_nums, jumbo_frames):
"""Execute the l3fwd on the dut_node. :param nodes: All the nodes info in the topology file. :param node: DUT node. :param if1: The test link int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class L3fwdTest:
"""Test the DPDK l3fwd performance."""
def start_l3fwd(nodes, node, if1, if2, lcores_list, nb_cores, queue_nums, jumbo_frames):
"""Execute the l3fwd on the dut_node. :param nodes: All the nodes info in the topology file. :param node: DUT node. :param if1: The test link interface 1. :pa... | the_stack_v2_python_sparse | resources/libraries/python/DPDK/L3fwdTest.py | nidhyanandhan/csit | train | 0 |
0116bdc5f6efcf46a510532a671916891f7bd2f8 | [
"def serialize(root):\n if not root:\n return\n nodes.append(root.val)\n serialize(root.left)\n serialize(root.right)\nnodes = []\nserialize(root)\nreturn ' '.join(map(str, nodes))",
"def deseralize(stop):\n if inorder and inorder[-1] != stop:\n root = TreeNode(preorder.pop())\n ... | <|body_start_0|>
def serialize(root):
if not root:
return
nodes.append(root.val)
serialize(root.left)
serialize(root.right)
nodes = []
serialize(root)
return ' '.join(map(str, nodes))
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_022176 | 1,379 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_018386 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | fa02b469344cf7c82510249fba9aa59ae0cb4cc0 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def serialize(root):
if not root:
return
nodes.append(root.val)
serialize(root.left)
serialize(root.right)
nodes =... | the_stack_v2_python_sparse | SerializeandDeserializeBST3.py | jiangshen95/UbuntuLeetCode | train | 0 | |
3be18b63166b8b629f38f48d3f1ef200feb5b42e | [
"cmd = 'sudo yum --color=never -y install %s' % ' '.join(packages)\noutput_expects = ['\\\\[sudo\\\\] password for .*:', 'No package (.*) available.', 'file .* from install of .* conflicts with file from package (.*?)\\r\\n', 'Error: (.*?) conflicts with .*?\\r\\n', 'Processing Conflict: .* conflicts (.*?)\\r\\n', ... | <|body_start_0|>
cmd = 'sudo yum --color=never -y install %s' % ' '.join(packages)
output_expects = ['\\[sudo\\] password for .*:', 'No package (.*) available.', 'file .* from install of .* conflicts with file from package (.*?)\r\n', 'Error: (.*?) conflicts with .*?\r\n', 'Processing Conflict: .* confl... | RedhatPackagerMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedhatPackagerMixin:
def _install(self, packages, time_out):
"""Attempts to install packages. Returns OK if the packages are installed or a result code if a recoverable-error occurred. Raises an exception if a non-recoverable error or timeout occurs."""
<|body_0|>
def _remov... | stack_v2_sparse_classes_36k_train_022177 | 16,357 | permissive | [
{
"docstring": "Attempts to install packages. Returns OK if the packages are installed or a result code if a recoverable-error occurred. Raises an exception if a non-recoverable error or timeout occurs.",
"name": "_install",
"signature": "def _install(self, packages, time_out)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_008347 | Implement the Python class `RedhatPackagerMixin` described below.
Class description:
Implement the RedhatPackagerMixin class.
Method signatures and docstrings:
- def _install(self, packages, time_out): Attempts to install packages. Returns OK if the packages are installed or a result code if a recoverable-error occur... | Implement the Python class `RedhatPackagerMixin` described below.
Class description:
Implement the RedhatPackagerMixin class.
Method signatures and docstrings:
- def _install(self, packages, time_out): Attempts to install packages. Returns OK if the packages are installed or a result code if a recoverable-error occur... | 4288b8f78250cc3a1c93b019e2c3b4bf78df177c | <|skeleton|>
class RedhatPackagerMixin:
def _install(self, packages, time_out):
"""Attempts to install packages. Returns OK if the packages are installed or a result code if a recoverable-error occurred. Raises an exception if a non-recoverable error or timeout occurs."""
<|body_0|>
def _remov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedhatPackagerMixin:
def _install(self, packages, time_out):
"""Attempts to install packages. Returns OK if the packages are installed or a result code if a recoverable-error occurred. Raises an exception if a non-recoverable error or timeout occurs."""
cmd = 'sudo yum --color=never -y install... | the_stack_v2_python_sparse | trove/guestagent/pkg.py | openstack/trove | train | 258 | |
ee896df291119363f9783440a11e63ecfb4296c8 | [
"super().__init__()\nself.in_channels = in_channels\nself.hidden_channels = hidden_channels\nself.forget_bias = forget_bias\npadding = (kernel_size // 2, kernel_size // 2)\nkernel_size = (kernel_size, kernel_size)\nself.conv = nn.Conv2d(in_channels=in_channels, out_channels=hidden_channels * 4, kernel_size=kernel_s... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.forget_bias = forget_bias
padding = (kernel_size // 2, kernel_size // 2)
kernel_size = (kernel_size, kernel_size)
self.conv = nn.Conv2d(in_channels=in_ch... | ConvLSTM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvLSTM:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01):
""":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量"""
<|body_0|>
def forward(self, inputs: Tensor) -> T... | stack_v2_sparse_classes_36k_train_022178 | 3,758 | permissive | [
{
"docstring": ":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01)"
},
{
"docstring": ":param inputs: ... | 2 | stack_v2_sparse_classes_30k_train_013214 | Implement the Python class `ConvLSTM` described below.
Class description:
Implement the ConvLSTM class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01): :param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size... | Implement the Python class `ConvLSTM` described below.
Class description:
Implement the ConvLSTM class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01): :param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size... | d8079d6ceb3a41a06552bb3d88298327d0645d57 | <|skeleton|>
class ConvLSTM:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01):
""":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量"""
<|body_0|>
def forward(self, inputs: Tensor) -> T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvLSTM:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01):
""":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量"""
super().__init__()
self.in_channels = in_channels
se... | the_stack_v2_python_sparse | study/models/CubicRNN/CubicLSTM.py | hechentao/STudy | train | 0 | |
7637949418c337cf32e16a3daf0a35fccb0357a7 | [
"try:\n surface = partial_lexeme.random_kanji_surface\nexcept ObjectDoesNotExist:\n raise plugin_api.UnsupportedItem(partial_lexeme)\nanswer = partial_lexeme.reading_set.all().order_by('?')[0].reading\nquestion = self.build_question(pivot=surface, pivot_type='w', pivot_id=partial_lexeme.id, stimulus=surface, ... | <|body_start_0|>
try:
surface = partial_lexeme.random_kanji_surface
except ObjectDoesNotExist:
raise plugin_api.UnsupportedItem(partial_lexeme)
answer = partial_lexeme.reading_set.all().order_by('?')[0].reading
question = self.build_question(pivot=surface, pivot_t... | Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution. | ReadingQuestionFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadingQuestionFactory:
"""Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution."""
def get_word_question(self, partial_lex... | stack_v2_sparse_classes_36k_train_022179 | 7,501 | no_license | [
{
"docstring": "See parent.",
"name": "get_word_question",
"signature": "def get_word_question(self, partial_lexeme, user)"
},
{
"docstring": "See parent.",
"name": "get_kanji_question",
"signature": "def get_kanji_question(self, partial_kanji, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020463 | Implement the Python class `ReadingQuestionFactory` described below.
Class description:
Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution.
Method ... | Implement the Python class `ReadingQuestionFactory` described below.
Class description:
Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution.
Method ... | 8ffde158e8b863d6ee725fb689be163b1365f258 | <|skeleton|>
class ReadingQuestionFactory:
"""Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution."""
def get_word_question(self, partial_lex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReadingQuestionFactory:
"""Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution."""
def get_word_question(self, partial_lexeme, user):
... | the_stack_v2_python_sparse | kanji_test/plugins/basic_drills.py | tryforceful/kanjitester | train | 0 |
706e065d5a7f1fe0b5b92beff9432613340340a9 | [
"keyword = '%student%'\ndata = {'fieldList': [{'fieldName': 'name', 'fieldValue': keyword, 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}\nfieldValue = data['fieldList'][0]['fieldValue'][1:-1]\nres = requests.post(url=self.query_schedu... | <|body_start_0|>
keyword = '%student%'
data = {'fieldList': [{'fieldName': 'name', 'fieldValue': keyword, 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
fieldValue = data['fieldList'][0]['fieldValue'][1:-1]
... | 测试查询schedulers接口 /api/schedulers/query | QuerySchedulers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuerySchedulers:
"""测试查询schedulers接口 /api/schedulers/query"""
def test_case01(self):
"""根据scheduler name模糊查询"""
<|body_0|>
def test_case02(self):
"""根据flowtype-dataflow查询"""
<|body_1|>
def test_case03(self):
"""根据flowtype-workflow查询"""
... | stack_v2_sparse_classes_36k_train_022180 | 15,511 | no_license | [
{
"docstring": "根据scheduler name模糊查询",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "根据flowtype-dataflow查询",
"name": "test_case02",
"signature": "def test_case02(self)"
},
{
"docstring": "根据flowtype-workflow查询",
"name": "test_case03",
"sig... | 6 | stack_v2_sparse_classes_30k_train_012034 | Implement the Python class `QuerySchedulers` described below.
Class description:
测试查询schedulers接口 /api/schedulers/query
Method signatures and docstrings:
- def test_case01(self): 根据scheduler name模糊查询
- def test_case02(self): 根据flowtype-dataflow查询
- def test_case03(self): 根据flowtype-workflow查询
- def test_case04(self):... | Implement the Python class `QuerySchedulers` described below.
Class description:
测试查询schedulers接口 /api/schedulers/query
Method signatures and docstrings:
- def test_case01(self): 根据scheduler name模糊查询
- def test_case02(self): 根据flowtype-dataflow查询
- def test_case03(self): 根据flowtype-workflow查询
- def test_case04(self):... | fc41513af3063169ff1b17d6f01f7074057ceb1f | <|skeleton|>
class QuerySchedulers:
"""测试查询schedulers接口 /api/schedulers/query"""
def test_case01(self):
"""根据scheduler name模糊查询"""
<|body_0|>
def test_case02(self):
"""根据flowtype-dataflow查询"""
<|body_1|>
def test_case03(self):
"""根据flowtype-workflow查询"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuerySchedulers:
"""测试查询schedulers接口 /api/schedulers/query"""
def test_case01(self):
"""根据scheduler name模糊查询"""
keyword = '%student%'
data = {'fieldList': [{'fieldName': 'name', 'fieldValue': keyword, 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'ord... | the_stack_v2_python_sparse | singl_api/api_test_cases/cases_for_schedulers_api.py | bingjiegu/For_API | train | 0 |
c94a2880a63fbaf3791d26f5efd26b8bc47132d7 | [
"try:\n self.ident = ident\n self.norder = self._find_order('DYDX_', ident, keylist)\n self.twodkeys = self._find_twodkeys('DYDX_', ident, keylist)\nexcept CKeyNotFound as e:\n raise TraceNotFound(ident, e.keyword)\nexcept CKeyLengthWrong as e:\n print('Field dependent keyword: ' + e.keyword)",
"de... | <|body_start_0|>
try:
self.ident = ident
self.norder = self._find_order('DYDX_', ident, keylist)
self.twodkeys = self._find_twodkeys('DYDX_', ident, keylist)
except CKeyNotFound as e:
raise TraceNotFound(ident, e.keyword)
except CKeyLengthWrong as ... | Configuration Beam object | ConfigTrace | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigTrace:
"""Configuration Beam object"""
def __init__(self, ident=None, keylist=None):
"""Initializer for the configuration beam object The method initializes a configuration beam object for a given beam identifier. All necessary keywords are extracted from an input keyword list.... | stack_v2_sparse_classes_36k_train_022181 | 48,172 | permissive | [
{
"docstring": "Initializer for the configuration beam object The method initializes a configuration beam object for a given beam identifier. All necessary keywords are extracted from an input keyword list. In case of missing keywords an exception is fired. @param ident: beam identification @type ident: Charact... | 2 | null | Implement the Python class `ConfigTrace` described below.
Class description:
Configuration Beam object
Method signatures and docstrings:
- def __init__(self, ident=None, keylist=None): Initializer for the configuration beam object The method initializes a configuration beam object for a given beam identifier. All nec... | Implement the Python class `ConfigTrace` described below.
Class description:
Configuration Beam object
Method signatures and docstrings:
- def __init__(self, ident=None, keylist=None): Initializer for the configuration beam object The method initializes a configuration beam object for a given beam identifier. All nec... | 043c173fd5497c18c2b1bfe8bcff65180bca3996 | <|skeleton|>
class ConfigTrace:
"""Configuration Beam object"""
def __init__(self, ident=None, keylist=None):
"""Initializer for the configuration beam object The method initializes a configuration beam object for a given beam identifier. All necessary keywords are extracted from an input keyword list.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigTrace:
"""Configuration Beam object"""
def __init__(self, ident=None, keylist=None):
"""Initializer for the configuration beam object The method initializes a configuration beam object for a given beam identifier. All necessary keywords are extracted from an input keyword list. In case of m... | the_stack_v2_python_sparse | stsdas/pkg/analysis/slitless/axe/axesrc/configfile.py | spacetelescope/stsdas_stripped | train | 1 |
3cdb45b84e322eeeeea47ab01086465d0ab05e12 | [
"if node == None:\n return maxSum\ncurSum += node.val\nmaxSum = max([maxSum, curSum])\nleftMaxSum = self.dfs(node.left, curSum, maxSum)\nrightMaxSum = self.dfs(node.right, curSum, maxSum)\nreturn max([maxSum, leftMaxSum, rightMaxSum])",
"\"\"\"\n ok, this is wrong.. \n think about when input=[-3]... | <|body_start_0|>
if node == None:
return maxSum
curSum += node.val
maxSum = max([maxSum, curSum])
leftMaxSum = self.dfs(node.left, curSum, maxSum)
rightMaxSum = self.dfs(node.right, curSum, maxSum)
return max([maxSum, leftMaxSum, rightMaxSum])
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, node, curSum, maxSum):
"""return the max, from node, to every descendents"""
<|body_0|>
def maxPathSum(self, root: TreeNode) -> int:
"""maxPath possibly comes from: 1. pass the root - left arm max + root.val + right arm max - right arm - how t... | stack_v2_sparse_classes_36k_train_022182 | 1,940 | no_license | [
{
"docstring": "return the max, from node, to every descendents",
"name": "dfs",
"signature": "def dfs(self, node, curSum, maxSum)"
},
{
"docstring": "maxPath possibly comes from: 1. pass the root - left arm max + root.val + right arm max - right arm - how to find the paths, from the root, to ev... | 2 | stack_v2_sparse_classes_30k_train_019151 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, node, curSum, maxSum): return the max, from node, to every descendents
- def maxPathSum(self, root: TreeNode) -> int: maxPath possibly comes from: 1. pass the root ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, node, curSum, maxSum): return the max, from node, to every descendents
- def maxPathSum(self, root: TreeNode) -> int: maxPath possibly comes from: 1. pass the root ... | 774cf38ac680aebd79eba1f9ef7ffdf8f94633fc | <|skeleton|>
class Solution:
def dfs(self, node, curSum, maxSum):
"""return the max, from node, to every descendents"""
<|body_0|>
def maxPathSum(self, root: TreeNode) -> int:
"""maxPath possibly comes from: 1. pass the root - left arm max + root.val + right arm max - right arm - how t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dfs(self, node, curSum, maxSum):
"""return the max, from node, to every descendents"""
if node == None:
return maxSum
curSum += node.val
maxSum = max([maxSum, curSum])
leftMaxSum = self.dfs(node.left, curSum, maxSum)
rightMaxSum = self.... | the_stack_v2_python_sparse | Facebook/20210324_124_BinaryTreeMaximumPathSum.py | sxu11/Algorithm_Design | train | 0 | |
a39273827da5a139d0ae4b1b1a2ee992980b92b8 | [
"assert in_channels % 2 == 0, 'in_channels should be divisible by 2'\nsuper().__init__()\nself.half_channels = in_channels // 2\nself.use_only_mean = use_only_mean\nself.input_conv = torch.nn.Conv1d(self.half_channels, hidden_channels, 1)\nself.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_s... | <|body_start_0|>
assert in_channels % 2 == 0, 'in_channels should be divisible by 2'
super().__init__()
self.half_channels = in_channels // 2
self.use_only_mean = use_only_mean
self.input_conv = torch.nn.Conv1d(self.half_channels, hidden_channels, 1)
self.encoder = WaveNe... | Residual affine coupling layer. | ResidualAffineCouplingLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualAffineCouplingLayer:
"""Residual affine coupling layer."""
def __init__(self, in_channels: int=192, hidden_channels: int=192, kernel_size: int=5, base_dilation: int=1, layers: int=5, stacks: int=1, global_channels: int=-1, dropout_rate: float=0.0, use_weight_norm: bool=True, bias: bo... | stack_v2_sparse_classes_36k_train_022183 | 7,596 | permissive | [
{
"docstring": "Initialzie ResidualAffineCouplingLayer module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number of hidden channels. kernel_size (int): Kernel size for WaveNet. base_dilation (int): Base dilation factor for WaveNet. layers (int): Number of layers of WaveNet. stacks... | 2 | stack_v2_sparse_classes_30k_train_013964 | Implement the Python class `ResidualAffineCouplingLayer` described below.
Class description:
Residual affine coupling layer.
Method signatures and docstrings:
- def __init__(self, in_channels: int=192, hidden_channels: int=192, kernel_size: int=5, base_dilation: int=1, layers: int=5, stacks: int=1, global_channels: i... | Implement the Python class `ResidualAffineCouplingLayer` described below.
Class description:
Residual affine coupling layer.
Method signatures and docstrings:
- def __init__(self, in_channels: int=192, hidden_channels: int=192, kernel_size: int=5, base_dilation: int=1, layers: int=5, stacks: int=1, global_channels: i... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class ResidualAffineCouplingLayer:
"""Residual affine coupling layer."""
def __init__(self, in_channels: int=192, hidden_channels: int=192, kernel_size: int=5, base_dilation: int=1, layers: int=5, stacks: int=1, global_channels: int=-1, dropout_rate: float=0.0, use_weight_norm: bool=True, bias: bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualAffineCouplingLayer:
"""Residual affine coupling layer."""
def __init__(self, in_channels: int=192, hidden_channels: int=192, kernel_size: int=5, base_dilation: int=1, layers: int=5, stacks: int=1, global_channels: int=-1, dropout_rate: float=0.0, use_weight_norm: bool=True, bias: bool=True, use_... | the_stack_v2_python_sparse | espnet2/gan_tts/vits/residual_coupling.py | espnet/espnet | train | 7,242 |
1cded47a04023c2124ed85482e56f1a5cd25fdd3 | [
"assert type(seg) == tuple, repr(seg)\nassert len(seg) in (2, 3), repr(seg)\nself.sc, self.offs = seg[:2]\nassert type(self.sc) == int, repr(self.sc)\nif len(seg) == 3:\n assert type(self.offs) == int, repr(self.offs)\n assert self.sc > 0, repr(seg)\n t = seg[2]\n if type(t) == bytes:\n self.text... | <|body_start_0|>
assert type(seg) == tuple, repr(seg)
assert len(seg) in (2, 3), repr(seg)
self.sc, self.offs = seg[:2]
assert type(self.sc) == int, repr(self.sc)
if len(seg) == 3:
assert type(self.offs) == int, repr(self.offs)
assert self.sc > 0, repr(seg... | LayoutSegment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutSegment:
def __init__(self, seg):
"""Create object from line layout segment structure"""
<|body_0|>
def subseg(self, text, start, end):
"""Return a "sub-segment" list containing segment structures that make up a portion of this segment. A list is returned to ha... | stack_v2_sparse_classes_36k_train_022184 | 18,219 | permissive | [
{
"docstring": "Create object from line layout segment structure",
"name": "__init__",
"signature": "def __init__(self, seg)"
},
{
"docstring": "Return a \"sub-segment\" list containing segment structures that make up a portion of this segment. A list is returned to handle cases where wide chara... | 2 | null | Implement the Python class `LayoutSegment` described below.
Class description:
Implement the LayoutSegment class.
Method signatures and docstrings:
- def __init__(self, seg): Create object from line layout segment structure
- def subseg(self, text, start, end): Return a "sub-segment" list containing segment structure... | Implement the Python class `LayoutSegment` described below.
Class description:
Implement the LayoutSegment class.
Method signatures and docstrings:
- def __init__(self, seg): Create object from line layout segment structure
- def subseg(self, text, start, end): Return a "sub-segment" list containing segment structure... | 95b7a061eabd6f2b607fba79e007186030f02720 | <|skeleton|>
class LayoutSegment:
def __init__(self, seg):
"""Create object from line layout segment structure"""
<|body_0|>
def subseg(self, text, start, end):
"""Return a "sub-segment" list containing segment structures that make up a portion of this segment. A list is returned to ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayoutSegment:
def __init__(self, seg):
"""Create object from line layout segment structure"""
assert type(seg) == tuple, repr(seg)
assert len(seg) in (2, 3), repr(seg)
self.sc, self.offs = seg[:2]
assert type(self.sc) == int, repr(self.sc)
if len(seg) == 3:
... | the_stack_v2_python_sparse | Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/urwid/text_layout.py | icl-rocketry/Avionics | train | 9 | |
64537b510102bd4700cb022b0d72d148c9c9ff1c | [
"super().__init__()\nself.x_dir = x_direction\nself.y_dir = y_direction\nself.z_dir = z_direction",
"if self.x_dir:\n self.grid.E[0, :, :, :] = self.grid.E[-1, :, :, :]\nif self.y_dir:\n self.grid.E[:, 0, :, :] = self.grid.E[:, -1, :, :]\nif self.z_dir:\n self.grid.E[:, :, 0, :] = self.grid.E[:, :, -1, :... | <|body_start_0|>
super().__init__()
self.x_dir = x_direction
self.y_dir = y_direction
self.z_dir = z_direction
<|end_body_0|>
<|body_start_1|>
if self.x_dir:
self.grid.E[0, :, :, :] = self.grid.E[-1, :, :, :]
if self.y_dir:
self.grid.E[:, 0, :, :]... | Implement a periodic boundary condition. | PeriodicBoundary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicBoundary:
"""Implement a periodic boundary condition."""
def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False):
"""Initialize periodic boundary object."""
<|body_0|>
def update_E(self):
"""Update E field."""
... | stack_v2_sparse_classes_36k_train_022185 | 3,210 | permissive | [
{
"docstring": "Initialize periodic boundary object.",
"name": "__init__",
"signature": "def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False)"
},
{
"docstring": "Update E field.",
"name": "update_E",
"signature": "def update_E(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_008997 | Implement the Python class `PeriodicBoundary` described below.
Class description:
Implement a periodic boundary condition.
Method signatures and docstrings:
- def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False): Initialize periodic boundary object.
- def update_E(self): Updat... | Implement the Python class `PeriodicBoundary` described below.
Class description:
Implement a periodic boundary condition.
Method signatures and docstrings:
- def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False): Initialize periodic boundary object.
- def update_E(self): Updat... | f2134cb3e36eabca1639b8ff4e428d3a268953bd | <|skeleton|>
class PeriodicBoundary:
"""Implement a periodic boundary condition."""
def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False):
"""Initialize periodic boundary object."""
<|body_0|>
def update_E(self):
"""Update E field."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeriodicBoundary:
"""Implement a periodic boundary condition."""
def __init__(self, x_direction: bool=False, y_direction: bool=False, z_direction: bool=False):
"""Initialize periodic boundary object."""
super().__init__()
self.x_dir = x_direction
self.y_dir = y_direction
... | the_stack_v2_python_sparse | fdtd/boundaries.py | tiagovla/fdtd.py | train | 4 |
ed2c7709959a00afce48dcfb29bb238abdf4e526 | [
"super(DistilleryFilterParameter, self).__init__(index, parameter, SearchParameterType.DISTILLERY)\nself.filter = self._get_filter(parameter)\nif not self.is_valid():\n return\nself.distilleries = self._get_distilleries(self.filter, user)",
"match_object = DistilleryFilterParameter.FILTER_REGEX.match(parameter... | <|body_start_0|>
super(DistilleryFilterParameter, self).__init__(index, parameter, SearchParameterType.DISTILLERY)
self.filter = self._get_filter(parameter)
if not self.is_valid():
return
self.distilleries = self._get_distilleries(self.filter, user)
<|end_body_0|>
<|body_sta... | Class representing a search query parameter that wants to filter the distilleries it searches through. Attributes ---------- filter : str String representation of distilleries to filter. distilleries : django.db.models.query.QuerySet Matching distillery objects. | DistilleryFilterParameter | [
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistilleryFilterParameter:
"""Class representing a search query parameter that wants to filter the distilleries it searches through. Attributes ---------- filter : str String representation of distilleries to filter. distilleries : django.db.models.query.QuerySet Matching distillery objects."""
... | stack_v2_sparse_classes_36k_train_022186 | 4,867 | permissive | [
{
"docstring": "Constructor for DistilleryFilterParameter. Parameters ---------- index : int Index of this search parameter in the search query string. parameter : str String representation of this parameter. user : appusers.models.AppUser",
"name": "__init__",
"signature": "def __init__(self, index, pa... | 4 | null | Implement the Python class `DistilleryFilterParameter` described below.
Class description:
Class representing a search query parameter that wants to filter the distilleries it searches through. Attributes ---------- filter : str String representation of distilleries to filter. distilleries : django.db.models.query.Que... | Implement the Python class `DistilleryFilterParameter` described below.
Class description:
Class representing a search query parameter that wants to filter the distilleries it searches through. Attributes ---------- filter : str String representation of distilleries to filter. distilleries : django.db.models.query.Que... | a379a134c0c5af14df4ed2afa066c1626506b754 | <|skeleton|>
class DistilleryFilterParameter:
"""Class representing a search query parameter that wants to filter the distilleries it searches through. Attributes ---------- filter : str String representation of distilleries to filter. distilleries : django.db.models.query.QuerySet Matching distillery objects."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistilleryFilterParameter:
"""Class representing a search query parameter that wants to filter the distilleries it searches through. Attributes ---------- filter : str String representation of distilleries to filter. distilleries : django.db.models.query.QuerySet Matching distillery objects."""
def __ini... | the_stack_v2_python_sparse | Incident-Response/Tools/cyphon/cyphon/query/search/distillery_filter_parameter.py | foss2cyber/Incident-Playbook | train | 1 |
3d53c1aec4a26c471e66d8c60b20d73e7b36de34 | [
"self.SUBJECT = 'MOSJA00301'\nsuper(OASEMailModifyMailAddressNotify, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)\nself.create_mail_text(user_name, valid_hour, url)",
"self.mail_text = System.objects.get(config_id=self.CONFIG_ID).value\nself.mail_text = get_message(self... | <|body_start_0|>
self.SUBJECT = 'MOSJA00301'
super(OASEMailModifyMailAddressNotify, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)
self.create_mail_text(user_name, valid_hour, url)
<|end_body_0|>
<|body_start_1|>
self.mail_text = System.objects.... | [クラス概要] メールアドレス変更通知メール | OASEMailModifyMailAddressNotify | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OASEMailModifyMailAddressNotify:
"""[クラス概要] メールアドレス変更通知メール"""
def __init__(self, addr_to, user_name, valid_hour, url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 valid_hour : int メールアドレス変更URLの有効期間(hour) url : str メール... | stack_v2_sparse_classes_36k_train_022187 | 20,173 | permissive | [
{
"docstring": "[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 valid_hour : int メールアドレス変更URLの有効期間(hour) url : str メールアドレス変更URL",
"name": "__init__",
"signature": "def __init__(self, addr_to, user_name, valid_hour, url, inquiry_url, login_url, charset='utf-8')"
},
{
"docstring... | 2 | null | Implement the Python class `OASEMailModifyMailAddressNotify` described below.
Class description:
[クラス概要] メールアドレス変更通知メール
Method signatures and docstrings:
- def __init__(self, addr_to, user_name, valid_hour, url, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユー... | Implement the Python class `OASEMailModifyMailAddressNotify` described below.
Class description:
[クラス概要] メールアドレス変更通知メール
Method signatures and docstrings:
- def __init__(self, addr_to, user_name, valid_hour, url, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユー... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class OASEMailModifyMailAddressNotify:
"""[クラス概要] メールアドレス変更通知メール"""
def __init__(self, addr_to, user_name, valid_hour, url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 valid_hour : int メールアドレス変更URLの有効期間(hour) url : str メール... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OASEMailModifyMailAddressNotify:
"""[クラス概要] メールアドレス変更通知メール"""
def __init__(self, addr_to, user_name, valid_hour, url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 valid_hour : int メールアドレス変更URLの有効期間(hour) url : str メールアドレス変更URL"""
... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/oase_mail.py | exastro-suite/oase | train | 10 |
b43912116ff57397a6e7f3217e076fa3105e7c37 | [
"self.rule_name = rule_name\nself.rule_index = rule_index\nself.rule = rule",
"service = self.rule['service']\nfor log_type in self.rule['log_types']:\n configs = audit_config.service_configs\n if log_type not in configs.get(service, {}) and log_type not in configs.get(IamAuditConfig.ALL_SERVICES, {}):\n ... | <|body_start_0|>
self.rule_name = rule_name
self.rule_index = rule_index
self.rule = rule
<|end_body_0|>
<|body_start_1|>
service = self.rule['service']
for log_type in self.rule['log_types']:
configs = audit_config.service_configs
if log_type not in conf... | Rule properties from the rule definition file. Also finds violations. | Rule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, rule_name, rule_index, rule):
"""Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule d... | stack_v2_sparse_classes_36k_train_022188 | 14,523 | permissive | [
{
"docstring": "Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule definition from the file.",
"name": "__init__",
"signature": "def __init__(self, rule_name, rule_index, rule)"
},
{
"docstring": "F... | 2 | stack_v2_sparse_classes_30k_train_020605 | Implement the Python class `Rule` described below.
Class description:
Rule properties from the rule definition file. Also finds violations.
Method signatures and docstrings:
- def __init__(self, rule_name, rule_index, rule): Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of th... | Implement the Python class `Rule` described below.
Class description:
Rule properties from the rule definition file. Also finds violations.
Method signatures and docstrings:
- def __init__(self, rule_name, rule_index, rule): Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of th... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, rule_name, rule_index, rule):
"""Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, rule_name, rule_index, rule):
"""Initialize. Args: rule_name (str): Name of the loaded rule. rule_index (int): The index of the rule from the rule definitions. rule (dict): The rule definition fro... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/audit/audit_logging_rules_engine.py | kevensen/forseti-security | train | 1 |
968d2d4abced6c7a9433a25f0c24d7a5b565f002 | [
"retrieved_participant = participant_records.read(participant_id=participant_id)\nif retrieved_participant:\n success_payload = payload_formatter.construct_success_payload(status=200, method='participant.get', params={'participant_id': participant_id}, data=retrieved_participant)\n logging.info(f\"Participant... | <|body_start_0|>
retrieved_participant = participant_records.read(participant_id=participant_id)
if retrieved_participant:
success_payload = payload_formatter.construct_success_payload(status=200, method='participant.get', params={'participant_id': participant_id}, data=retrieved_participant... | Handles all participant interactions for logging individual server configurations | Participant | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Participant:
"""Handles all participant interactions for logging individual server configurations"""
def get(self, participant_id):
"""Retrieves all metadata describing specified project"""
<|body_0|>
def put(self, participant_id):
"""Updates a participant's spec... | stack_v2_sparse_classes_36k_train_022189 | 13,154 | permissive | [
{
"docstring": "Retrieves all metadata describing specified project",
"name": "get",
"signature": "def get(self, participant_id)"
},
{
"docstring": "Updates a participant's specified choices IF & ONLY IF his/her registered experiments have not yet commenced",
"name": "put",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_011303 | Implement the Python class `Participant` described below.
Class description:
Handles all participant interactions for logging individual server configurations
Method signatures and docstrings:
- def get(self, participant_id): Retrieves all metadata describing specified project
- def put(self, participant_id): Updates... | Implement the Python class `Participant` described below.
Class description:
Handles all participant interactions for logging individual server configurations
Method signatures and docstrings:
- def get(self, participant_id): Retrieves all metadata describing specified project
- def put(self, participant_id): Updates... | d7b45216e5d1854fe65213f06ae3f3bb6d99cab0 | <|skeleton|>
class Participant:
"""Handles all participant interactions for logging individual server configurations"""
def get(self, participant_id):
"""Retrieves all metadata describing specified project"""
<|body_0|>
def put(self, participant_id):
"""Updates a participant's spec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Participant:
"""Handles all participant interactions for logging individual server configurations"""
def get(self, participant_id):
"""Retrieves all metadata describing specified project"""
retrieved_participant = participant_records.read(participant_id=participant_id)
if retrieve... | the_stack_v2_python_sparse | rest_rpc/connection/participants.py | markchc101/synergos_rest | train | 0 |
6c1d77bd64f3dbf4adeb2112d79dab481fdced9b | [
"print('test_login1_normal start run...')\npo = LoginPage(self.driver)\npo.Login_action('昆明万睿房地产开发有限公司', '12345')\nsleep(3)\nself.assertEqual(po.type_loginPass_hint(), '退出系统')\nfunction_zd.insert_img(self.driver, 'fdczzxt_login1_normal.png')\nprint('test_login1_normal is test end')",
"print('test_login2_passwdErr... | <|body_start_0|>
print('test_login1_normal start run...')
po = LoginPage(self.driver)
po.Login_action('昆明万睿房地产开发有限公司', '12345')
sleep(3)
self.assertEqual(po.type_loginPass_hint(), '退出系统')
function_zd.insert_img(self.driver, 'fdczzxt_login1_normal.png')
print('test... | LoginTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"""
<|body_0|>
def test_login2_passwdError(self):
"""用户名正确密码错误登录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
print('test_login1_normal start run...')
po = LoginPage(self.driver)
... | stack_v2_sparse_classes_36k_train_022190 | 1,694 | no_license | [
{
"docstring": "用户名密码正确登录",
"name": "test_login1_normal",
"signature": "def test_login1_normal(self)"
},
{
"docstring": "用户名正确密码错误登录",
"name": "test_login2_passwdError",
"signature": "def test_login2_passwdError(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007406 | Implement the Python class `LoginTest` described below.
Class description:
Implement the LoginTest class.
Method signatures and docstrings:
- def test_login1_normal(self): 用户名密码正确登录
- def test_login2_passwdError(self): 用户名正确密码错误登录 | Implement the Python class `LoginTest` described below.
Class description:
Implement the LoginTest class.
Method signatures and docstrings:
- def test_login1_normal(self): 用户名密码正确登录
- def test_login2_passwdError(self): 用户名正确密码错误登录
<|skeleton|>
class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"... | c9fb6ad8c837b58a35e53b98758b242710354a35 | <|skeleton|>
class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"""
<|body_0|>
def test_login2_passwdError(self):
"""用户名正确密码错误登录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"""
print('test_login1_normal start run...')
po = LoginPage(self.driver)
po.Login_action('昆明万睿房地产开发有限公司', '12345')
sleep(3)
self.assertEqual(po.type_loginPass_hint(), '退出系统')
function_zd.insert_img(sel... | the_stack_v2_python_sparse | untitled5/venv/fdczzxt_test/Website/test_case/test_login.py | sack1986/python_interface | train | 0 | |
a745098dad93ebee4282f503a489fe10d56f64a3 | [
"for item in content.items():\n if item not in serializer.data.items():\n key, val = item\n print('CONTENT %s' % key.upper(), val)\n print('SERIALIZER %s' % key.upper(), serializer.data[key])",
"diff = (item for item in list_a if item not in list_b)\nfor d in diff:\n print(d)"
] | <|body_start_0|>
for item in content.items():
if item not in serializer.data.items():
key, val = item
print('CONTENT %s' % key.upper(), val)
print('SERIALIZER %s' % key.upper(), serializer.data[key])
<|end_body_0|>
<|body_start_1|>
diff = (ite... | Some method to help the test | TestMixinUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMixinUtils:
"""Some method to help the test"""
def all_serializer_items_diff_assertion(self, serializer, content):
"""Find out the different items and print them out"""
<|body_0|>
def diff_between_lists(self, list_a, list_b):
"""Find the different items betwe... | stack_v2_sparse_classes_36k_train_022191 | 7,639 | no_license | [
{
"docstring": "Find out the different items and print them out",
"name": "all_serializer_items_diff_assertion",
"signature": "def all_serializer_items_diff_assertion(self, serializer, content)"
},
{
"docstring": "Find the different items between two lists :type list_a: list :type list_b: list",... | 2 | stack_v2_sparse_classes_30k_train_018322 | Implement the Python class `TestMixinUtils` described below.
Class description:
Some method to help the test
Method signatures and docstrings:
- def all_serializer_items_diff_assertion(self, serializer, content): Find out the different items and print them out
- def diff_between_lists(self, list_a, list_b): Find the ... | Implement the Python class `TestMixinUtils` described below.
Class description:
Some method to help the test
Method signatures and docstrings:
- def all_serializer_items_diff_assertion(self, serializer, content): Find out the different items and print them out
- def diff_between_lists(self, list_a, list_b): Find the ... | 33d6e35ef3483da311c06502f9b6ce996bc0d06e | <|skeleton|>
class TestMixinUtils:
"""Some method to help the test"""
def all_serializer_items_diff_assertion(self, serializer, content):
"""Find out the different items and print them out"""
<|body_0|>
def diff_between_lists(self, list_a, list_b):
"""Find the different items betwe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMixinUtils:
"""Some method to help the test"""
def all_serializer_items_diff_assertion(self, serializer, content):
"""Find out the different items and print them out"""
for item in content.items():
if item not in serializer.data.items():
key, val = item
... | the_stack_v2_python_sparse | utils/tests.py | levivm/backend | train | 1 |
6bef858df4696f940a6281783607687c17531364 | [
"while n != 42:\n prev, n = (n, sum(map(lambda i: int(i) ** 2, str(n))))\n if prev == n:\n return True\nreturn False",
"num_sum = n\nrepeat_num = []\nrepeat_num.append(n)\nwhile num_sum != 1:\n num_sum = 0\n for i in str(n):\n num_sum += int(i) ** 2\n if num_sum in repeat_num:\n ... | <|body_start_0|>
while n != 42:
prev, n = (n, sum(map(lambda i: int(i) ** 2, str(n))))
if prev == n:
return True
return False
<|end_body_0|>
<|body_start_1|>
num_sum = n
repeat_num = []
repeat_num.append(n)
while num_sum != 1:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def _isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while n != 42:
prev, n = (n, sum(map(lambda i: int(i) ** 2, st... | stack_v2_sparse_classes_36k_train_022192 | 1,595 | permissive | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isHappy",
"signature": "def isHappy(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "_isHappy",
"signature": "def _isHappy(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020851 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): :type n: int :rtype: bool
- def _isHappy(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): :type n: int :rtype: bool
- def _isHappy(self, n): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: in... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def _isHappy(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isHappy(self, n):
""":type n: int :rtype: bool"""
while n != 42:
prev, n = (n, sum(map(lambda i: int(i) ** 2, str(n))))
if prev == n:
return True
return False
def _isHappy(self, n):
""":type n: int :rtype: bool"""
... | the_stack_v2_python_sparse | 202.happy-number.py | windard/leeeeee | train | 0 | |
1551cf21b02340673adabca151988a906dc0f1ae | [
"highest_index = len(array) - 1\nHeap.heapify(array, highest_index)\nfor end in range(highest_index, 0, -1):\n array[end], array[0] = (array[0], array[end])\n Heap.sift_down(array, 0, end - 1)",
"first = (highest_index - 1) // 2\nfor start in range(first, -1, -1):\n Heap.sift_down(array, start, highest_i... | <|body_start_0|>
highest_index = len(array) - 1
Heap.heapify(array, highest_index)
for end in range(highest_index, 0, -1):
array[end], array[0] = (array[0], array[end])
Heap.sift_down(array, 0, end - 1)
<|end_body_0|>
<|body_start_1|>
first = (highest_index - 1) ... | Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort | Heap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Heap:
"""Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort"""
def heap_sort(array):
"""A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and ... | stack_v2_sparse_classes_36k_train_022193 | 14,101 | no_license | [
{
"docstring": "A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and sift_down() Inplace: Yes Time complexity: all O(nlogn)",
"name": "heap_sort",
"signature": "def heap_sort(array)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_011483 | Implement the Python class `Heap` described below.
Class description:
Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort
Method signatures and docstrings:
- def heap_sort(array): A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort... | Implement the Python class `Heap` described below.
Class description:
Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort
Method signatures and docstrings:
- def heap_sort(array): A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort... | c88059dc66297af577ad2b8afa4e0ac0ad622915 | <|skeleton|>
class Heap:
"""Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort"""
def heap_sort(array):
"""A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Heap:
"""Contains various heap sort implementations. http://en.wikipedia.org/wiki/Heapsort"""
def heap_sort(array):
"""A basic implementation of heap sort. As with merge sort, heap sort is also often out performed by quick sort in practical cases. Uses helper functions heapify() and sift_down() I... | the_stack_v2_python_sparse | codes/BuildLinks1.02/test_input/sort_codes/pysort.py | DaHuO/Supergraph | train | 2 |
157c088bb0b750118de6b62089fac599c07aaf08 | [
"dict = {}\nfor item in strs:\n key = tuple(sorted(item))\n dict[key] = dict.get(key, []) + [item]\nreturn list(dict.values())",
"ans = collections.defaultdict(list)\nfor s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n ans[tuple(count)].append(s)\nreturn ans.val... | <|body_start_0|>
dict = {}
for item in strs:
key = tuple(sorted(item))
dict[key] = dict.get(key, []) + [item]
return list(dict.values())
<|end_body_0|>
<|body_start_1|>
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""常规方法"""
<|body_0|>
def groupAnagrams1(strs):
"""利用asii"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict = {}
for item in strs:
key = tuple(sorted(item)... | stack_v2_sparse_classes_36k_train_022194 | 1,567 | no_license | [
{
"docstring": "常规方法",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs: List[str]) -> List[List[str]]"
},
{
"docstring": "利用asii",
"name": "groupAnagrams1",
"signature": "def groupAnagrams1(strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 常规方法
- def groupAnagrams1(strs): 利用asii | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 常规方法
- def groupAnagrams1(strs): 利用asii
<|skeleton|>
class Solution:
def groupAnagrams(self, strs: List[str]) -... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""常规方法"""
<|body_0|>
def groupAnagrams1(strs):
"""利用asii"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""常规方法"""
dict = {}
for item in strs:
key = tuple(sorted(item))
dict[key] = dict.get(key, []) + [item]
return list(dict.values())
def groupAnagrams1(strs):
"""利用asii"""
... | the_stack_v2_python_sparse | 算法/Week_02/49. 字母异位词分组.py | RichieSong/algorithm | train | 0 | |
d646cb1df0afe8fbe23d81f04d56e56be8a4980d | [
"def sumNumbersRec(nd, sum, total):\n sum = sum * 10 + nd.val\n if not nd.left and (not nd.right):\n total.append(sum)\n if nd.left:\n sumNumbersRec(nd.left, sum, total)\n if nd.right:\n sumNumbersRec(nd.right, sum, total)\nif not root:\n return\nret = []\nsumNumbersRec(root, 0, ... | <|body_start_0|>
def sumNumbersRec(nd, sum, total):
sum = sum * 10 + nd.val
if not nd.left and (not nd.right):
total.append(sum)
if nd.left:
sumNumbersRec(nd.left, sum, total)
if nd.right:
sumNumbersRec(nd.right, sum... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers1(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumNumbers2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def sumNumbersRec(nd, sum, total):
... | stack_v2_sparse_classes_36k_train_022195 | 1,579 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers1",
"signature": "def sumNumbers1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers2",
"signature": "def sumNumbers2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005126 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root): :type root: TreeNode :rtype: int
- def sumNumbers2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root): :type root: TreeNode :rtype: int
- def sumNumbers2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumNumbers1(s... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class Solution:
def sumNumbers1(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumNumbers2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbers1(self, root):
""":type root: TreeNode :rtype: int"""
def sumNumbersRec(nd, sum, total):
sum = sum * 10 + nd.val
if not nd.left and (not nd.right):
total.append(sum)
if nd.left:
sumNumbersRec(nd.left, s... | the_stack_v2_python_sparse | leetcode/129.py | liuweilin17/algorithm | train | 3 | |
d0ee64a91e7e9fd5c126afeef26dd6352f7f34c7 | [
"if fname:\n if not fname.endswith('.pkl'):\n fname = fname + '.pkl'\n ifile = open(fname, 'rb')\n self._archive = pkl.load(ifile)\n ifile.close()\nelse:\n self._archive = None\nself._fname = fname\nself._pulled = {}\nself._new = {}\nif kwds:\n for key, value in list(kwds.items(... | <|body_start_0|>
if fname:
if not fname.endswith('.pkl'):
fname = fname + '.pkl'
ifile = open(fname, 'rb')
self._archive = pkl.load(ifile)
ifile.close()
else:
self._archive = None
self._fname = fname
... | A container class that provides lazy persistance of instance attributes as a Python pickle. This is doubly lazy: attributes are not placed in the namespace until actually requested, and they are not saved to the archive until the AttrStore is explicitly saved. If only NumPy arrays are to be stored, ArrayStore may be mo... | AttrStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttrStore:
"""A container class that provides lazy persistance of instance attributes as a Python pickle. This is doubly lazy: attributes are not placed in the namespace until actually requested, and they are not saved to the archive until the AttrStore is explicitly saved. If only NumPy arrays a... | stack_v2_sparse_classes_36k_train_022196 | 14,154 | no_license | [
{
"docstring": "Prepare to load attributes from storage if a file name is provided; otherwise support saving of arrays assigned as attributes.",
"name": "__init__",
"signature": "def __init__(self, fname=None, **kwds)"
},
{
"docstring": "Catch references to attributes that have not yet been load... | 5 | stack_v2_sparse_classes_30k_train_019479 | Implement the Python class `AttrStore` described below.
Class description:
A container class that provides lazy persistance of instance attributes as a Python pickle. This is doubly lazy: attributes are not placed in the namespace until actually requested, and they are not saved to the archive until the AttrStore is e... | Implement the Python class `AttrStore` described below.
Class description:
A container class that provides lazy persistance of instance attributes as a Python pickle. This is doubly lazy: attributes are not placed in the namespace until actually requested, and they are not saved to the archive until the AttrStore is e... | 215de4e93b5cf79a1e9f380047b4db92bfeaf45c | <|skeleton|>
class AttrStore:
"""A container class that provides lazy persistance of instance attributes as a Python pickle. This is doubly lazy: attributes are not placed in the namespace until actually requested, and they are not saved to the archive until the AttrStore is explicitly saved. If only NumPy arrays a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttrStore:
"""A container class that provides lazy persistance of instance attributes as a Python pickle. This is doubly lazy: attributes are not placed in the namespace until actually requested, and they are not saved to the archive until the AttrStore is explicitly saved. If only NumPy arrays are to be stor... | the_stack_v2_python_sparse | package/inference/utils/ioutils.py | tloredo/inference | train | 3 |
fee878b3fb49d2eb8f59596dfd73e19487deac28 | [
"m = len(nums)\ndp = [0] * (m + 1)\nfor i in range(1, m + 1):\n dp[i] = max(nums[i - 1], dp[i - 1] + nums[i - 1])\nreturn max(dp[1:])",
"m = len(nums)\nlast = -float('inf')\nres = -float('inf')\nfor i in range(1, m + 1):\n last = max(nums[i - 1], last + nums[i - 1])\n res = max(res, last)\nreturn res"
] | <|body_start_0|>
m = len(nums)
dp = [0] * (m + 1)
for i in range(1, m + 1):
dp[i] = max(nums[i - 1], dp[i - 1] + nums[i - 1])
return max(dp[1:])
<|end_body_0|>
<|body_start_1|>
m = len(nums)
last = -float('inf')
res = -float('inf')
for i in ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
"""[-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py,-5,4] dp[i] 以i结尾子数组的最大和 dp[i] = dp[i] + nums[i] if dp[i]+nums[i]>nums = nums[i] dp[0] = 0 res = max(dp)"""
<|body_0|>
def maxSubArray(self, nums):
"""[-2,1_最短回文串.py,-3,4,-1_最短回文串.p... | stack_v2_sparse_classes_36k_train_022197 | 1,162 | no_license | [
{
"docstring": "[-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py,-5,4] dp[i] 以i结尾子数组的最大和 dp[i] = dp[i] + nums[i] if dp[i]+nums[i]>nums = nums[i] dp[0] = 0 res = max(dp)",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": "[-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py... | 2 | stack_v2_sparse_classes_30k_train_015358 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): [-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py,-5,4] dp[i] 以i结尾子数组的最大和 dp[i] = dp[i] + nums[i] if dp[i]+nums[i]>nums = nums[i] dp[0] = 0 res = max(dp)
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): [-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py,-5,4] dp[i] 以i结尾子数组的最大和 dp[i] = dp[i] + nums[i] if dp[i]+nums[i]>nums = nums[i] dp[0] = 0 res = max(dp)
... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
"""[-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py,-5,4] dp[i] 以i结尾子数组的最大和 dp[i] = dp[i] + nums[i] if dp[i]+nums[i]>nums = nums[i] dp[0] = 0 res = max(dp)"""
<|body_0|>
def maxSubArray(self, nums):
"""[-2,1_最短回文串.py,-3,4,-1_最短回文串.p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
"""[-2,1_最短回文串.py,-3,4,-1_最短回文串.py,2,1_最短回文串.py,-5,4] dp[i] 以i结尾子数组的最大和 dp[i] = dp[i] + nums[i] if dp[i]+nums[i]>nums = nums[i] dp[0] = 0 res = max(dp)"""
m = len(nums)
dp = [0] * (m + 1)
for i in range(1, m + 1):
dp[i] = max(n... | the_stack_v2_python_sparse | 3_Offer2nd-HandWriting/6_DP/3_连续子数组的最大和.py | fzingithub/SwordRefers2Offer | train | 1 | |
5388c56d81e1f15971b74de5034f82622c34decc | [
"super().__init__(block_class)\nif not isinstance(fixed_dims, int) or not fixed_dims > 0:\n raise ValueError(f'{type(self).__name__} requires fixed_dims to be an int > 0.')\nself.fixed_dims = fixed_dims",
"from_shape = get_shape('out', from_blocks[0])\nif self.fixed_dims == 1:\n to_shape = from_shape + [blo... | <|body_start_0|>
super().__init__(block_class)
if not isinstance(fixed_dims, int) or not fixed_dims > 0:
raise ValueError(f'{type(self).__name__} requires fixed_dims to be an int > 0.')
self.fixed_dims = fixed_dims
<|end_body_0|>
<|body_start_1|>
from_shape = get_shape('out'... | Propagator for blocks that adds fixed dimensions. | AddFixedPropagator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddFixedPropagator:
"""Propagator for blocks that adds fixed dimensions."""
def __init__(self, block_class: str, fixed_dims: int=1):
"""Initializer for AddFixedPropagator instance. Args: block_class: The name of the block class being propagated. fixed_dims: Number of fixed dimensions... | stack_v2_sparse_classes_36k_train_022198 | 4,438 | permissive | [
{
"docstring": "Initializer for AddFixedPropagator instance. Args: block_class: The name of the block class being propagated. fixed_dims: Number of fixed dimensions. Raises: ValueError: If fixed_dims not int > 0.",
"name": "__init__",
"signature": "def __init__(self, block_class: str, fixed_dims: int=1)... | 2 | stack_v2_sparse_classes_30k_train_020479 | Implement the Python class `AddFixedPropagator` described below.
Class description:
Propagator for blocks that adds fixed dimensions.
Method signatures and docstrings:
- def __init__(self, block_class: str, fixed_dims: int=1): Initializer for AddFixedPropagator instance. Args: block_class: The name of the block class... | Implement the Python class `AddFixedPropagator` described below.
Class description:
Propagator for blocks that adds fixed dimensions.
Method signatures and docstrings:
- def __init__(self, block_class: str, fixed_dims: int=1): Initializer for AddFixedPropagator instance. Args: block_class: The name of the block class... | 55eacc273e61ab0166b5692204a20ab756b92e4c | <|skeleton|>
class AddFixedPropagator:
"""Propagator for blocks that adds fixed dimensions."""
def __init__(self, block_class: str, fixed_dims: int=1):
"""Initializer for AddFixedPropagator instance. Args: block_class: The name of the block class being propagated. fixed_dims: Number of fixed dimensions... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddFixedPropagator:
"""Propagator for blocks that adds fixed dimensions."""
def __init__(self, block_class: str, fixed_dims: int=1):
"""Initializer for AddFixedPropagator instance. Args: block_class: The name of the block class being propagated. fixed_dims: Number of fixed dimensions. Raises: Val... | the_stack_v2_python_sparse | narchi/propagators/fixed.py | omni-us/narchi | train | 3 |
d673712b280876bc8613eadcf9e4aa5c0b7e6b1a | [
"json_data = data().decode()\nkwargs = {'description': None, 'email': None}\ntry:\n parameters = json_data and loads(json_data)\n if parameters:\n for param in kwargs:\n if param in parameters:\n kwargs[param] = parameters[param]\nexcept ValueError:\n raise generate_http_er... | <|body_start_0|>
json_data = data().decode()
kwargs = {'description': None, 'email': None}
try:
parameters = json_data and loads(json_data)
if parameters:
for param in kwargs:
if param in parameters:
kwargs[param... | Add and update a VO. | VO | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VO:
"""Add and update a VO."""
def POST(self, new_vo):
"""Add a VO with a given name. HTTP Success: 201 Created HTTP Error: 401 Unauthorized 409 Conflict 500 InternalError :param new_vo: VO to be added."""
<|body_0|>
def PUT(self, updated_vo):
"""Update the detai... | stack_v2_sparse_classes_36k_train_022199 | 7,903 | permissive | [
{
"docstring": "Add a VO with a given name. HTTP Success: 201 Created HTTP Error: 401 Unauthorized 409 Conflict 500 InternalError :param new_vo: VO to be added.",
"name": "POST",
"signature": "def POST(self, new_vo)"
},
{
"docstring": "Update the details for a given VO HTTP Success: 200 OK HTTP ... | 2 | null | Implement the Python class `VO` described below.
Class description:
Add and update a VO.
Method signatures and docstrings:
- def POST(self, new_vo): Add a VO with a given name. HTTP Success: 201 Created HTTP Error: 401 Unauthorized 409 Conflict 500 InternalError :param new_vo: VO to be added.
- def PUT(self, updated_... | Implement the Python class `VO` described below.
Class description:
Add and update a VO.
Method signatures and docstrings:
- def POST(self, new_vo): Add a VO with a given name. HTTP Success: 201 Created HTTP Error: 401 Unauthorized 409 Conflict 500 InternalError :param new_vo: VO to be added.
- def PUT(self, updated_... | bf33d9441d3b4ff160a392eed56724f635a03fe6 | <|skeleton|>
class VO:
"""Add and update a VO."""
def POST(self, new_vo):
"""Add a VO with a given name. HTTP Success: 201 Created HTTP Error: 401 Unauthorized 409 Conflict 500 InternalError :param new_vo: VO to be added."""
<|body_0|>
def PUT(self, updated_vo):
"""Update the detai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VO:
"""Add and update a VO."""
def POST(self, new_vo):
"""Add a VO with a given name. HTTP Success: 201 Created HTTP Error: 401 Unauthorized 409 Conflict 500 InternalError :param new_vo: VO to be added."""
json_data = data().decode()
kwargs = {'description': None, 'email': None}
... | the_stack_v2_python_sparse | lib/rucio/web/rest/webpy/v1/vo.py | viveknigam3003/rucio | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.