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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35b28acc7c552cf47a2b605c156dc1a5e51e3fda | [
"ancestor = None\n\ndef find_nodes(node) -> int:\n nonlocal ancestor\n if not node:\n return 0\n found_from_left = find_nodes(node.left)\n if found_from_left == 2:\n return 2\n if found_from_left == 1 and node.val in {p.val, q.val}:\n ancestor = node\n return 2\n found_... | <|body_start_0|>
ancestor = None
def find_nodes(node) -> int:
nonlocal ancestor
if not node:
return 0
found_from_left = find_nodes(node.left)
if found_from_left == 2:
return 2
if found_from_left == 1 and node.va... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/25/2019 19:40"""
<|body_0|>
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/21/2021 16:57"""
<|bo... | stack_v2_sparse_classes_36k_train_034200 | 4,875 | no_license | [
{
"docstring": "08/25/2019 19:40",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "08/21/2021 16:57",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 08/25/2019 19:40
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 08/25/2019 19:40
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/25/2019 19:40"""
<|body_0|>
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/21/2021 16:57"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/25/2019 19:40"""
ancestor = None
def find_nodes(node) -> int:
nonlocal ancestor
if not node:
return 0
found_from_left = fin... | the_stack_v2_python_sparse | leetcode/solved/236_Lowest_Common_Ancestor_of_a_Binary_Tree/solution.py | sungminoh/algorithms | train | 0 | |
34d0cfb659245dae2c58bfc2aac6a746495b9409 | [
"super().__init__()\nself.requires = sorted(['m200c', 'z'])\nself.provides = sorted(['c200c'])\nself.mpivot = 2.0 * 1000000000000.0 / 0.7\nself.a200 = 6.71\nself.b200 = -0.091\nself.c200 = -0.44",
"indices = self._get_indices(parnames)\nmarr = ftab[:, indices[0]]\nzarr = ftab[:, indices[1]]\ncarr = self.a200 * (1... | <|body_start_0|>
super().__init__()
self.requires = sorted(['m200c', 'z'])
self.provides = sorted(['c200c'])
self.mpivot = 2.0 * 1000000000000.0 / 0.7
self.a200 = 6.71
self.b200 = -0.091
self.c200 = -0.44
<|end_body_0|>
<|body_start_1|>
indices = self._ge... | DuffyCScale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DuffyCScale:
def __init__(self):
"""Calculates NFW concentration based on M200 and redshift following Duffy et al. 2008 requires: m200c, z provides: c200c"""
<|body_0|>
def convert(self, ftab, parnames=None, point=False):
"""Performs conversion :param ftab: np 2D arr... | stack_v2_sparse_classes_36k_train_034201 | 8,315 | no_license | [
{
"docstring": "Calculates NFW concentration based on M200 and redshift following Duffy et al. 2008 requires: m200c, z provides: c200c",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Performs conversion :param ftab: np 2D array containing the parameters, must be sorted... | 2 | stack_v2_sparse_classes_30k_train_001279 | Implement the Python class `DuffyCScale` described below.
Class description:
Implement the DuffyCScale class.
Method signatures and docstrings:
- def __init__(self): Calculates NFW concentration based on M200 and redshift following Duffy et al. 2008 requires: m200c, z provides: c200c
- def convert(self, ftab, parname... | Implement the Python class `DuffyCScale` described below.
Class description:
Implement the DuffyCScale class.
Method signatures and docstrings:
- def __init__(self): Calculates NFW concentration based on M200 and redshift following Duffy et al. 2008 requires: m200c, z provides: c200c
- def convert(self, ftab, parname... | 927f61410e643a6cfba6464a70e4126a450fc0bb | <|skeleton|>
class DuffyCScale:
def __init__(self):
"""Calculates NFW concentration based on M200 and redshift following Duffy et al. 2008 requires: m200c, z provides: c200c"""
<|body_0|>
def convert(self, ftab, parnames=None, point=False):
"""Performs conversion :param ftab: np 2D arr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DuffyCScale:
def __init__(self):
"""Calculates NFW concentration based on M200 and redshift following Duffy et al. 2008 requires: m200c, z provides: c200c"""
super().__init__()
self.requires = sorted(['m200c', 'z'])
self.provides = sorted(['c200c'])
self.mpivot = 2.0 * ... | the_stack_v2_python_sparse | sublens/model/astroconvert.py | vargatn/subhalo_lensing | train | 1 | |
fa3de8a9ccaae415fbcf60dc9553c8daa6d1c070 | [
"super(CreateVendorPartForm, self).__init__(*args, **kwargs)\nsettings = Settings.get_settings()\nif settings:\n self.owner.get_label = operator.attrgetter(settings.name_order)",
"initial_validation = super(CreateVendorPartForm, self).validate()\nerrors = False\nif not initial_validation:\n errors = True\nv... | <|body_start_0|>
super(CreateVendorPartForm, self).__init__(*args, **kwargs)
settings = Settings.get_settings()
if settings:
self.owner.get_label = operator.attrgetter(settings.name_order)
<|end_body_0|>
<|body_start_1|>
initial_validation = super(CreateVendorPartForm, self)... | CreateVendorPartForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateVendorPartForm:
def __init__(self, *args, **kwargs):
"""Create instance."""
<|body_0|>
def validate(self):
"""Validate the form."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CreateVendorPartForm, self).__init__(*args, **kwargs)
... | stack_v2_sparse_classes_36k_train_034202 | 2,184 | permissive | [
{
"docstring": "Create instance.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Validate the form.",
"name": "validate",
"signature": "def validate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016328 | Implement the Python class `CreateVendorPartForm` described below.
Class description:
Implement the CreateVendorPartForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create instance.
- def validate(self): Validate the form. | Implement the Python class `CreateVendorPartForm` described below.
Class description:
Implement the CreateVendorPartForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create instance.
- def validate(self): Validate the form.
<|skeleton|>
class CreateVendorPartForm:
def __init__... | ecb146cc26c6ade2863bcdc6d271ead3cbcbbe40 | <|skeleton|>
class CreateVendorPartForm:
def __init__(self, *args, **kwargs):
"""Create instance."""
<|body_0|>
def validate(self):
"""Validate the form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateVendorPartForm:
def __init__(self, *args, **kwargs):
"""Create instance."""
super(CreateVendorPartForm, self).__init__(*args, **kwargs)
settings = Settings.get_settings()
if settings:
self.owner.get_label = operator.attrgetter(settings.name_order)
def val... | the_stack_v2_python_sparse | pid/vendorpart/forms.py | PlanetaryResources/pid | train | 3 | |
3b7f8af47a15834c56a6e17cb4ff1e343fccd94e | [
"self.number = len(xs)\nx2i, y2i = ({}, {})\nfor i, x in enumerate(xs):\n x2i.setdefault(x, []).append(i)\nfor i, y in enumerate(ys):\n y2i.setdefault(y, []).append(i)\nself.mat = np.array([[xs[i], ys[i]] for i in range(len(xs))])\nself.xs = np.sort(np.array(xs))\nself.ys = np.sort(np.array(ys))\nself.x2i = x... | <|body_start_0|>
self.number = len(xs)
x2i, y2i = ({}, {})
for i, x in enumerate(xs):
x2i.setdefault(x, []).append(i)
for i, y in enumerate(ys):
y2i.setdefault(y, []).append(i)
self.mat = np.array([[xs[i], ys[i]] for i in range(len(xs))])
self.xs =... | x,y coordinates for fast access, query point numbers and ids. | XY | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XY:
"""x,y coordinates for fast access, query point numbers and ids."""
def __init__(self, xs, ys):
"""xs: [1,2,3] ys: [4,5,6] xs and ys should be the same length. (x,y) is the locatation for a PET."""
<|body_0|>
def _query(self, cor, cor2i, left, right):
"""For ... | stack_v2_sparse_classes_36k_train_034203 | 11,706 | permissive | [
{
"docstring": "xs: [1,2,3] ys: [4,5,6] xs and ys should be the same length. (x,y) is the locatation for a PET.",
"name": "__init__",
"signature": "def __init__(self, xs, ys)"
},
{
"docstring": "For a sorted one-dimension numpy array, query the points id in a region.",
"name": "_query",
... | 5 | null | Implement the Python class `XY` described below.
Class description:
x,y coordinates for fast access, query point numbers and ids.
Method signatures and docstrings:
- def __init__(self, xs, ys): xs: [1,2,3] ys: [4,5,6] xs and ys should be the same length. (x,y) is the locatation for a PET.
- def _query(self, cor, cor2... | Implement the Python class `XY` described below.
Class description:
x,y coordinates for fast access, query point numbers and ids.
Method signatures and docstrings:
- def __init__(self, xs, ys): xs: [1,2,3] ys: [4,5,6] xs and ys should be the same length. (x,y) is the locatation for a PET.
- def _query(self, cor, cor2... | 3b29b4195bc65516120b6c5731c0496231648063 | <|skeleton|>
class XY:
"""x,y coordinates for fast access, query point numbers and ids."""
def __init__(self, xs, ys):
"""xs: [1,2,3] ys: [4,5,6] xs and ys should be the same length. (x,y) is the locatation for a PET."""
<|body_0|>
def _query(self, cor, cor2i, left, right):
"""For ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XY:
"""x,y coordinates for fast access, query point numbers and ids."""
def __init__(self, xs, ys):
"""xs: [1,2,3] ys: [4,5,6] xs and ys should be the same length. (x,y) is the locatation for a PET."""
self.number = len(xs)
x2i, y2i = ({}, {})
for i, x in enumerate(xs):
... | the_stack_v2_python_sparse | build/lib/cLoops2/ds.py | YaqiangCao/cLoops2 | train | 39 |
45cb95ebc021cfeb4cf30e61286646e57b3a1e6b | [
"dsObs = self.build_observational_dataset(fileName)\nobsDescriptor = LatLonGridDescriptor.read(ds=dsObs, latVarName='lat', lonVarName='lon')\ndsObs.close()\nreturn obsDescriptor",
"dsObs = xr.open_dataset(fileName)\ndsObs.iMONTH.values += 1\ndsObs.rename({'month': 'calmonth', 'lat': 'latCoord', 'lon': 'lonCoord',... | <|body_start_0|>
dsObs = self.build_observational_dataset(fileName)
obsDescriptor = LatLonGridDescriptor.read(ds=dsObs, latVarName='lat', lonVarName='lon')
dsObs.close()
return obsDescriptor
<|end_body_0|>
<|body_start_1|>
dsObs = xr.open_dataset(fileName)
dsObs.iMONTH.v... | A subtask for reading and remapping MLD observations Authors ------- Luke Van Roekel, Xylar Asay-Davis, Milena Veneziani | RemapObservedMLDClimatology | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemapObservedMLDClimatology:
"""A subtask for reading and remapping MLD observations Authors ------- Luke Van Roekel, Xylar Asay-Davis, Milena Veneziani"""
def get_observation_descriptor(self, fileName):
"""get a MeshDescriptor for the observation grid Parameters ---------- fileName ... | stack_v2_sparse_classes_36k_train_034204 | 7,963 | no_license | [
{
"docstring": "get a MeshDescriptor for the observation grid Parameters ---------- fileName : str observation file name describing the source grid Returns ------- obsDescriptor : ``MeshDescriptor`` The descriptor for the observation grid Authors ------- Xylar Asay-Davis",
"name": "get_observation_descripto... | 2 | null | Implement the Python class `RemapObservedMLDClimatology` described below.
Class description:
A subtask for reading and remapping MLD observations Authors ------- Luke Van Roekel, Xylar Asay-Davis, Milena Veneziani
Method signatures and docstrings:
- def get_observation_descriptor(self, fileName): get a MeshDescriptor... | Implement the Python class `RemapObservedMLDClimatology` described below.
Class description:
A subtask for reading and remapping MLD observations Authors ------- Luke Van Roekel, Xylar Asay-Davis, Milena Veneziani
Method signatures and docstrings:
- def get_observation_descriptor(self, fileName): get a MeshDescriptor... | e56da52b9885a79c051e2f0f7c2619e14caf8a21 | <|skeleton|>
class RemapObservedMLDClimatology:
"""A subtask for reading and remapping MLD observations Authors ------- Luke Van Roekel, Xylar Asay-Davis, Milena Veneziani"""
def get_observation_descriptor(self, fileName):
"""get a MeshDescriptor for the observation grid Parameters ---------- fileName ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemapObservedMLDClimatology:
"""A subtask for reading and remapping MLD observations Authors ------- Luke Van Roekel, Xylar Asay-Davis, Milena Veneziani"""
def get_observation_descriptor(self, fileName):
"""get a MeshDescriptor for the observation grid Parameters ---------- fileName : str observa... | the_stack_v2_python_sparse | mpas_analysis/ocean/climatology_map_mld.py | zengxiaoqing/MPAS-Analysis | train | 0 |
b5727d03dc434eeda4aefbba241518a172c772dd | [
"json_parser = RequestParser()\njson_parser.add_argument('target', type=parser.user_id, required=True, location='json')\nargs = json_parser.parse_args()\ntarget = args.target\nif target == g.user_id:\n return ({'message': 'User cannot follow self.'}, 400)\nret = 1\ntry:\n follow = Relation(user_id=g.user_id, ... | <|body_start_0|>
json_parser = RequestParser()
json_parser.add_argument('target', type=parser.user_id, required=True, location='json')
args = json_parser.parse_args()
target = args.target
if target == g.user_id:
return ({'message': 'User cannot follow self.'}, 400)
... | 关注用户 | FollowingListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowingListResource:
"""关注用户"""
def post(self):
"""关注用户"""
<|body_0|>
def get(self):
"""获取关注的用户列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_parser = RequestParser()
json_parser.add_argument('target', type=parser.user_id, req... | stack_v2_sparse_classes_36k_train_034205 | 6,555 | no_license | [
{
"docstring": "关注用户",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "获取关注的用户列表",
"name": "get",
"signature": "def get(self)"
}
] | 2 | null | Implement the Python class `FollowingListResource` described below.
Class description:
关注用户
Method signatures and docstrings:
- def post(self): 关注用户
- def get(self): 获取关注的用户列表 | Implement the Python class `FollowingListResource` described below.
Class description:
关注用户
Method signatures and docstrings:
- def post(self): 关注用户
- def get(self): 获取关注的用户列表
<|skeleton|>
class FollowingListResource:
"""关注用户"""
def post(self):
"""关注用户"""
<|body_0|>
def get(self):
... | 12b52f21a4ec20b4853870468c28d2385dc185a8 | <|skeleton|>
class FollowingListResource:
"""关注用户"""
def post(self):
"""关注用户"""
<|body_0|>
def get(self):
"""获取关注的用户列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FollowingListResource:
"""关注用户"""
def post(self):
"""关注用户"""
json_parser = RequestParser()
json_parser.add_argument('target', type=parser.user_id, required=True, location='json')
args = json_parser.parse_args()
target = args.target
if target == g.user_id:
... | the_stack_v2_python_sparse | flask_prj/tbd_42/toutiao/resources/user/following.py | 123wuyu/demo_prj | train | 1 |
00cc7b4c028b54b035a1c1661c0ab55390264dec | [
"robot.sort()\nfactory.sort()\n\n@cache\ndef dp(i, j, k) -> int:\n if i == len(robot):\n return 0\n if j == len(factory):\n return math.inf\n return min(dp(i, j + 1, 0), dp(i + 1, j, k + 1) + abs(robot[i] - factory[j][0]) if factory[j][1] > k else math.inf)\nreturn dp(0, 0, 0)",
"cnt = Coun... | <|body_start_0|>
robot.sort()
factory.sort()
@cache
def dp(i, j, k) -> int:
if i == len(robot):
return 0
if j == len(factory):
return math.inf
return min(dp(i, j + 1, 0), dp(i + 1, j, k + 1) + abs(robot[i] - factory[j][... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
"""Ref: https://leetcode.cn/problems/minimum-total-distance-traveled/discuss/2783305/Python-DP-Solution Runtime: 2908 ms, faster than 50.00% Memory Usage: 445.2 MB, less than 100.00% 1 <= robot.l... | stack_v2_sparse_classes_36k_train_034206 | 2,985 | permissive | [
{
"docstring": "Ref: https://leetcode.cn/problems/minimum-total-distance-traveled/discuss/2783305/Python-DP-Solution Runtime: 2908 ms, faster than 50.00% Memory Usage: 445.2 MB, less than 100.00% 1 <= robot.length, factory.length <= 100 factory[j].length == 2 -10^9 <= robot[i], positionj <= 10^9 0 <= limitj <= ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: Ref: https://leetcode.cn/problems/minimum-total-distance-traveled/discuss/2783305/Python-DP-Sol... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: Ref: https://leetcode.cn/problems/minimum-total-distance-traveled/discuss/2783305/Python-DP-Sol... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
"""Ref: https://leetcode.cn/problems/minimum-total-distance-traveled/discuss/2783305/Python-DP-Solution Runtime: 2908 ms, faster than 50.00% Memory Usage: 445.2 MB, less than 100.00% 1 <= robot.l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
"""Ref: https://leetcode.cn/problems/minimum-total-distance-traveled/discuss/2783305/Python-DP-Solution Runtime: 2908 ms, faster than 50.00% Memory Usage: 445.2 MB, less than 100.00% 1 <= robot.length, factory... | the_stack_v2_python_sparse | src/2463-MinimumTotalDistanceTraveled.py | Jiezhi/myleetcode | train | 1 | |
d25059110956a59cf2b5760b5b38a38df93f4aa0 | [
"Module.__init__(self)\nself.acq_func = acq_function\nmodel = self.acq_func.model\nif hasattr(acq_function, 'X_pending'):\n if acq_function.X_pending is not None:\n raise UnsupportedError('Proximal acquisition function requires `X_pending` to be None.')\n self.X_pending = acq_function.X_pending\nself.r... | <|body_start_0|>
Module.__init__(self)
self.acq_func = acq_function
model = self.acq_func.model
if hasattr(acq_function, 'X_pending'):
if acq_function.X_pending is not None:
raise UnsupportedError('Proximal acquisition function requires `X_pending` to be None.... | A wrapper around AcquisitionFunctions to add proximal weighting of the acquisition function. The acquisition function is weighted via a squared exponential centered at the last training point, with varying lengthscales corresponding to `proximal_weights`. Can only be used with acquisition functions based on single batc... | ProximalAcquisitionFunction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProximalAcquisitionFunction:
"""A wrapper around AcquisitionFunctions to add proximal weighting of the acquisition function. The acquisition function is weighted via a squared exponential centered at the last training point, with varying lengthscales corresponding to `proximal_weights`. Can only ... | stack_v2_sparse_classes_36k_train_034207 | 8,229 | permissive | [
{
"docstring": "Derived Acquisition Function weighted by proximity to recently observed point. Args: acq_function: The base acquisition function, operating on input tensors of feature dimension `d`. proximal_weights: A `d` dim tensor used to bias locality along each axis. transformed_weighting: If True, the pro... | 2 | stack_v2_sparse_classes_30k_train_018335 | Implement the Python class `ProximalAcquisitionFunction` described below.
Class description:
A wrapper around AcquisitionFunctions to add proximal weighting of the acquisition function. The acquisition function is weighted via a squared exponential centered at the last training point, with varying lengthscales corresp... | Implement the Python class `ProximalAcquisitionFunction` described below.
Class description:
A wrapper around AcquisitionFunctions to add proximal weighting of the acquisition function. The acquisition function is weighted via a squared exponential centered at the last training point, with varying lengthscales corresp... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class ProximalAcquisitionFunction:
"""A wrapper around AcquisitionFunctions to add proximal weighting of the acquisition function. The acquisition function is weighted via a squared exponential centered at the last training point, with varying lengthscales corresponding to `proximal_weights`. Can only ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProximalAcquisitionFunction:
"""A wrapper around AcquisitionFunctions to add proximal weighting of the acquisition function. The acquisition function is weighted via a squared exponential centered at the last training point, with varying lengthscales corresponding to `proximal_weights`. Can only be used with ... | the_stack_v2_python_sparse | botorch/acquisition/proximal.py | pytorch/botorch | train | 2,891 |
309c85fdf9231ca1d2f9311f344808ff18f9d27f | [
"config = {'foo': 'bar'}\nconfigs = hyperrun.chain([config])\nself.assertEqual(len(configs), 1)",
"configs1 = [{'foo': 'bar'}, {'bar': 'foo'}]\nconfigs = hyperrun.chain(configs1)\nself.assertEqual(len(configs), 2)",
"configs1 = [{'foo': 'bar'}, {'bar': 'foo'}]\nconfigs2 = [{'thomas': 'edison'}, {'life': '42'}]\... | <|body_start_0|>
config = {'foo': 'bar'}
configs = hyperrun.chain([config])
self.assertEqual(len(configs), 1)
<|end_body_0|>
<|body_start_1|>
configs1 = [{'foo': 'bar'}, {'bar': 'foo'}]
configs = hyperrun.chain(configs1)
self.assertEqual(len(configs), 2)
<|end_body_1|>
... | Test cases for chaining configuration dictionaries. | TestHyperRunChain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHyperRunChain:
"""Test cases for chaining configuration dictionaries."""
def test_single_configuration(self):
"""Single configuration gives back a single configuration."""
<|body_0|>
def test_no_chain_two_configurations(self):
"""Two configurations from same ... | stack_v2_sparse_classes_36k_train_034208 | 3,278 | permissive | [
{
"docstring": "Single configuration gives back a single configuration.",
"name": "test_single_configuration",
"signature": "def test_single_configuration(self)"
},
{
"docstring": "Two configurations from same list do not get chained.",
"name": "test_no_chain_two_configurations",
"signat... | 3 | stack_v2_sparse_classes_30k_train_005748 | Implement the Python class `TestHyperRunChain` described below.
Class description:
Test cases for chaining configuration dictionaries.
Method signatures and docstrings:
- def test_single_configuration(self): Single configuration gives back a single configuration.
- def test_no_chain_two_configurations(self): Two conf... | Implement the Python class `TestHyperRunChain` described below.
Class description:
Test cases for chaining configuration dictionaries.
Method signatures and docstrings:
- def test_single_configuration(self): Single configuration gives back a single configuration.
- def test_no_chain_two_configurations(self): Two conf... | 0f0f654e488a1839455786ccc4ad023c0aa0c2e8 | <|skeleton|>
class TestHyperRunChain:
"""Test cases for chaining configuration dictionaries."""
def test_single_configuration(self):
"""Single configuration gives back a single configuration."""
<|body_0|>
def test_no_chain_two_configurations(self):
"""Two configurations from same ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestHyperRunChain:
"""Test cases for chaining configuration dictionaries."""
def test_single_configuration(self):
"""Single configuration gives back a single configuration."""
config = {'foo': 'bar'}
configs = hyperrun.chain([config])
self.assertEqual(len(configs), 1)
... | the_stack_v2_python_sparse | utils/test_hyperrun.py | nuric/pix2rule | train | 10 |
e8803fb0b37441fc39afd7061341d8695d73ff35 | [
"super(__class__, self).__init__()\nself.parent = parent\nself.app = app\nuic.loadUi(self.app.theme['ui_path'] + '/AddFriendDialog.ui', self)\nself.setWindowTitle('Add Chum')\nself.setWindowIcon(QIcon(app.theme['path'] + '/trayicon.png'))\nself.acceptButton.clicked.connect(self.accepted)\nself.rejectButton.clicked.... | <|body_start_0|>
super(__class__, self).__init__()
self.parent = parent
self.app = app
uic.loadUi(self.app.theme['ui_path'] + '/AddFriendDialog.ui', self)
self.setWindowTitle('Add Chum')
self.setWindowIcon(QIcon(app.theme['path'] + '/trayicon.png'))
self.acceptBut... | AddFriendDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddFriendDialog:
def __init__(self, app, parent):
"""Dialog opened when the Add [Chum] button is pressed, adds to chumsTree widget"""
<|body_0|>
def accepted(self):
"""Call once accepted, check if name is alphanumeric if not warn and try again"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_034209 | 40,316 | permissive | [
{
"docstring": "Dialog opened when the Add [Chum] button is pressed, adds to chumsTree widget",
"name": "__init__",
"signature": "def __init__(self, app, parent)"
},
{
"docstring": "Call once accepted, check if name is alphanumeric if not warn and try again",
"name": "accepted",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_003996 | Implement the Python class `AddFriendDialog` described below.
Class description:
Implement the AddFriendDialog class.
Method signatures and docstrings:
- def __init__(self, app, parent): Dialog opened when the Add [Chum] button is pressed, adds to chumsTree widget
- def accepted(self): Call once accepted, check if na... | Implement the Python class `AddFriendDialog` described below.
Class description:
Implement the AddFriendDialog class.
Method signatures and docstrings:
- def __init__(self, app, parent): Dialog opened when the Add [Chum] button is pressed, adds to chumsTree widget
- def accepted(self): Call once accepted, check if na... | 70be67f3671b35aa6cbe6e4eb66a4a1c07707ce3 | <|skeleton|>
class AddFriendDialog:
def __init__(self, app, parent):
"""Dialog opened when the Add [Chum] button is pressed, adds to chumsTree widget"""
<|body_0|>
def accepted(self):
"""Call once accepted, check if name is alphanumeric if not warn and try again"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddFriendDialog:
def __init__(self, app, parent):
"""Dialog opened when the Add [Chum] button is pressed, adds to chumsTree widget"""
super(__class__, self).__init__()
self.parent = parent
self.app = app
uic.loadUi(self.app.theme['ui_path'] + '/AddFriendDialog.ui', self... | the_stack_v2_python_sparse | dialogs.py | henry232323/Pesterchum-Discord | train | 28 | |
b9615ce8bc2be6d03eb7b42569210928da8d3a93 | [
"@functools.wraps(udf)\ndef wrapper() -> None:\n udf_args, udf_kwargs = self._prepare_udf_args(udf=udf, fp_config=fp_config)\n output = udf(*udf_args, **udf_kwargs)\n self.udf_output_receiver.ingest_udf_output(output, fp_config)\nreturn wrapper",
"args = ()\nkwargs = {**self.udf_arg_provider.provide_inpu... | <|body_start_0|>
@functools.wraps(udf)
def wrapper() -> None:
udf_args, udf_kwargs = self._prepare_udf_args(udf=udf, fp_config=fp_config)
output = udf(*udf_args, **udf_kwargs)
self.udf_output_receiver.ingest_udf_output(output, fp_config)
return wrapper
<|end_b... | Class that wraps a user provided function. | UDFWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDFWrapper:
"""Class that wraps a user provided function."""
def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]:
"""Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function i... | stack_v2_sparse_classes_36k_train_034210 | 3,203 | permissive | [
{
"docstring": "Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function includes but is not limited to loading data sources and ingesting output data to a Feature Group. Args: udf (Callable[..., T]): The feature_processor wrapped user function. f... | 2 | null | Implement the Python class `UDFWrapper` described below.
Class description:
Class that wraps a user provided function.
Method signatures and docstrings:
- def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]: Wrap the provided UDF with the logic defined by the FeatureProcess... | Implement the Python class `UDFWrapper` described below.
Class description:
Class that wraps a user provided function.
Method signatures and docstrings:
- def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]: Wrap the provided UDF with the logic defined by the FeatureProcess... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class UDFWrapper:
"""Class that wraps a user provided function."""
def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]:
"""Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UDFWrapper:
"""Class that wraps a user provided function."""
def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]:
"""Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function includes but i... | the_stack_v2_python_sparse | src/sagemaker/feature_store/feature_processor/_udf_wrapper.py | aws/sagemaker-python-sdk | train | 2,050 |
c8ce2598aa05bd3adc8c7388f79798981336b44e | [
"self.check_parameters(params)\nexp = np.exp(1j * params[0])\nreturn UnitaryMatrix([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, exp]])",
"self.check_param... | <|body_start_0|>
self.check_parameters(params)
exp = np.exp(1j * params[0])
return UnitaryMatrix([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, ... | A gate representing a controlled controlled phase rotation. It is given by the following parameterized unitary: .. math:: \\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\ 0 & 0 ... | CCPGate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CCPGate:
"""A gate representing a controlled controlled phase rotation. It is given by the following parameterized unitary: .. math:: \\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\ 0 & 0 ... | stack_v2_sparse_classes_36k_train_034211 | 2,518 | permissive | [
{
"docstring": "Return the unitary for this gate, see :class:`Unitary` for more.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: RealVector=[]) -> UnitaryMatrix"
},
{
"docstring": "Return the gradient for this gate. See :class:`DifferentiableUnitary` for more info.",
"na... | 2 | null | Implement the Python class `CCPGate` described below.
Class description:
A gate representing a controlled controlled phase rotation. It is given by the following parameterized unitary: .. math:: \\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\ 0 ... | Implement the Python class `CCPGate` described below.
Class description:
A gate representing a controlled controlled phase rotation. It is given by the following parameterized unitary: .. math:: \\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\ 0 ... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class CCPGate:
"""A gate representing a controlled controlled phase rotation. It is given by the following parameterized unitary: .. math:: \\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\ 0 & 0 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CCPGate:
"""A gate representing a controlled controlled phase rotation. It is given by the following parameterized unitary: .. math:: \\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 0 & 0 & 1 &... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/ccp.py | BQSKit/bqskit | train | 54 |
cb1d212b910ea79590f24b94688c37d533801cc9 | [
"super().__init__()\nself._model = deepcopy(model)\nself._num_outputs = self._model.num_outputs\nseed = torch.tensor(seed if seed is not None else torch.randint(0, 1000000, (1,)).item())\nself.register_buffer('_seed', seed)",
"try:\n return self._Xs\nexcept AttributeError:\n return None",
"try:\n retur... | <|body_start_0|>
super().__init__()
self._model = deepcopy(model)
self._num_outputs = self._model.num_outputs
seed = torch.tensor(seed if seed is not None else torch.randint(0, 1000000, (1,)).item())
self.register_buffer('_seed', seed)
<|end_body_0|>
<|body_start_1|>
try... | Convenience wrapper for sampling a function from a GP prior. This wrapper implicitly defines the GP sample as a self-updating function by keeping track of the evaluated points and respective base samples used during the evaluation. This does not yet support multi-output models. | GPDraw | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPDraw:
"""Convenience wrapper for sampling a function from a GP prior. This wrapper implicitly defines the GP sample as a self-updating function by keeping track of the evaluated points and respective base samples used during the evaluation. This does not yet support multi-output models."""
... | stack_v2_sparse_classes_36k_train_034212 | 20,040 | permissive | [
{
"docstring": "Construct a GP function sampler. Args: model: The Model defining the GP prior.",
"name": "__init__",
"signature": "def __init__(self, model: Model, seed: Optional[int]=None) -> None"
},
{
"docstring": "A `(batch_shape) x n_eval x d`-dim tensor of locations at which the GP was eva... | 4 | null | Implement the Python class `GPDraw` described below.
Class description:
Convenience wrapper for sampling a function from a GP prior. This wrapper implicitly defines the GP sample as a self-updating function by keeping track of the evaluated points and respective base samples used during the evaluation. This does not y... | Implement the Python class `GPDraw` described below.
Class description:
Convenience wrapper for sampling a function from a GP prior. This wrapper implicitly defines the GP sample as a self-updating function by keeping track of the evaluated points and respective base samples used during the evaluation. This does not y... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class GPDraw:
"""Convenience wrapper for sampling a function from a GP prior. This wrapper implicitly defines the GP sample as a self-updating function by keeping track of the evaluated points and respective base samples used during the evaluation. This does not yet support multi-output models."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GPDraw:
"""Convenience wrapper for sampling a function from a GP prior. This wrapper implicitly defines the GP sample as a self-updating function by keeping track of the evaluated points and respective base samples used during the evaluation. This does not yet support multi-output models."""
def __init__... | the_stack_v2_python_sparse | botorch/utils/gp_sampling.py | pytorch/botorch | train | 2,891 |
5a504c26ff87c705e1d6f63ebe6dcbe01c522f4f | [
"if self.imdb and self.imdb.thumb_image:\n return self.imdb.thumb_image.url\nif self.rotten_tomatoes and self.rotten_tomatoes.thumb_uri:\n return self.rotten_tomatoes.thumb_uri\nreturn None",
"plot_summary = None\nif self.imdb and self.imdb.plot_outline:\n plot_summary = self.imdb.plot_outline\nreturn pl... | <|body_start_0|>
if self.imdb and self.imdb.thumb_image:
return self.imdb.thumb_image.url
if self.rotten_tomatoes and self.rotten_tomatoes.thumb_uri:
return self.rotten_tomatoes.thumb_uri
return None
<|end_body_0|>
<|body_start_1|>
plot_summary = None
if ... | Content metadata container. | ContentMetadata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentMetadata:
"""Content metadata container."""
def thumb_uri(self):
"""Gets the preferred thumbnail URI from available metadata sources."""
<|body_0|>
def plot_summary(self):
"""Gets the preferred plot summary from available metadata sources."""
<|bod... | stack_v2_sparse_classes_36k_train_034213 | 16,456 | no_license | [
{
"docstring": "Gets the preferred thumbnail URI from available metadata sources.",
"name": "thumb_uri",
"signature": "def thumb_uri(self)"
},
{
"docstring": "Gets the preferred plot summary from available metadata sources.",
"name": "plot_summary",
"signature": "def plot_summary(self)"
... | 3 | null | Implement the Python class `ContentMetadata` described below.
Class description:
Content metadata container.
Method signatures and docstrings:
- def thumb_uri(self): Gets the preferred thumbnail URI from available metadata sources.
- def plot_summary(self): Gets the preferred plot summary from available metadata sour... | Implement the Python class `ContentMetadata` described below.
Class description:
Content metadata container.
Method signatures and docstrings:
- def thumb_uri(self): Gets the preferred thumbnail URI from available metadata sources.
- def plot_summary(self): Gets the preferred plot summary from available metadata sour... | 06a7b524054b329ea2171ae8d080f286ee19b783 | <|skeleton|>
class ContentMetadata:
"""Content metadata container."""
def thumb_uri(self):
"""Gets the preferred thumbnail URI from available metadata sources."""
<|body_0|>
def plot_summary(self):
"""Gets the preferred plot summary from available metadata sources."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContentMetadata:
"""Content metadata container."""
def thumb_uri(self):
"""Gets the preferred thumbnail URI from available metadata sources."""
if self.imdb and self.imdb.thumb_image:
return self.imdb.thumb_image.url
if self.rotten_tomatoes and self.rotten_tomatoes.thu... | the_stack_v2_python_sparse | venclave/models.py | kazimuth/media-enclave | train | 2 |
20e7991f4068a4b7c31b61b3a22a35b4a3a510be | [
"super().__init__()\nself.n_layers = n_layers\nif residuals is not None:\n residuals = residuals.lower()\nself.residuals = residuals\nself.layers = nn.ModuleList()\nfor _ in range(n_layers - 1):\n self.layers.append(MLPBlock(features_in=features_in, features_out=n_features, activation_factory=activation_facto... | <|body_start_0|>
super().__init__()
self.n_layers = n_layers
if residuals is not None:
residuals = residuals.lower()
self.residuals = residuals
self.layers = nn.ModuleList()
for _ in range(n_layers - 1):
self.layers.append(MLPBlock(features_in=feat... | A fully-connected feed-forward neural network. The MLP can be used both as a fully-connected on 2D data as well as a module in a CNN. When used with 4D output the input is automatically permuted so that features are oriented along the last dimension of the input tensor. | MLP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""A fully-connected feed-forward neural network. The MLP can be used both as a fully-connected on 2D data as well as a module in a CNN. When used with 4D output the input is automatically permuted so that features are oriented along the last dimension of the input tensor."""
def __init... | stack_v2_sparse_classes_36k_train_034214 | 9,125 | permissive | [
{
"docstring": "Create MLP module. Args: features_in: Number of features in the input. n_features: Number of features of the hidden layers. features_out: Number of features of the output. n_layers: The number of layers. residuals: The type of residual connections in the MLP: None, 'simple', or 'hyper'. activati... | 2 | stack_v2_sparse_classes_30k_train_016107 | Implement the Python class `MLP` described below.
Class description:
A fully-connected feed-forward neural network. The MLP can be used both as a fully-connected on 2D data as well as a module in a CNN. When used with 4D output the input is automatically permuted so that features are oriented along the last dimension ... | Implement the Python class `MLP` described below.
Class description:
A fully-connected feed-forward neural network. The MLP can be used both as a fully-connected on 2D data as well as a module in a CNN. When used with 4D output the input is automatically permuted so that features are oriented along the last dimension ... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class MLP:
"""A fully-connected feed-forward neural network. The MLP can be used both as a fully-connected on 2D data as well as a module in a CNN. When used with 4D output the input is automatically permuted so that features are oriented along the last dimension of the input tensor."""
def __init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLP:
"""A fully-connected feed-forward neural network. The MLP can be used both as a fully-connected on 2D data as well as a module in a CNN. When used with 4D output the input is automatically permuted so that features are oriented along the last dimension of the input tensor."""
def __init__(self, feat... | the_stack_v2_python_sparse | quantnn/models/pytorch/fully_connected.py | simonpf/quantnn | train | 7 |
a966b5b6e49d1b8dd50721541fe866b7c4c5a03b | [
"self.day = day\nself.month = month\nself.year = year",
"if cls.is_valid_date(astring):\n day, month, year = map(int, astring.split('-'))\n return cls(day, month, year)\nelse:\n raise IOError(f'{astring!r} is not a valid date string.')",
"try:\n day, month, year = map(int, astring.split('-'))\nexcep... | <|body_start_0|>
self.day = day
self.month = month
self.year = year
<|end_body_0|>
<|body_start_1|>
if cls.is_valid_date(astring):
day, month, year = map(int, astring.split('-'))
return cls(day, month, year)
else:
raise IOError(f'{astring!r} i... | Source: https://stackoverflow.com/questions/12179271 | Date | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Date:
"""Source: https://stackoverflow.com/questions/12179271"""
def __init__(self, day=0, month=0, year=0):
"""Initialize from day, month and year values (no verification)."""
<|body_0|>
def from_string(cls, astring):
"""Initialize from (verified) 'day-month-yea... | stack_v2_sparse_classes_36k_train_034215 | 3,912 | no_license | [
{
"docstring": "Initialize from day, month and year values (no verification).",
"name": "__init__",
"signature": "def __init__(self, day=0, month=0, year=0)"
},
{
"docstring": "Initialize from (verified) 'day-month-year' string.",
"name": "from_string",
"signature": "def from_string(cls,... | 3 | stack_v2_sparse_classes_30k_train_002270 | Implement the Python class `Date` described below.
Class description:
Source: https://stackoverflow.com/questions/12179271
Method signatures and docstrings:
- def __init__(self, day=0, month=0, year=0): Initialize from day, month and year values (no verification).
- def from_string(cls, astring): Initialize from (ver... | Implement the Python class `Date` described below.
Class description:
Source: https://stackoverflow.com/questions/12179271
Method signatures and docstrings:
- def __init__(self, day=0, month=0, year=0): Initialize from day, month and year values (no verification).
- def from_string(cls, astring): Initialize from (ver... | dd931c09fe5229907a93f3c3992924650abb3315 | <|skeleton|>
class Date:
"""Source: https://stackoverflow.com/questions/12179271"""
def __init__(self, day=0, month=0, year=0):
"""Initialize from day, month and year values (no verification)."""
<|body_0|>
def from_string(cls, astring):
"""Initialize from (verified) 'day-month-yea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Date:
"""Source: https://stackoverflow.com/questions/12179271"""
def __init__(self, day=0, month=0, year=0):
"""Initialize from day, month and year values (no verification)."""
self.day = day
self.month = month
self.year = year
def from_string(cls, astring):
"... | the_stack_v2_python_sparse | Cours/avance.py | ycopin/Informatique-Python | train | 3 |
588b1e7ec922834ad5143bae0e228b55142a06a4 | [
"self.cell = cell\nself.shape = shape\nself.dimension = cell.dimension\nself.Nsites = np.prod(shape) * self.cell.Nsites\nself.sites = np.zeros(self.shape + [self.cell.Nsites], dtype='object')\nself.bonds = []\nself.build_sites()\nself.build_bonds()",
"for i in range(self.shape[0]):\n for j in range(self.shape[... | <|body_start_0|>
self.cell = cell
self.shape = shape
self.dimension = cell.dimension
self.Nsites = np.prod(shape) * self.cell.Nsites
self.sites = np.zeros(self.shape + [self.cell.Nsites], dtype='object')
self.bonds = []
self.build_sites()
self.build_bonds(... | Class for lattice | Lattice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lattice:
"""Class for lattice"""
def __init__(self, cell, shape):
"""Initialize of lattice instance Parameters ---------- cell : Cell Cell class shape : list a list of three integer dimension : int dimension of the lattice, which can be one two or three Nsites : int number of sites i... | stack_v2_sparse_classes_36k_train_034216 | 7,577 | permissive | [
{
"docstring": "Initialize of lattice instance Parameters ---------- cell : Cell Cell class shape : list a list of three integer dimension : int dimension of the lattice, which can be one two or three Nsites : int number of sites in the lattice sites : numpy array numpy array for element of site object bonds : ... | 6 | stack_v2_sparse_classes_30k_train_009740 | Implement the Python class `Lattice` described below.
Class description:
Class for lattice
Method signatures and docstrings:
- def __init__(self, cell, shape): Initialize of lattice instance Parameters ---------- cell : Cell Cell class shape : list a list of three integer dimension : int dimension of the lattice, whi... | Implement the Python class `Lattice` described below.
Class description:
Class for lattice
Method signatures and docstrings:
- def __init__(self, cell, shape): Initialize of lattice instance Parameters ---------- cell : Cell Cell class shape : list a list of three integer dimension : int dimension of the lattice, whi... | 9b6323857fc27b17056ad6c8520d4a10a23dad4b | <|skeleton|>
class Lattice:
"""Class for lattice"""
def __init__(self, cell, shape):
"""Initialize of lattice instance Parameters ---------- cell : Cell Cell class shape : list a list of three integer dimension : int dimension of the lattice, which can be one two or three Nsites : int number of sites i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lattice:
"""Class for lattice"""
def __init__(self, cell, shape):
"""Initialize of lattice instance Parameters ---------- cell : Cell Cell class shape : list a list of three integer dimension : int dimension of the lattice, which can be one two or three Nsites : int number of sites in the lattice... | the_stack_v2_python_sparse | moha/modelsystem/lattice.py | xujunyao0928/moha | train | 0 |
f2cbee85eeee28d7bedd2bba061443e939cd89b9 | [
"F = [float('inf') for _ in range(366 + 30)]\nfor i in range(366, 366 + 30):\n F[i] = 0\ndays_set = set(days)\nfor i in range(365, 0, -1):\n if i not in days_set:\n F[i] = F[i + 1]\n else:\n F[i] = min((c + F[i + d] for d, c in zip([1, 7, 30], costs)))\nreturn F[1]",
"n = len(days)\nF = [fl... | <|body_start_0|>
F = [float('inf') for _ in range(366 + 30)]
for i in range(366, 366 + 30):
F[i] = 0
days_set = set(days)
for i in range(365, 0, -1):
if i not in days_set:
F[i] = F[i + 1]
else:
F[i] = min((c + F[i + d] f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
"""Iterate backward. Why does iterate backward work? Currrent min depends on the future mins Let F[i] be the min cost at day i, covering all trips from i to 365 F[i] = min(F[i + d] + c for d, c in zip([1, 7, 30... | stack_v2_sparse_classes_36k_train_034217 | 4,205 | no_license | [
{
"docstring": "Iterate backward. Why does iterate backward work? Currrent min depends on the future mins Let F[i] be the min cost at day i, covering all trips from i to 365 F[i] = min(F[i + d] + c for d, c in zip([1, 7, 30], costs)) If day i is not travel day, then wait until i + k that is a travel day O(365)"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mincostTickets(self, days: List[int], costs: List[int]) -> int: Iterate backward. Why does iterate backward work? Currrent min depends on the future mins Let F[i] be the min ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mincostTickets(self, days: List[int], costs: List[int]) -> int: Iterate backward. Why does iterate backward work? Currrent min depends on the future mins Let F[i] be the min ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
"""Iterate backward. Why does iterate backward work? Currrent min depends on the future mins Let F[i] be the min cost at day i, covering all trips from i to 365 F[i] = min(F[i + d] + c for d, c in zip([1, 7, 30... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
"""Iterate backward. Why does iterate backward work? Currrent min depends on the future mins Let F[i] be the min cost at day i, covering all trips from i to 365 F[i] = min(F[i + d] + c for d, c in zip([1, 7, 30], costs)) If ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/983 Minimum Cost For Tickets.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
54f166f08813310ce20a7b5ee504de8323429b3e | [
"team_list = list(Southerner.objects.by_season(season))\nif len(team_list) > 0:\n rank = 1\n previous = team_list[0]\n previous.rank = 1\n for i, entry in enumerate(team_list[1:]):\n if entry.avg_points_per_game != previous.avg_points_per_game:\n rank = i + 2\n entry.rank = ... | <|body_start_0|>
team_list = list(Southerner.objects.by_season(season))
if len(team_list) > 0:
rank = 1
previous = team_list[0]
previous.rank = 1
for i, entry in enumerate(team_list[1:]):
if entry.avg_points_per_game != previous.avg_points_... | View for displaying the Southerners League stats for a particular season | SouthernersSeasonView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SouthernersSeasonView:
"""View for displaying the Southerners League stats for a particular season"""
def get_southerners_list(self, season):
"""Returns a list of Southerners League items for the specified season"""
<|body_0|>
def get_context_data(self, **kwargs):
... | stack_v2_sparse_classes_36k_train_034218 | 7,907 | no_license | [
{
"docstring": "Returns a list of Southerners League items for the specified season",
"name": "get_southerners_list",
"signature": "def get_southerners_list(self, season)"
},
{
"docstring": "Gets the context data for the view. In addition to the 'team_list' item, the following are also added to ... | 2 | stack_v2_sparse_classes_30k_train_018340 | Implement the Python class `SouthernersSeasonView` described below.
Class description:
View for displaying the Southerners League stats for a particular season
Method signatures and docstrings:
- def get_southerners_list(self, season): Returns a list of Southerners League items for the specified season
- def get_cont... | Implement the Python class `SouthernersSeasonView` described below.
Class description:
View for displaying the Southerners League stats for a particular season
Method signatures and docstrings:
- def get_southerners_list(self, season): Returns a list of Southerners League items for the specified season
- def get_cont... | d85aa4522c4ffa603efa9e8625fc7253fb7550b5 | <|skeleton|>
class SouthernersSeasonView:
"""View for displaying the Southerners League stats for a particular season"""
def get_southerners_list(self, season):
"""Returns a list of Southerners League items for the specified season"""
<|body_0|>
def get_context_data(self, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SouthernersSeasonView:
"""View for displaying the Southerners League stats for a particular season"""
def get_southerners_list(self, season):
"""Returns a list of Southerners League items for the specified season"""
team_list = list(Southerner.objects.by_season(season))
if len(tea... | the_stack_v2_python_sparse | src/teams/views.py | cshc/cshc-web | train | 3 |
f8e4500485dcd758c213ecdb8e04e9e747ff0640 | [
"from SALib.analyze import morris\ndata, n_samples = preclean_X(data, feature_names, feature_types)\npredict_fn, n_classes, _ = determine_classes(model, data, n_samples)\nif 3 <= n_classes:\n raise Exception('multiclass MorrisSensitivity not supported')\npredict_fn = unify_predict_fn(predict_fn, data, 1 if n_cla... | <|body_start_0|>
from SALib.analyze import morris
data, n_samples = preclean_X(data, feature_names, feature_types)
predict_fn, n_classes, _ = determine_classes(model, data, n_samples)
if 3 <= n_classes:
raise Exception('multiclass MorrisSensitivity not supported')
pre... | Method of Morris for analyzing blackbox systems. If using this please cite the package owners as can be found here: https://github.com/SALib/SALib Morris, Max D. "Factorial sampling plans for preliminary computational experiments." Technometrics 33.2 (1991): 161-174. | MorrisSensitivity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MorrisSensitivity:
"""Method of Morris for analyzing blackbox systems. If using this please cite the package owners as can be found here: https://github.com/SALib/SALib Morris, Max D. "Factorial sampling plans for preliminary computational experiments." Technometrics 33.2 (1991): 161-174."""
... | stack_v2_sparse_classes_36k_train_034219 | 10,783 | permissive | [
{
"docstring": "Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regression) data: Data used to initialize LIME with. feature_names: List of feature names. feature_types: List of feature types. sampler: A SamplerMixin derrived class that can ... | 2 | stack_v2_sparse_classes_30k_train_018021 | Implement the Python class `MorrisSensitivity` described below.
Class description:
Method of Morris for analyzing blackbox systems. If using this please cite the package owners as can be found here: https://github.com/SALib/SALib Morris, Max D. "Factorial sampling plans for preliminary computational experiments." Tech... | Implement the Python class `MorrisSensitivity` described below.
Class description:
Method of Morris for analyzing blackbox systems. If using this please cite the package owners as can be found here: https://github.com/SALib/SALib Morris, Max D. "Factorial sampling plans for preliminary computational experiments." Tech... | e6f38ea195aecbbd9d28c7183a83c65ada16e1ae | <|skeleton|>
class MorrisSensitivity:
"""Method of Morris for analyzing blackbox systems. If using this please cite the package owners as can be found here: https://github.com/SALib/SALib Morris, Max D. "Factorial sampling plans for preliminary computational experiments." Technometrics 33.2 (1991): 161-174."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MorrisSensitivity:
"""Method of Morris for analyzing blackbox systems. If using this please cite the package owners as can be found here: https://github.com/SALib/SALib Morris, Max D. "Factorial sampling plans for preliminary computational experiments." Technometrics 33.2 (1991): 161-174."""
def __init__... | the_stack_v2_python_sparse | python/interpret-core/interpret/blackbox/_sensitivity.py | interpretml/interpret | train | 3,731 |
b8cfb5b4a2f19b775e84ee30e2382a288a5a590f | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units=units)\nself.U = tf.keras.layers.Dense(units=units)\nself.V = tf.keras.layers.Dense(units=1)",
"score = self.V(tf.nn.tanh(self.W(tf.expand_dims(s_prev, axis=1)) + self.U(hidden_states)))\nw = tf.nn.softmax(score, axis=1)\nreturn (tf.redu... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)
self.V = tf.keras.layers.Dense(units=1)
<|end_body_0|>
<|body_start_1|>
score = self.V(tf.nn.tanh(self.W(tf.expand_dims(s_prev, axis=1))... | [summary] Args: tf ([type]): [description] | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, units):
"""[summary] Args: units ([type]): [description]"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""[summary] Args: s_prev ([type]): [description] hidden_states ([type... | stack_v2_sparse_classes_36k_train_034220 | 1,089 | no_license | [
{
"docstring": "[summary] Args: units ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "[summary] Args: s_prev ([type]): [description] hidden_states ([type]): [description] Returns: [type]: [description]",
"name": "call",
"signature... | 2 | stack_v2_sparse_classes_30k_train_012265 | Implement the Python class `SelfAttention` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, units): [summary] Args: units ([type]): [description]
- def call(self, s_prev, hidden_states): [summary] Args: s_prev ([type]): [description]... | Implement the Python class `SelfAttention` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, units): [summary] Args: units ([type]): [description]
- def call(self, s_prev, hidden_states): [summary] Args: s_prev ([type]): [description]... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class SelfAttention:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, units):
"""[summary] Args: units ([type]): [description]"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""[summary] Args: s_prev ([type]): [description] hidden_states ([type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, units):
"""[summary] Args: units ([type]): [description]"""
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
1fd41dbcbb07d51ddf961e62787d70ad5a2a23e1 | [
"m, n = (len(grid), len(grid[0]))\ndirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\ndef dfs(cur, pre, visited, mark):\n visited[cur[0]][cur[1]] = True\n for dx, dy in dirs:\n i, j = (cur[0] + dx, cur[1] + dy)\n if i < 0 or i >= m or j < 0 or (j >= n) or (grid[i][j] != mark):\n continue\n ... | <|body_start_0|>
m, n = (len(grid), len(grid[0]))
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(cur, pre, visited, mark):
visited[cur[0]][cur[1]] = True
for dx, dy in dirs:
i, j = (cur[0] + dx, cur[1] + dy)
if i < 0 or i >= m or j < 0 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsCycle(self, grid):
""":type grid: List[List[str]] :rtype: bool"""
<|body_0|>
def containsCycleUF(self, grid):
""":type grid: List[List[str]] :rtype: bool"""
<|body_1|>
def containsCycleTLE(self, grid):
""":type grid: List[Li... | stack_v2_sparse_classes_36k_train_034221 | 28,242 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: bool",
"name": "containsCycle",
"signature": "def containsCycle(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: bool",
"name": "containsCycleUF",
"signature": "def containsCycleUF(self, grid)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_014071 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsCycle(self, grid): :type grid: List[List[str]] :rtype: bool
- def containsCycleUF(self, grid): :type grid: List[List[str]] :rtype: bool
- def containsCycleTLE(self, g... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsCycle(self, grid): :type grid: List[List[str]] :rtype: bool
- def containsCycleUF(self, grid): :type grid: List[List[str]] :rtype: bool
- def containsCycleTLE(self, g... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def containsCycle(self, grid):
""":type grid: List[List[str]] :rtype: bool"""
<|body_0|>
def containsCycleUF(self, grid):
""":type grid: List[List[str]] :rtype: bool"""
<|body_1|>
def containsCycleTLE(self, grid):
""":type grid: List[Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsCycle(self, grid):
""":type grid: List[List[str]] :rtype: bool"""
m, n = (len(grid), len(grid[0]))
dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(cur, pre, visited, mark):
visited[cur[0]][cur[1]] = True
for dx, dy in dirs:
... | the_stack_v2_python_sparse | D/DetectCyclesin2DGrid.py | bssrdf/pyleet | train | 2 | |
986b27ecd3188def636acd8d3dca2b517b53693d | [
"self.name = name\nself.international = international\nself.emoji = emoji",
"tag = session.query(Tag).get(name)\nif tag and emoji:\n tag.emoji = True\n if tag.international is True:\n tag.international = False\nif tag and (not international) and tag.international:\n tag.international = False\nif t... | <|body_start_0|>
self.name = name
self.international = international
self.emoji = emoji
<|end_body_0|>
<|body_start_1|>
tag = session.query(Tag).get(name)
if tag and emoji:
tag.emoji = True
if tag.international is True:
tag.international =... | The model for a sticker. | Tag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
<|body_0|>
def get_or_create(session, name, international, emoji=False):
"""Get or create a new sticker."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_034222 | 1,813 | permissive | [
{
"docstring": "Create a new sticker.",
"name": "__init__",
"signature": "def __init__(self, name, international, emoji)"
},
{
"docstring": "Get or create a new sticker.",
"name": "get_or_create",
"signature": "def get_or_create(session, name, international, emoji=False)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000302 | Implement the Python class `Tag` described below.
Class description:
The model for a sticker.
Method signatures and docstrings:
- def __init__(self, name, international, emoji): Create a new sticker.
- def get_or_create(session, name, international, emoji=False): Get or create a new sticker. | Implement the Python class `Tag` described below.
Class description:
The model for a sticker.
Method signatures and docstrings:
- def __init__(self, name, international, emoji): Create a new sticker.
- def get_or_create(session, name, international, emoji=False): Get or create a new sticker.
<|skeleton|>
class Tag:
... | 873468f8de26cc32d1de9b688140569b8086ab5b | <|skeleton|>
class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
<|body_0|>
def get_or_create(session, name, international, emoji=False):
"""Get or create a new sticker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
self.name = name
self.international = international
self.emoji = emoji
def get_or_create(session, name, international, emoji=False):
"""Get or creat... | the_stack_v2_python_sparse | stickerfinder/models/tag.py | arlessweschler/sticker-finder | train | 0 |
5e03adcad67aef73b6801d5bf8aad51652f4b4eb | [
"bin1, bin2, w2 = self._calc_bin(logits, target)\nw1 = 1 - w2\nnlp = -F.log_softmax(logits, dim=-1)\nB = _get_indexer(logits.shape[:-1])\nloss = w1 * nlp[B + (bin1,)] + w2 * nlp[B + (bin2,)]\nneg_entropy = w1.xlogy(w1) + w2.xlogy(w2)\nreturn (loss + neg_entropy).relu()",
"support = self._calc_support(logits.shape... | <|body_start_0|>
bin1, bin2, w2 = self._calc_bin(logits, target)
w1 = 1 - w2
nlp = -F.log_softmax(logits, dim=-1)
B = _get_indexer(logits.shape[:-1])
loss = w1 * nlp[B + (bin1,)] + w2 * nlp[B + (bin2,)]
neg_entropy = w1.xlogy(w1) + w2.xlogy(w2)
return (loss + neg_... | A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being one of the ``n`` values. If a target value y is not an integer, it is treated as having prabability mass of :math:... | DiscreteRegressionLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteRegressionLoss:
"""A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being one of the ``n`` values. If a target value y is not an integer, ... | stack_v2_sparse_classes_36k_train_034223 | 31,133 | permissive | [
{
"docstring": "Caculate the loss. Args: logits: shape is [B, n] target: the shape is [B] Returns: loss with the same shape as target",
"name": "__call__",
"signature": "def __call__(self, logits: torch.Tensor, target: torch.Tensor)"
},
{
"docstring": "Calculate the expected predition in the unt... | 3 | stack_v2_sparse_classes_30k_train_011325 | Implement the Python class `DiscreteRegressionLoss` described below.
Class description:
A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being one of the ``n`` values. ... | Implement the Python class `DiscreteRegressionLoss` described below.
Class description:
A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being one of the ``n`` values. ... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class DiscreteRegressionLoss:
"""A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being one of the ``n`` values. If a target value y is not an integer, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteRegressionLoss:
"""A loss for predicting the distribution of a scalar. The target is assumed to be in the range ``[-(n-1)//2, n//2]``, where ``n=logits.shape[-1]``. The logits are used to calculate the probabilities of being one of the ``n`` values. If a target value y is not an integer, it is treated... | the_stack_v2_python_sparse | alf/utils/losses.py | HorizonRobotics/alf | train | 288 |
a1972b4d8f3596122d2702566b4cd8114896bee6 | [
"if len(matrix) == 0:\n self.cummatrix = []\nelse:\n m, n = (len(matrix), len(matrix[0]))\n self.cummatrix = [[0] * (n + 1) for i in range(m + 1)]\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n self.cummatrix[i][j] = matrix[i - 1][j - 1] + self.cummatrix[i - 1][j] + self.cum... | <|body_start_0|>
if len(matrix) == 0:
self.cummatrix = []
else:
m, n = (len(matrix), len(matrix[0]))
self.cummatrix = [[0] * (n + 1) for i in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
self.cummatr... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k_train_034224 | 1,255 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 921abbb1b0add8f92fb2d4e034950d8a31b9c90c | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if len(matrix) == 0:
self.cummatrix = []
else:
m, n = (len(matrix), len(matrix[0]))
self.cummatrix = [[0] * (n + 1) for i in range(m + 1)]... | the_stack_v2_python_sparse | 304. Range Sum Query 2D - Immutable.py | jlyang1990/LeetCode | train | 5 | |
11fa30e8782ebdf7a7437bf5c552604d1d6129e1 | [
"bg = self.bg\nif bg is None or bg.bgPr is None:\n self._change_to_noFill_bg()\nreturn self.bg.bgPr",
"self._remove_bg()\nbg = self.get_or_add_bg()\nbg.add_noFill_bgPr()\nreturn bg"
] | <|body_start_0|>
bg = self.bg
if bg is None or bg.bgPr is None:
self._change_to_noFill_bg()
return self.bg.bgPr
<|end_body_0|>
<|body_start_1|>
self._remove_bg()
bg = self.get_or_add_bg()
bg.add_noFill_bgPr()
return bg
<|end_body_1|>
| `p:cSld` element. | CT_CommonSlideData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_CommonSlideData:
"""`p:cSld` element."""
def get_or_add_bgPr(self):
"""Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added."""
<|body_0|>
def _change_to_no... | stack_v2_sparse_classes_36k_train_034225 | 10,213 | permissive | [
{
"docstring": "Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added.",
"name": "get_or_add_bgPr",
"signature": "def get_or_add_bgPr(self)"
},
{
"docstring": "Establish a `p:bg` child ... | 2 | null | Implement the Python class `CT_CommonSlideData` described below.
Class description:
`p:cSld` element.
Method signatures and docstrings:
- def get_or_add_bgPr(self): Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settin... | Implement the Python class `CT_CommonSlideData` described below.
Class description:
`p:cSld` element.
Method signatures and docstrings:
- def get_or_add_bgPr(self): Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settin... | 61257cdf1a3bc79534e88d1f50a0885a688f04c2 | <|skeleton|>
class CT_CommonSlideData:
"""`p:cSld` element."""
def get_or_add_bgPr(self):
"""Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added."""
<|body_0|>
def _change_to_no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_CommonSlideData:
"""`p:cSld` element."""
def get_or_add_bgPr(self):
"""Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added."""
bg = self.bg
if bg is None or bg.bgPr ... | the_stack_v2_python_sparse | pptx/oxml/slide.py | AndreasSteiner/python-pptx | train | 2 |
8336e3d9585e60a7489e4b03d54ca5cec00c3c43 | [
"if not strs:\n return ''\nfor k, v in enumerate(zip(*strs)):\n if len(set(v)) > 1:\n return strs[0][:k]\nreturn min(strs, key=len)",
"if not strs:\n return ''\nshort_str = min(strs, key=len)\nfor k, v in enumerate(short_str):\n for i in strs:\n if i[k] != v:\n return short_st... | <|body_start_0|>
if not strs:
return ''
for k, v in enumerate(zip(*strs)):
if len(set(v)) > 1:
return strs[0][:k]
return min(strs, key=len)
<|end_body_0|>
<|body_start_1|>
if not strs:
return ''
short_str = min(strs, key=len)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
"""编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 主要用了Python的解包,和zip将可迭代对象打包成一个tuple(元组) 还是用了enumerate()函数,将一个可遍历的数据对象,组合为一个索引序列,同时列出数据和数据下标。 :type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
... | stack_v2_sparse_classes_36k_train_034226 | 1,481 | no_license | [
{
"docstring": "编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 \"\"。 主要用了Python的解包,和zip将可迭代对象打包成一个tuple(元组) 还是用了enumerate()函数,将一个可遍历的数据对象,组合为一个索引序列,同时列出数据和数据下标。 :type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": "常规解法... | 2 | stack_v2_sparse_classes_30k_train_001932 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 主要用了Python的解包,和zip将可迭代对象打包成一个tuple(元组) 还是用了enumerate()函数,将一个可遍历的数据对象,组合为一个索引序列,同时列出数据和数据下标。 :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 主要用了Python的解包,和zip将可迭代对象打包成一个tuple(元组) 还是用了enumerate()函数,将一个可遍历的数据对象,组合为一个索引序列,同时列出数据和数据下标。 :typ... | f5de348cbc00fc24ca0282235fac6d819817d005 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
"""编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 主要用了Python的解包,和zip将可迭代对象打包成一个tuple(元组) 还是用了enumerate()函数,将一个可遍历的数据对象,组合为一个索引序列,同时列出数据和数据下标。 :type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix(self, strs):
"""编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 主要用了Python的解包,和zip将可迭代对象打包成一个tuple(元组) 还是用了enumerate()函数,将一个可遍历的数据对象,组合为一个索引序列,同时列出数据和数据下标。 :type strs: List[str] :rtype: str"""
if not strs:
return ''
for k, v in enumerate(zip(*... | the_stack_v2_python_sparse | 10-20/14.py | hubogle/PythonCode | train | 0 | |
30e84a1acbd5db1380c984ead3159692317285cf | [
"if command.strip() is None:\n return (False, COMMON_NONE)\ntry:\n command_result = cls.list_result_command(command)\n if 0 == dict_flag:\n return (True, command_result)\n command_dict_list = cls.trans_list_to_dict(command_result, start, end, changeKeys)\nexcept:\n return (False, COMMON_EXCEPT... | <|body_start_0|>
if command.strip() is None:
return (False, COMMON_NONE)
try:
command_result = cls.list_result_command(command)
if 0 == dict_flag:
return (True, command_result)
command_dict_list = cls.trans_list_to_dict(command_result, star... | some common function | Common | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Common:
"""some common function"""
def command_exec(cls, command, dict_flag=0, start=0, end=-1, changeKeys=None):
"""exec command then return; if dict_flag=0 return string list,if dict_flag=1 return dict list. when dict_flag=1, change string list from start to end. you can change the... | stack_v2_sparse_classes_36k_train_034227 | 3,473 | no_license | [
{
"docstring": "exec command then return; if dict_flag=0 return string list,if dict_flag=1 return dict list. when dict_flag=1, change string list from start to end. you can change the dict_key through diction changeKeys like {o:\"time\",2:\"dev\"} :param command: :param dict_flag: :param start: :param end: :par... | 5 | null | Implement the Python class `Common` described below.
Class description:
some common function
Method signatures and docstrings:
- def command_exec(cls, command, dict_flag=0, start=0, end=-1, changeKeys=None): exec command then return; if dict_flag=0 return string list,if dict_flag=1 return dict list. when dict_flag=1,... | Implement the Python class `Common` described below.
Class description:
some common function
Method signatures and docstrings:
- def command_exec(cls, command, dict_flag=0, start=0, end=-1, changeKeys=None): exec command then return; if dict_flag=0 return string list,if dict_flag=1 return dict list. when dict_flag=1,... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class Common:
"""some common function"""
def command_exec(cls, command, dict_flag=0, start=0, end=-1, changeKeys=None):
"""exec command then return; if dict_flag=0 return string list,if dict_flag=1 return dict list. when dict_flag=1, change string list from start to end. you can change the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Common:
"""some common function"""
def command_exec(cls, command, dict_flag=0, start=0, end=-1, changeKeys=None):
"""exec command then return; if dict_flag=0 return string list,if dict_flag=1 return dict list. when dict_flag=1, change string list from start to end. you can change the dict_key thr... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/sysmonitor/common.py | sdtimothy8/Coding | train | 0 |
b3b64a7ce4301645d888c09c992089dbc780d216 | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_as_by_search(self.search)\n as_s = obj_model['query_set']\n only_main_property = False\nelse:\n as_ids = kwargs.get('obj_ids').split(';')\n as_s = facade.get_as_by_ids(as_ids)\n only_main_property = True\n obj_model = None\nserializer_as =... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_as_by_search(self.search)
as_s = obj_model['query_set']
only_main_property = False
else:
as_ids = kwargs.get('obj_ids').split(';')
as_s = facade.get_as_by_ids(as_ids)
... | AsDBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of AS's by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new AS."""
<|body_1|>
def put(self, request, *args, **kwargs):
"""Update AS."""
... | stack_v2_sparse_classes_36k_train_034228 | 7,072 | permissive | [
{
"docstring": "Returns a list of AS's by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new AS.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update AS.",
"name": "... | 4 | null | Implement the Python class `AsDBView` described below.
Class description:
Implement the AsDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of AS's by ids ou dict.
- def post(self, request, *args, **kwargs): Create new AS.
- def put(self, request, *args, **kwarg... | Implement the Python class `AsDBView` described below.
Class description:
Implement the AsDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of AS's by ids ou dict.
- def post(self, request, *args, **kwargs): Create new AS.
- def put(self, request, *args, **kwarg... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class AsDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of AS's by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new AS."""
<|body_1|>
def put(self, request, *args, **kwargs):
"""Update AS."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of AS's by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_as_by_search(self.search)
as_s = obj_model['query_set']
only_main_property = False
else:
... | the_stack_v2_python_sparse | networkapi/api_asn/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
bd5c7e89b1db92f4c10cf1d243a961dfad3bb5c1 | [
"super().validate()\nif not hasattr(self, 'sourceId'):\n raise ValueError('Source ID is mandatory')\nelif self.sourceId is None:\n raise ValueError('Source ID must have a value')",
"ref = CaseReference()\nref.sourceId = d.get('sourceId')\nreturn ref"
] | <|body_start_0|>
super().validate()
if not hasattr(self, 'sourceId'):
raise ValueError('Source ID is mandatory')
elif self.sourceId is None:
raise ValueError('Source ID must have a value')
<|end_body_0|>
<|body_start_1|>
ref = CaseReference()
ref.sourceId... | Represents information about the source of a given case. | CaseReference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseReference:
"""Represents information about the source of a given case."""
def validate(self):
"""Check whether I am consistent. Raise ValueError if not."""
<|body_0|>
def from_dict(d: dict[str, str]):
"""Create a CaseReference from a dictionary representation... | stack_v2_sparse_classes_36k_train_034229 | 829 | permissive | [
{
"docstring": "Check whether I am consistent. Raise ValueError if not.",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "Create a CaseReference from a dictionary representation.",
"name": "from_dict",
"signature": "def from_dict(d: dict[str, str])"
}
] | 2 | null | Implement the Python class `CaseReference` described below.
Class description:
Represents information about the source of a given case.
Method signatures and docstrings:
- def validate(self): Check whether I am consistent. Raise ValueError if not.
- def from_dict(d: dict[str, str]): Create a CaseReference from a dict... | Implement the Python class `CaseReference` described below.
Class description:
Represents information about the source of a given case.
Method signatures and docstrings:
- def validate(self): Check whether I am consistent. Raise ValueError if not.
- def from_dict(d: dict[str, str]): Create a CaseReference from a dict... | dda3640355aee7912a7492ef0c135c35b2adeaea | <|skeleton|>
class CaseReference:
"""Represents information about the source of a given case."""
def validate(self):
"""Check whether I am consistent. Raise ValueError if not."""
<|body_0|>
def from_dict(d: dict[str, str]):
"""Create a CaseReference from a dictionary representation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CaseReference:
"""Represents information about the source of a given case."""
def validate(self):
"""Check whether I am consistent. Raise ValueError if not."""
super().validate()
if not hasattr(self, 'sourceId'):
raise ValueError('Source ID is mandatory')
elif ... | the_stack_v2_python_sparse | data-serving/reusable-data-service/data_service/model/case_reference.py | globaldothealth/list | train | 35 |
0b539af758ae92d1fe1778293f4b3a75523925b4 | [
"self.require_write_permission()\nparser = reqparse.RequestParser()\nparser.add_argument('event', type=dict)\npargs = parser.parse_args()\nevent_args = util.add_nested_arguments(pargs, 'event', {'name': str, 'location': str, 'action': str, 'value': str})\nevent = EventModel(self.client, event_args['name'], event_ar... | <|body_start_0|>
self.require_write_permission()
parser = reqparse.RequestParser()
parser.add_argument('event', type=dict)
pargs = parser.parse_args()
event_args = util.add_nested_arguments(pargs, 'event', {'name': str, 'location': str, 'action': str, 'value': str})
event... | Methods going to the /events route. | Events | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Events:
"""Methods going to the /events route."""
def post(self):
"""Create a new event and return the id and uri of the event."""
<|body_0|>
def get(self):
"""Get a list of all events. Also accepts query parameters: full=<bool> before=<int> after=<int> limit=<in... | stack_v2_sparse_classes_36k_train_034230 | 4,478 | permissive | [
{
"docstring": "Create a new event and return the id and uri of the event.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get a list of all events. Also accepts query parameters: full=<bool> before=<int> after=<int> limit=<int> offset=<int> which allows for a more fine-graine... | 2 | stack_v2_sparse_classes_30k_train_011009 | Implement the Python class `Events` described below.
Class description:
Methods going to the /events route.
Method signatures and docstrings:
- def post(self): Create a new event and return the id and uri of the event.
- def get(self): Get a list of all events. Also accepts query parameters: full=<bool> before=<int> ... | Implement the Python class `Events` described below.
Class description:
Methods going to the /events route.
Method signatures and docstrings:
- def post(self): Create a new event and return the id and uri of the event.
- def get(self): Get a list of all events. Also accepts query parameters: full=<bool> before=<int> ... | 8e0de271dc484f518a97b946a29455f6fffb88a6 | <|skeleton|>
class Events:
"""Methods going to the /events route."""
def post(self):
"""Create a new event and return the id and uri of the event."""
<|body_0|>
def get(self):
"""Get a list of all events. Also accepts query parameters: full=<bool> before=<int> after=<int> limit=<in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Events:
"""Methods going to the /events route."""
def post(self):
"""Create a new event and return the id and uri of the event."""
self.require_write_permission()
parser = reqparse.RequestParser()
parser.add_argument('event', type=dict)
pargs = parser.parse_args()
... | the_stack_v2_python_sparse | cred/resources/events.py | Tehnix/cred-server | train | 3 |
7576348745a1722575e4c4a2164b05aeca070a5f | [
"s1, s2 = ('', '')\nwhile l1:\n s1 = s1 + str(l1.val)\n l1 = l1.next\nwhile l2:\n s2 = s2 + str(l2.val)\n l2 = l2.next\nnum = int(s1[::-1]) + int(s2[::-1])\nnum = str(num)[::-1]\npivot = head = ListNode(num[0])\nfor x in num[1:]:\n head.next = ListNode(int(x))\n head = head.next\nreturn pivot",
... | <|body_start_0|>
s1, s2 = ('', '')
while l1:
s1 = s1 + str(l1.val)
l1 = l1.next
while l2:
s2 = s2 + str(l2.val)
l2 = l2.next
num = int(s1[::-1]) + int(s2[::-1])
num = str(num)[::-1]
pivot = head = ListNode(num[0])
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""先遍历生成int,求值后再生成链表。"""
<|body_0|>
def addTwoNumbers2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""内置函数divmod() x,y = divmod(m,n) x = m//n y = m%n"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_034231 | 2,266 | no_license | [
{
"docstring": "先遍历生成int,求值后再生成链表。",
"name": "addTwoNumbers1",
"signature": "def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "内置函数divmod() x,y = divmod(m,n) x = m//n y = m%n",
"name": "addTwoNumbers2",
"signature": "def addTwoNumbers2(self, l1: ListNod... | 2 | stack_v2_sparse_classes_30k_train_003318 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode: 先遍历生成int,求值后再生成链表。
- def addTwoNumbers2(self, l1: ListNode, l2: ListNode) -> ListNode: 内置函数divmod() x,y = divmod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode: 先遍历生成int,求值后再生成链表。
- def addTwoNumbers2(self, l1: ListNode, l2: ListNode) -> ListNode: 内置函数divmod() x,y = divmod... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""先遍历生成int,求值后再生成链表。"""
<|body_0|>
def addTwoNumbers2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""内置函数divmod() x,y = divmod(m,n) x = m//n y = m%n"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""先遍历生成int,求值后再生成链表。"""
s1, s2 = ('', '')
while l1:
s1 = s1 + str(l1.val)
l1 = l1.next
while l2:
s2 = s2 + str(l2.val)
l2 = l2.next
num = int(s1[... | the_stack_v2_python_sparse | 002_add-two-numbers.py | helloocc/algorithm | train | 1 | |
00a5a3ffc0610537d707eb4b4b7e1020c796e921 | [
"from collections import defaultdict\ncourseDict = defaultdict(list)\nfor relation in prerequisites:\n nextCourse, prevCourse = (relation[0], relation[1])\n courseDict[prevCourse].append(nextCourse)\nvisited = [False] * numCourses\npath = [False] * numCourses\nfor currCourse in range(numCourses):\n if self... | <|body_start_0|>
from collections import defaultdict
courseDict = defaultdict(list)
for relation in prerequisites:
nextCourse, prevCourse = (relation[0], relation[1])
courseDict[prevCourse].append(nextCourse)
visited = [False] * numCourses
path = [False] *... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
<|body_0|>
def isCyclic(self, currCourse, courseDict, path, visited):
"""backtracking method to check that no cycle would be formed... | stack_v2_sparse_classes_36k_train_034232 | 2,170 | no_license | [
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "canFinish",
"signature": "def canFinish(self, numCourses, prerequisites)"
},
{
"docstring": "backtracking method to check that no cycle would be formed starting from currCourse",
"name": "isCyc... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
- def isCyclic(self, currCourse, courseDict, path, visited... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
- def isCyclic(self, currCourse, courseDict, path, visited... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
<|body_0|>
def isCyclic(self, currCourse, courseDict, path, visited):
"""backtracking method to check that no cycle would be formed... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
from collections import defaultdict
courseDict = defaultdict(list)
for relation in prerequisites:
nextCourse, prevCourse = (relati... | the_stack_v2_python_sparse | python_leetcode_2020/Python_Leetcode_2020/207_course_schedule.py | xiangcao/Leetcode | train | 0 | |
d3f216b51814d2fe337175ea3686b86e4daa4dcd | [
"expected_topic = 'Web Server'\nexpected_message = 'Web Server (server1.example.com) is DOWN (Host Is Unreachable).'\nself.check_webhook('uptimerobot_monitor_down', expected_topic, expected_message)",
"expected_topic = 'Mail Server'\nexpected_message = '\\nMail Server (server2.example.com) is back UP (Host Is Rea... | <|body_start_0|>
expected_topic = 'Web Server'
expected_message = 'Web Server (server1.example.com) is DOWN (Host Is Unreachable).'
self.check_webhook('uptimerobot_monitor_down', expected_topic, expected_message)
<|end_body_0|>
<|body_start_1|>
expected_topic = 'Mail Server'
exp... | UptimeRobotHookTests | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UptimeRobotHookTests:
def test_uptimerobot_monitor_down(self) -> None:
"""Tests if uptimerobot monitor down is handled correctly"""
<|body_0|>
def test_uptimerobot_monitor_up(self) -> None:
"""Tests if uptimerobot monitor up is handled correctly"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_034233 | 1,971 | permissive | [
{
"docstring": "Tests if uptimerobot monitor down is handled correctly",
"name": "test_uptimerobot_monitor_down",
"signature": "def test_uptimerobot_monitor_down(self) -> None"
},
{
"docstring": "Tests if uptimerobot monitor up is handled correctly",
"name": "test_uptimerobot_monitor_up",
... | 3 | stack_v2_sparse_classes_30k_train_002798 | Implement the Python class `UptimeRobotHookTests` described below.
Class description:
Implement the UptimeRobotHookTests class.
Method signatures and docstrings:
- def test_uptimerobot_monitor_down(self) -> None: Tests if uptimerobot monitor down is handled correctly
- def test_uptimerobot_monitor_up(self) -> None: T... | Implement the Python class `UptimeRobotHookTests` described below.
Class description:
Implement the UptimeRobotHookTests class.
Method signatures and docstrings:
- def test_uptimerobot_monitor_down(self) -> None: Tests if uptimerobot monitor down is handled correctly
- def test_uptimerobot_monitor_up(self) -> None: T... | 965a25d91b6ee2db54038f5df855215fa25146b0 | <|skeleton|>
class UptimeRobotHookTests:
def test_uptimerobot_monitor_down(self) -> None:
"""Tests if uptimerobot monitor down is handled correctly"""
<|body_0|>
def test_uptimerobot_monitor_up(self) -> None:
"""Tests if uptimerobot monitor up is handled correctly"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UptimeRobotHookTests:
def test_uptimerobot_monitor_down(self) -> None:
"""Tests if uptimerobot monitor down is handled correctly"""
expected_topic = 'Web Server'
expected_message = 'Web Server (server1.example.com) is DOWN (Host Is Unreachable).'
self.check_webhook('uptimerobot... | the_stack_v2_python_sparse | zerver/webhooks/uptimerobot/tests.py | zulip/zulip | train | 20,239 | |
b33c619ced54e8195b9f7ae2135e451b4ac2ffce | [
"self.start_pose = start_pose\nself.num_pts = num_pts\nself.delta_val = delta_val\nself.dim = dim\nself.deltas = self.get_line_deltas()\nself.path = []\nself.make_path()",
"delta = np.zeros(6)\ndelta[self.dim] = self.delta_val\nreturn [delta] * self.num_pts"
] | <|body_start_0|>
self.start_pose = start_pose
self.num_pts = num_pts
self.delta_val = delta_val
self.dim = dim
self.deltas = self.get_line_deltas()
self.path = []
self.make_path()
<|end_body_0|>
<|body_start_1|>
delta = np.zeros(6)
delta[self.dim]... | Class definition for straight line in given direction. | Line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Line:
"""Class definition for straight line in given direction."""
def __init__(self, start_pose, num_pts, delta_val, dim=0):
"""Initialize Line class Args: start_pose (list): 7f pose at start of path. Best to set at robot reset pose. num_pts (int): number of points in path. path_len... | stack_v2_sparse_classes_36k_train_034234 | 8,130 | no_license | [
{
"docstring": "Initialize Line class Args: start_pose (list): 7f pose at start of path. Best to set at robot reset pose. num_pts (int): number of points in path. path_length (float): length of path in m delta_val (float): (optional) delta in m between each step. If None, end_pos must be specified. dim (int): d... | 2 | null | Implement the Python class `Line` described below.
Class description:
Class definition for straight line in given direction.
Method signatures and docstrings:
- def __init__(self, start_pose, num_pts, delta_val, dim=0): Initialize Line class Args: start_pose (list): 7f pose at start of path. Best to set at robot rese... | Implement the Python class `Line` described below.
Class description:
Class definition for straight line in given direction.
Method signatures and docstrings:
- def __init__(self, start_pose, num_pts, delta_val, dim=0): Initialize Line class Args: start_pose (list): 7f pose at start of path. Best to set at robot rese... | d15791905abf8ff5def7fd0d3e303e619fc150d1 | <|skeleton|>
class Line:
"""Class definition for straight line in given direction."""
def __init__(self, start_pose, num_pts, delta_val, dim=0):
"""Initialize Line class Args: start_pose (list): 7f pose at start of path. Best to set at robot reset pose. num_pts (int): number of points in path. path_len... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Line:
"""Class definition for straight line in given direction."""
def __init__(self, start_pose, num_pts, delta_val, dim=0):
"""Initialize Line class Args: start_pose (list): 7f pose at start of path. Best to set at robot reset pose. num_pts (int): number of points in path. path_length (float): ... | the_stack_v2_python_sparse | demos/demo_path.py | kayburns/perls2 | train | 0 |
8a80e3f9249f3fae3b1e26d093550f08fc1aae47 | [
"max_idx = nums.index(max(nums))\nfor idx, x in enumerate(nums):\n if idx != max_idx:\n if nums[max_idx] < 2 * x:\n return -1\nreturn max_idx",
"m = max(nums)\nif all((m >= 2 * x for x in nums if x != m)):\n return nums.index(m)\nreturn -1"
] | <|body_start_0|>
max_idx = nums.index(max(nums))
for idx, x in enumerate(nums):
if idx != max_idx:
if nums[max_idx] < 2 * x:
return -1
return max_idx
<|end_body_0|>
<|body_start_1|>
m = max(nums)
if all((m >= 2 * x for x in nums if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dominant_index(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dominantIndex(self, nums):
"""any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. all(iterable, /) Return T... | stack_v2_sparse_classes_36k_train_034235 | 846 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "dominant_index",
"signature": "def dominant_index(self, nums)"
},
{
"docstring": "any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. all(iterable, /) Return True if bool(x... | 2 | stack_v2_sparse_classes_30k_val_000039 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dominant_index(self, nums): :type nums: List[int] :rtype: int
- def dominantIndex(self, nums): any(iterable, /) Return True if bool(x) is True for any x in the iterable. If t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dominant_index(self, nums): :type nums: List[int] :rtype: int
- def dominantIndex(self, nums): any(iterable, /) Return True if bool(x) is True for any x in the iterable. If t... | cc7740026c3774be21ab924b99ae7596ef20d0e4 | <|skeleton|>
class Solution:
def dominant_index(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dominantIndex(self, nums):
"""any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. all(iterable, /) Return T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dominant_index(self, nums):
""":type nums: List[int] :rtype: int"""
max_idx = nums.index(max(nums))
for idx, x in enumerate(nums):
if idx != max_idx:
if nums[max_idx] < 2 * x:
return -1
return max_idx
def domina... | the_stack_v2_python_sparse | data_structure/arrays_and_strings/747_dominant_index.py | yangtao0304/hands-on-programming-exercise | train | 0 | |
73c0b537b4cea0625ec2f1e75b908c02115ec6e7 | [
"super().__init__()\nself.chs = chs\nself.upconvs = nn.ModuleList([nn.ConvTranspose2d(chs[i], chs[i + 1], 2, 2) for i in range(len(chs) - 1)])\nself.dec_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])",
"for i in range(len(self.chs) - 1):\n x = self.upconvs[i](x)\n enc_ftrs ... | <|body_start_0|>
super().__init__()
self.chs = chs
self.upconvs = nn.ModuleList([nn.ConvTranspose2d(chs[i], chs[i + 1], 2, 2) for i in range(len(chs) - 1)])
self.dec_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])
<|end_body_0|>
<|body_start_1|>
... | U-net decoder half | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""U-net decoder half"""
def __init__(self, chs=(1024, 512, 256, 128, 64)):
"""Class for U-net decoder half. Inputs: chs - The channels of the block of the encoder. Default = (1024, 512, 256, 128, 64)"""
<|body_0|>
def forward(self, x, encoder_features):
... | stack_v2_sparse_classes_36k_train_034236 | 11,891 | no_license | [
{
"docstring": "Class for U-net decoder half. Inputs: chs - The channels of the block of the encoder. Default = (1024, 512, 256, 128, 64)",
"name": "__init__",
"signature": "def __init__(self, chs=(1024, 512, 256, 128, 64))"
},
{
"docstring": "Forward of the U-net decoder. Inputs: x - Input batc... | 3 | stack_v2_sparse_classes_30k_train_006027 | Implement the Python class `Decoder` described below.
Class description:
U-net decoder half
Method signatures and docstrings:
- def __init__(self, chs=(1024, 512, 256, 128, 64)): Class for U-net decoder half. Inputs: chs - The channels of the block of the encoder. Default = (1024, 512, 256, 128, 64)
- def forward(sel... | Implement the Python class `Decoder` described below.
Class description:
U-net decoder half
Method signatures and docstrings:
- def __init__(self, chs=(1024, 512, 256, 128, 64)): Class for U-net decoder half. Inputs: chs - The channels of the block of the encoder. Default = (1024, 512, 256, 128, 64)
- def forward(sel... | 0b65d43a9bb5e70d7e4e3fcd322b47b173e16fa6 | <|skeleton|>
class Decoder:
"""U-net decoder half"""
def __init__(self, chs=(1024, 512, 256, 128, 64)):
"""Class for U-net decoder half. Inputs: chs - The channels of the block of the encoder. Default = (1024, 512, 256, 128, 64)"""
<|body_0|>
def forward(self, x, encoder_features):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""U-net decoder half"""
def __init__(self, chs=(1024, 512, 256, 128, 64)):
"""Class for U-net decoder half. Inputs: chs - The channels of the block of the encoder. Default = (1024, 512, 256, 128, 64)"""
super().__init__()
self.chs = chs
self.upconvs = nn.ModuleLi... | the_stack_v2_python_sparse | models/attackers/inversion_attacker_2.py | RamonDijkstra/AI-FACT | train | 0 |
c66281169df608b7f2b0b01f546d23ffb347e6ac | [
"response = super().get_paginated_response(data)\nresponse.data['total_pages'] = self.page.paginator.num_pages\nresponse.data['current_page'] = self.page.number\nreturn Response(response.data)",
"schema_data = super().get_paginated_response_schema(schema)\nschema_data['properties']['total_pages'] = {'type': 'inte... | <|body_start_0|>
response = super().get_paginated_response(data)
response.data['total_pages'] = self.page.paginator.num_pages
response.data['current_page'] = self.page.number
return Response(response.data)
<|end_body_0|>
<|body_start_1|>
schema_data = super().get_paginated_respo... | MyPageNumberPagination | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPageNumberPagination:
def get_paginated_response(self, data):
"""重写父类的get_paginated_response()方法 在分页后的数据构成的响应体中添加total_pages(总共分了多少页)和current_page_num(当前所在第几页)字段 @param data: @return:"""
<|body_0|>
def get_paginated_response_schema(self, schema):
"""接口文档schema"""
... | stack_v2_sparse_classes_36k_train_034237 | 1,651 | permissive | [
{
"docstring": "重写父类的get_paginated_response()方法 在分页后的数据构成的响应体中添加total_pages(总共分了多少页)和current_page_num(当前所在第几页)字段 @param data: @return:",
"name": "get_paginated_response",
"signature": "def get_paginated_response(self, data)"
},
{
"docstring": "接口文档schema",
"name": "get_paginated_response_sch... | 2 | stack_v2_sparse_classes_30k_train_008440 | Implement the Python class `MyPageNumberPagination` described below.
Class description:
Implement the MyPageNumberPagination class.
Method signatures and docstrings:
- def get_paginated_response(self, data): 重写父类的get_paginated_response()方法 在分页后的数据构成的响应体中添加total_pages(总共分了多少页)和current_page_num(当前所在第几页)字段 @param data: ... | Implement the Python class `MyPageNumberPagination` described below.
Class description:
Implement the MyPageNumberPagination class.
Method signatures and docstrings:
- def get_paginated_response(self, data): 重写父类的get_paginated_response()方法 在分页后的数据构成的响应体中添加total_pages(总共分了多少页)和current_page_num(当前所在第几页)字段 @param data: ... | 7b471d5c3fdd021564bc87d73c4e04a69059d291 | <|skeleton|>
class MyPageNumberPagination:
def get_paginated_response(self, data):
"""重写父类的get_paginated_response()方法 在分页后的数据构成的响应体中添加total_pages(总共分了多少页)和current_page_num(当前所在第几页)字段 @param data: @return:"""
<|body_0|>
def get_paginated_response_schema(self, schema):
"""接口文档schema"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyPageNumberPagination:
def get_paginated_response(self, data):
"""重写父类的get_paginated_response()方法 在分页后的数据构成的响应体中添加total_pages(总共分了多少页)和current_page_num(当前所在第几页)字段 @param data: @return:"""
response = super().get_paginated_response(data)
response.data['total_pages'] = self.page.paginato... | the_stack_v2_python_sparse | utils/drf_utils/my_page_number_pagination.py | xiaozhou9/beer_server | train | 0 | |
39c8f57757a37d5b2208c4899bd79d9d8aa7eb07 | [
"self.security = acm.FInstrument[security]\nself.position = position\nself.price = price",
"value_date = CALENDAR.AdjustBankingDays(trade_date, settle_offset)\ntrade = acm.FTrade()\ntrade.Instrument(self.security)\ntrade.Currency('ZAR')\ntrade.Counterparty(JSE)\ntrade.Acquirer(PRIME_SERVICES_DESK)\ntrade.Price(se... | <|body_start_0|>
self.security = acm.FInstrument[security]
self.position = position
self.price = price
<|end_body_0|>
<|body_start_1|>
value_date = CALENDAR.AdjustBankingDays(trade_date, settle_offset)
trade = acm.FTrade()
trade.Instrument(self.security)
trade.Cu... | Simple trade representation. Attributes: - Stock (security) - Position (to be used as quantity) - Price | RTMTrade | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RTMTrade:
"""Simple trade representation. Attributes: - Stock (security) - Position (to be used as quantity) - Price"""
def __init__(self, security, position, price):
"""Initialize the trade."""
<|body_0|>
def book(self, portfolio, settle_offset, trade_date, status, reve... | stack_v2_sparse_classes_36k_train_034238 | 12,079 | no_license | [
{
"docstring": "Initialize the trade.",
"name": "__init__",
"signature": "def __init__(self, security, position, price)"
},
{
"docstring": "Book the trade. Set revert to True if you want to close the position.",
"name": "book",
"signature": "def book(self, portfolio, settle_offset, trade... | 2 | null | Implement the Python class `RTMTrade` described below.
Class description:
Simple trade representation. Attributes: - Stock (security) - Position (to be used as quantity) - Price
Method signatures and docstrings:
- def __init__(self, security, position, price): Initialize the trade.
- def book(self, portfolio, settle_... | Implement the Python class `RTMTrade` described below.
Class description:
Simple trade representation. Attributes: - Stock (security) - Position (to be used as quantity) - Price
Method signatures and docstrings:
- def __init__(self, security, position, price): Initialize the trade.
- def book(self, portfolio, settle_... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class RTMTrade:
"""Simple trade representation. Attributes: - Stock (security) - Position (to be used as quantity) - Price"""
def __init__(self, security, position, price):
"""Initialize the trade."""
<|body_0|>
def book(self, portfolio, settle_offset, trade_date, status, reve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RTMTrade:
"""Simple trade representation. Attributes: - Stock (security) - Position (to be used as quantity) - Price"""
def __init__(self, security, position, price):
"""Initialize the trade."""
self.security = acm.FInstrument[security]
self.position = position
self.price ... | the_stack_v2_python_sparse | Python modules/rtm_migration.py | webclinic017/fa-absa-py3 | train | 0 |
b707840a3ac5ca9b4115b77edd1bcb1f8da9022d | [
"self.name = 'Ausputzer'\nTemplateFunction.__init__(self, task_config, general_config)\nself.__execute()",
"self.finish()\nself.logger.info('Lösche alle temporären SDE-Connectionfiles')\nfor v in self.general_config['connections'].values():\n for cf in v.connection_files:\n self.logger.info(cf)\n v.d... | <|body_start_0|>
self.name = 'Ausputzer'
TemplateFunction.__init__(self, task_config, general_config)
self.__execute()
<|end_body_0|>
<|body_start_1|>
self.finish()
self.logger.info('Lösche alle temporären SDE-Connectionfiles')
for v in self.general_config['connections']... | Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren | Ausputzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ausputzer:
"""Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren"""
def __init__(self, task_config, general_config):
"""Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)... | stack_v2_sparse_classes_36k_train_034239 | 1,615 | no_license | [
{
"docstring": "Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)",
"name": "__init__",
"signature": "def __init__(self, task_config, general_config)"
},
{
"docstring": "Führt den eigentlichen Funktionsablauf aus",
"name": "__execute",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_012959 | Implement the Python class `Ausputzer` described below.
Class description:
Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren
Method signatures and docstrings:
- def __init__(self, task_config, general_config): Constructor :param task_co... | Implement the Python class `Ausputzer` described below.
Class description:
Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren
Method signatures and docstrings:
- def __init__(self, task_config, general_config): Constructor :param task_co... | 65c1cdc83a40a0343800a839c6f3cbe61ec37abc | <|skeleton|>
class Ausputzer:
"""Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren"""
def __init__(self, task_config, general_config):
"""Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ausputzer:
"""Diese Funktion führt am Ende eines Imports/Tasks bestimmte Aufräumarbeiten aus: - Connection-Files löschen - Logging herunterfahren"""
def __init__(self, task_config, general_config):
"""Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)"""
s... | the_stack_v2_python_sparse | src/iLader/functions/Ausputzer.py | AGIBE/iLader | train | 0 |
15e1a85868167b095c08f3b0c857620bcf167583 | [
"l, r = (0, len(height) - 1)\nmaxArea = -1\nwhile l < r:\n maxArea = max(maxArea, min(height[l], height[r]) * (r - l))\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\nreturn maxArea",
"maxHeight = -1\nmaxPos = -1\nfor i in range(len(height)):\n if height[i] >= maxHeight:\n ... | <|body_start_0|>
l, r = (0, len(height) - 1)
maxArea = -1
while l < r:
maxArea = max(maxArea, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxArea
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l, r = (0, len(height) - 1)
maxArea =... | stack_v2_sparse_classes_36k_train_034240 | 1,827 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004225 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxArea(sel... | 31012a004ba14ddfb468a91925d86bc2dfb60dd4 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
l, r = (0, len(height) - 1)
maxArea = -1
while l < r:
maxArea = max(maxArea, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
... | the_stack_v2_python_sparse | top100like/ContainerWithMostWater.py | yuhangxiaocs/LeetCodePy | train | 1 | |
ebb951a27fb23440b35705131762458a37fbc329 | [
"self._interval = datetime.timedelta(seconds=interval)\nself._callback = callback\nself._next_run = None\nself.last_success = None\nself.last_attempt = None\nself.retries = 0",
"if self.retries == 0:\n interval = self._interval\nelse:\n backoff_secs = 2 ** self.retries * 60\n interval = datetime.timedelt... | <|body_start_0|>
self._interval = datetime.timedelta(seconds=interval)
self._callback = callback
self._next_run = None
self.last_success = None
self.last_attempt = None
self.retries = 0
<|end_body_0|>
<|body_start_1|>
if self.retries == 0:
interval = ... | Throttle_Mixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Throttle_Mixin:
def every(self, interval, callback):
"""Limit the update to a certain number of seconds."""
<|body_0|>
def _schedule_next_run(self):
"""Determine when to run next time"""
<|body_1|>
def success(self):
"""Update success variables""... | stack_v2_sparse_classes_36k_train_034241 | 2,088 | permissive | [
{
"docstring": "Limit the update to a certain number of seconds.",
"name": "every",
"signature": "def every(self, interval, callback)"
},
{
"docstring": "Determine when to run next time",
"name": "_schedule_next_run",
"signature": "def _schedule_next_run(self)"
},
{
"docstring": ... | 6 | stack_v2_sparse_classes_30k_train_001428 | Implement the Python class `Throttle_Mixin` described below.
Class description:
Implement the Throttle_Mixin class.
Method signatures and docstrings:
- def every(self, interval, callback): Limit the update to a certain number of seconds.
- def _schedule_next_run(self): Determine when to run next time
- def success(se... | Implement the Python class `Throttle_Mixin` described below.
Class description:
Implement the Throttle_Mixin class.
Method signatures and docstrings:
- def every(self, interval, callback): Limit the update to a certain number of seconds.
- def _schedule_next_run(self): Determine when to run next time
- def success(se... | 3a54de98ab107cf1266404400c7eb576007c8b17 | <|skeleton|>
class Throttle_Mixin:
def every(self, interval, callback):
"""Limit the update to a certain number of seconds."""
<|body_0|>
def _schedule_next_run(self):
"""Determine when to run next time"""
<|body_1|>
def success(self):
"""Update success variables""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Throttle_Mixin:
def every(self, interval, callback):
"""Limit the update to a certain number of seconds."""
self._interval = datetime.timedelta(seconds=interval)
self._callback = callback
self._next_run = None
self.last_success = None
self.last_attempt = None
... | the_stack_v2_python_sparse | ledmatrix/data/utils/throttle_mixin.py | mattgrogan/ledmatrix | train | 1 | |
4ad36df7c63f624ea5457349ab79c2488c67db01 | [
"confor = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s', '%H:%M:%S')\nwarfor = logging.Formatter('%(asctime)s :: %(levelname)-8s :: %(message)s', '%b-%d %H:%M:%S')\ncon = logging.StreamHandler(sys.stdout)\ncon.setLevel(logging.DEBUG)\ncon.setFormatter(confor)\nwar = logging.handlers.RotatingFileHa... | <|body_start_0|>
confor = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s', '%H:%M:%S')
warfor = logging.Formatter('%(asctime)s :: %(levelname)-8s :: %(message)s', '%b-%d %H:%M:%S')
con = logging.StreamHandler(sys.stdout)
con.setLevel(logging.DEBUG)
con.setFormatte... | Ironworks logger | IronworksLogger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IronworksLogger:
"""Ironworks logger"""
def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT):
"""init the logger"""
<|body_0|>
def log(self, toLog, logLevel):
"""wrapper for logger output"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
confor = lo... | stack_v2_sparse_classes_36k_train_034242 | 2,179 | permissive | [
{
"docstring": "init the logger",
"name": "__init__",
"signature": "def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT)"
},
{
"docstring": "wrapper for logger output",
"name": "log",
"signature": "def log(self, toLog, logLevel)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004914 | Implement the Python class `IronworksLogger` described below.
Class description:
Ironworks logger
Method signatures and docstrings:
- def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): init the logger
- def log(self, toLog, logLevel): wrapper for logger output | Implement the Python class `IronworksLogger` described below.
Class description:
Ironworks logger
Method signatures and docstrings:
- def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): init the logger
- def log(self, toLog, logLevel): wrapper for logger output
<|skeleton|>
class IronworksLogger:
"""Ironworks lo... | 37be48e37f63530dd7bf82618948ef82522699a0 | <|skeleton|>
class IronworksLogger:
"""Ironworks logger"""
def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT):
"""init the logger"""
<|body_0|>
def log(self, toLog, logLevel):
"""wrapper for logger output"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IronworksLogger:
"""Ironworks logger"""
def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT):
"""init the logger"""
confor = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s', '%H:%M:%S')
warfor = logging.Formatter('%(asctime)s :: %(levelname)-8s :: %(message)s', '%b-%... | the_stack_v2_python_sparse | ironworks/logger.py | hephaestus9/Ironworks | train | 1 |
d8fc1c09d4cb8596cd39dffbd1fdb0397f4ffc7c | [
"count = 4\nbehaviour = 'Flock'\ne = polybos.ExperimentManager(node_count=count)\ne.add_ratio_scenarios(behaviour)\nself.assertEqual(len(e.scenarios), count + 1)\nv, s = e.scenarios.items()[count / 2]\nself.assertEqual(len(s.get_behaviour_dict()[behaviour]), int(count * float(re.split('\\\\(|\\\\)|%', v)[1]) / 100.... | <|body_start_0|>
count = 4
behaviour = 'Flock'
e = polybos.ExperimentManager(node_count=count)
e.add_ratio_scenarios(behaviour)
self.assertEqual(len(e.scenarios), count + 1)
v, s = e.scenarios.items()[count / 2]
self.assertEqual(len(s.get_behaviour_dict()[behaviou... | ExperimentGeneration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperimentGeneration:
def testRatioExperimentGeneration(self):
"""Basic tests of polybos experiment generation"""
<|body_0|>
def testRuntimeModification(self):
"""Ensure that polybos appropriately propagates simulation time using the run method"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_034243 | 4,705 | no_license | [
{
"docstring": "Basic tests of polybos experiment generation",
"name": "testRatioExperimentGeneration",
"signature": "def testRatioExperimentGeneration(self)"
},
{
"docstring": "Ensure that polybos appropriately propagates simulation time using the run method",
"name": "testRuntimeModificati... | 5 | stack_v2_sparse_classes_30k_train_016962 | Implement the Python class `ExperimentGeneration` described below.
Class description:
Implement the ExperimentGeneration class.
Method signatures and docstrings:
- def testRatioExperimentGeneration(self): Basic tests of polybos experiment generation
- def testRuntimeModification(self): Ensure that polybos appropriate... | Implement the Python class `ExperimentGeneration` described below.
Class description:
Implement the ExperimentGeneration class.
Method signatures and docstrings:
- def testRatioExperimentGeneration(self): Basic tests of polybos experiment generation
- def testRuntimeModification(self): Ensure that polybos appropriate... | 2ac1194ea4fdc096e9aee79c7cdbc254c6e55b18 | <|skeleton|>
class ExperimentGeneration:
def testRatioExperimentGeneration(self):
"""Basic tests of polybos experiment generation"""
<|body_0|>
def testRuntimeModification(self):
"""Ensure that polybos appropriately propagates simulation time using the run method"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExperimentGeneration:
def testRatioExperimentGeneration(self):
"""Basic tests of polybos experiment generation"""
count = 4
behaviour = 'Flock'
e = polybos.ExperimentManager(node_count=count)
e.add_ratio_scenarios(behaviour)
self.assertEqual(len(e.scenarios), co... | the_stack_v2_python_sparse | src/polybos/test.py | andrewbolster/aietes | train | 0 | |
78682361ad36c3487a521d08ad1da6b91e5bb0de | [
"if t == 0 and len(nums) == len(set(nums)):\n return False\nfor i in range(len(nums)):\n for j in range(1, k + 1):\n if i + j >= len(nums):\n break\n if abs(nums[i + j] - nums[i]) <= t:\n return True\nreturn False",
"if k < 1 or t < 0:\n return False\nmaps = {}\nfor i ... | <|body_start_0|>
if t == 0 and len(nums) == len(set(nums)):
return False
for i in range(len(nums)):
for j in range(1, k + 1):
if i + j >= len(nums):
break
if abs(nums[i + j] - nums[i]) <= t:
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate2(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_034244 | 1,385 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool",
"name": "containsNearbyAlmostDuplicate",
"signature": "def containsNearbyAlmostDuplicate(self, nums, k, t)"
},
{
"docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool",
"name": "containsNearby... | 2 | stack_v2_sparse_classes_30k_train_005507 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool
- def containsNearbyAlmostDuplicate2(self, nums, k, t): :type nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool
- def containsNearbyAlmostDuplicate2(self, nums, k, t): :type nu... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate2(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
if t == 0 and len(nums) == len(set(nums)):
return False
for i in range(len(nums)):
for j in range(1, k + 1):
if i + ... | the_stack_v2_python_sparse | 220. Contains Duplicate III/contains3.py | Macielyoung/LeetCode | train | 1 | |
6191b0684e0069d07c310e4cb11fa694217cf713 | [
"def helper(node):\n if not node.left and (not node.right):\n return node\n elif not node.left:\n right = helper(node.right)\n return right\n elif not node.right:\n left = helper(node.left)\n node.right = node.left\n node.left = None\n return left\n left ... | <|body_start_0|>
def helper(node):
if not node.left and (not node.right):
return node
elif not node.left:
right = helper(node.right)
return right
elif not node.right:
left = helper(node.left)
node... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
<|body_0|>
def flattenClean(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k_train_034245 | 2,884 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.",
"name": "flattenCle... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.
- def flattenClean(self, root): :type root: TreeNode :rtype: None... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead.
- def flattenClean(self, root): :type root: TreeNode :rtype: None... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
<|body_0|>
def flattenClean(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: None Do not return anything, modify root in-place instead."""
def helper(node):
if not node.left and (not node.right):
return node
elif not node.left:
right = helper(node.... | the_stack_v2_python_sparse | F/FlattenBinaryTreetoLinkedList.py | bssrdf/pyleet | train | 2 | |
d6e89a5b0125c05fd721eb61667b842afc40fc97 | [
"while 1:\n try:\n self.find(By.ID, 'username').send_keys(username)\n break\n except:\n print('没有找到元素')\nself.find(By.ID, 'memberAdd_acctid').send_keys(account)\nself.find(By.ID, 'memberAdd_phone').send_keys(phone)\nself.find(By.CSS_SELECTOR, '.js_btn_save').click()",
"pages: str = self... | <|body_start_0|>
while 1:
try:
self.find(By.ID, 'username').send_keys(username)
break
except:
print('没有找到元素')
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phone)
... | 添加成员类 | AddMemberPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while 1:
try:
self.find(By.ID, 'user... | stack_v2_sparse_classes_36k_train_034246 | 4,450 | no_license | [
{
"docstring": "添加成员",
"name": "add_member",
"signature": "def add_member(self, username, account, phone)"
},
{
"docstring": "获取所有的联系人姓名",
"name": "get_member",
"signature": "def get_member(self)"
}
] | 2 | null | Implement the Python class `AddMemberPage` described below.
Class description:
添加成员类
Method signatures and docstrings:
- def add_member(self, username, account, phone): 添加成员
- def get_member(self): 获取所有的联系人姓名 | Implement the Python class `AddMemberPage` described below.
Class description:
添加成员类
Method signatures and docstrings:
- def add_member(self, username, account, phone): 添加成员
- def get_member(self): 获取所有的联系人姓名
<|skeleton|>
class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
... | 41651054386069fb3da5ec80d4acd922561f6de5 | <|skeleton|>
class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
"""添加成员"""
while 1:
try:
self.find(By.ID, 'username').send_keys(username)
break
except:
print('没有找到元素')
self.find(By.ID, 'memberAdd_ac... | the_stack_v2_python_sparse | com/python/pytest_test1/web/selenium_po/page/add_member_page.py | fengzige1993/PythonData | train | 0 |
a6e4e35c41f8794a9d63b92bf8f3b4e14cf988dd | [
"m, n = x.shape\nself.theta = np.zeros(n)\ni = 0\nwhile True:\n i += 1\n prev_theta = self.theta\n hx = 1.0 / (1 + np.exp(x.dot(self.theta)))\n H1 = 1.0 / m * hx * (1 - hx) * x.T\n H = H1.dot(x)\n gradient = -(1.0 / m) * x.T.dot(y - hx)\n self.theta = self.theta + np.linalg.inv(H).dot(gradient)... | <|body_start_0|>
m, n = x.shape
self.theta = np.zeros(n)
i = 0
while True:
i += 1
prev_theta = self.theta
hx = 1.0 / (1 + np.exp(x.dot(self.theta)))
H1 = 1.0 / m * hx * (1 - hx) * x.T
H = H1.dot(x)
gradient = -(1.0 /... | Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval) | LogisticRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegression:
"""Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval)"""
def fit(self, x, y):
"""Run Newton's Method to minimize J(theta) for logistic regression. Args: x: Training ... | stack_v2_sparse_classes_36k_train_034247 | 3,133 | no_license | [
{
"docstring": "Run Newton's Method to minimize J(theta) for logistic regression. Args: x: Training example inputs. Shape (m, n). y: Training example labels. Shape (m,).",
"name": "fit",
"signature": "def fit(self, x, y)"
},
{
"docstring": "Make a prediction given new inputs x. Args: x: Inputs o... | 2 | stack_v2_sparse_classes_30k_train_012984 | Implement the Python class `LogisticRegression` described below.
Class description:
Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval)
Method signatures and docstrings:
- def fit(self, x, y): Run Newton's Method to mini... | Implement the Python class `LogisticRegression` described below.
Class description:
Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval)
Method signatures and docstrings:
- def fit(self, x, y): Run Newton's Method to mini... | 73efc2abe0b126be53f1e8a366bd7efadaa0267a | <|skeleton|>
class LogisticRegression:
"""Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval)"""
def fit(self, x, y):
"""Run Newton's Method to minimize J(theta) for logistic regression. Args: x: Training ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogisticRegression:
"""Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval)"""
def fit(self, x, y):
"""Run Newton's Method to minimize J(theta) for logistic regression. Args: x: Training example input... | the_stack_v2_python_sparse | CS229_2018/ps1/src/p01b_logreg.py | haroldmei/MLAI | train | 1 |
593856676a0c39a1c04eda2cb186788e3395b803 | [
"super().__init__(x_ref=x_ref, p_val=p_val, x_ref_preprocessed=x_ref_preprocessed, preprocess_at_init=preprocess_at_init, update_x_ref=update_x_ref, preprocess_fn=preprocess_fn, sigma=sigma, configure_kernel_from_x_ref=configure_kernel_from_x_ref, n_permutations=n_permutations, input_shape=input_shape, data_type=da... | <|body_start_0|>
super().__init__(x_ref=x_ref, p_val=p_val, x_ref_preprocessed=x_ref_preprocessed, preprocess_at_init=preprocess_at_init, update_x_ref=update_x_ref, preprocess_fn=preprocess_fn, sigma=sigma, configure_kernel_from_x_ref=configure_kernel_from_x_ref, n_permutations=n_permutations, input_shape=input... | MMDDriftTF | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMDDriftTF:
def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=None, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, co... | stack_v2_sparse_classes_36k_train_034248 | 6,034 | permissive | [
{
"docstring": "Maximum Mean Discrepancy (MMD) data drift detector using a permutation test. Parameters ---------- x_ref Data used as reference distribution. p_val p-value used for the significance of the permutation test. x_ref_preprocessed Whether the given reference data `x_ref` has been preprocessed yet. If... | 3 | null | Implement the Python class `MMDDriftTF` described below.
Class description:
Implement the MMDDriftTF class.
Method signatures and docstrings:
- def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=No... | Implement the Python class `MMDDriftTF` described below.
Class description:
Implement the MMDDriftTF class.
Method signatures and docstrings:
- def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=No... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class MMDDriftTF:
def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=None, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MMDDriftTF:
def __init__(self, x_ref: Union[np.ndarray, list], p_val: float=0.05, x_ref_preprocessed: bool=False, preprocess_at_init: bool=True, update_x_ref: Optional[Dict[str, int]]=None, preprocess_fn: Optional[Callable]=None, kernel: Callable=GaussianRBF, sigma: Optional[np.ndarray]=None, configure_kernel... | the_stack_v2_python_sparse | alibi_detect/cd/tensorflow/mmd.py | SeldonIO/alibi-detect | train | 1,922 | |
f011f099de166710225d93a1e7b85e36fa4c0ca7 | [
"if ShowProductsAndCustomers.mongo is None:\n return 'connection not found'\nwith ShowProductsAndCustomers.mongo:\n norton_db = ShowProductsAndCustomers.mongo.connection.NortonDB\n products_list = []\n try:\n products = norton_db['products']\n products_collection = products.find()\n ... | <|body_start_0|>
if ShowProductsAndCustomers.mongo is None:
return 'connection not found'
with ShowProductsAndCustomers.mongo:
norton_db = ShowProductsAndCustomers.mongo.connection.NortonDB
products_list = []
try:
products = norton_db['prod... | show products class | ShowProductsAndCustomers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowProductsAndCustomers:
"""show products class"""
def see_products_for_rent():
"""return a list of all products"""
<|body_0|>
def see_all_different_products():
"""Returns a Python dictionary of products listed as available with the following fields: product_id,... | stack_v2_sparse_classes_36k_train_034249 | 9,178 | no_license | [
{
"docstring": "return a list of all products",
"name": "see_products_for_rent",
"signature": "def see_products_for_rent()"
},
{
"docstring": "Returns a Python dictionary of products listed as available with the following fields: product_id, description, product_type, quantity_available",
"n... | 3 | stack_v2_sparse_classes_30k_train_014567 | Implement the Python class `ShowProductsAndCustomers` described below.
Class description:
show products class
Method signatures and docstrings:
- def see_products_for_rent(): return a list of all products
- def see_all_different_products(): Returns a Python dictionary of products listed as available with the followin... | Implement the Python class `ShowProductsAndCustomers` described below.
Class description:
show products class
Method signatures and docstrings:
- def see_products_for_rent(): return a list of all products
- def see_all_different_products(): Returns a Python dictionary of products listed as available with the followin... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ShowProductsAndCustomers:
"""show products class"""
def see_products_for_rent():
"""return a list of all products"""
<|body_0|>
def see_all_different_products():
"""Returns a Python dictionary of products listed as available with the following fields: product_id,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShowProductsAndCustomers:
"""show products class"""
def see_products_for_rent():
"""return a list of all products"""
if ShowProductsAndCustomers.mongo is None:
return 'connection not found'
with ShowProductsAndCustomers.mongo:
norton_db = ShowProductsAndCus... | the_stack_v2_python_sparse | students/michael_mcdonald/lesson5/database.py | JavaRod/SP_Python220B_2019 | train | 1 |
5a7dd5447199d1584e646e5cedfe3395a1f35421 | [
"files_list = []\nfor file in os.listdir(settings.STATIC_COLOR_THEMES_DIR):\n files_list.append(os.path.splitext(file))\nchoices = [(file_name.lower(), _(file_name.replace('-', ' ').title())) for file_name, file_ext in files_list if file_ext == '.css' and file_name.lower() != 'default']\nchoices.insert(0, cls.de... | <|body_start_0|>
files_list = []
for file in os.listdir(settings.STATIC_COLOR_THEMES_DIR):
files_list.append(os.path.splitext(file))
choices = [(file_name.lower(), _(file_name.replace('-', ' ').title())) for file_name, file_ext in files_list if file_ext == '.css' and file_name.lower(... | Color Theme Setting | ColorTheme | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorTheme:
"""Color Theme Setting"""
def get_color_themes_choices(cls):
"""Get all color themes from static folder"""
<|body_0|>
def is_valid_choice(cls, user_color_theme):
"""Check if color theme is valid choice"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_034250 | 33,917 | permissive | [
{
"docstring": "Get all color themes from static folder",
"name": "get_color_themes_choices",
"signature": "def get_color_themes_choices(cls)"
},
{
"docstring": "Check if color theme is valid choice",
"name": "is_valid_choice",
"signature": "def is_valid_choice(cls, user_color_theme)"
... | 2 | stack_v2_sparse_classes_30k_train_004041 | Implement the Python class `ColorTheme` described below.
Class description:
Color Theme Setting
Method signatures and docstrings:
- def get_color_themes_choices(cls): Get all color themes from static folder
- def is_valid_choice(cls, user_color_theme): Check if color theme is valid choice | Implement the Python class `ColorTheme` described below.
Class description:
Color Theme Setting
Method signatures and docstrings:
- def get_color_themes_choices(cls): Get all color themes from static folder
- def is_valid_choice(cls, user_color_theme): Check if color theme is valid choice
<|skeleton|>
class ColorThe... | 2a0ea66f6591756eeb62da28d24daec3ad4209e8 | <|skeleton|>
class ColorTheme:
"""Color Theme Setting"""
def get_color_themes_choices(cls):
"""Get all color themes from static folder"""
<|body_0|>
def is_valid_choice(cls, user_color_theme):
"""Check if color theme is valid choice"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorTheme:
"""Color Theme Setting"""
def get_color_themes_choices(cls):
"""Get all color themes from static folder"""
files_list = []
for file in os.listdir(settings.STATIC_COLOR_THEMES_DIR):
files_list.append(os.path.splitext(file))
choices = [(file_name.lowe... | the_stack_v2_python_sparse | InvenTree/common/models.py | MedShift/InvenTree | train | 0 |
69b75dc28780c677529f123474af9b63e5c79cd9 | [
"time = self.flowsheet().config.time.first()\nsys_cost_params = self.parent_block().costing_param\nflow_in_m3yr = pyunits.convert(self.flow_in, to_units=pyunits.m ** 3 / pyunits.year)\nif self.unit_process_name == 'tramp_oil_tank':\n disposal_cost = 0.00114\n self.costing.other_var_cost = flow_in_m3yr * dispo... | <|body_start_0|>
time = self.flowsheet().config.time.first()
sys_cost_params = self.parent_block().costing_param
flow_in_m3yr = pyunits.convert(self.flow_in, to_units=pyunits.m ** 3 / pyunits.year)
if self.unit_process_name == 'tramp_oil_tank':
disposal_cost = 0.00114
... | UnitProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitProcess:
def fixed_cap(self):
""":param flow_in: Flow in to basic unit [m3/hr] :type flow_in: float"""
<|body_0|>
def elect(self):
"""Electricity intensity for basic units. :return: Electricity intensity [kWh/m3]"""
<|body_1|>
def get_costing(self, u... | stack_v2_sparse_classes_36k_train_034251 | 3,795 | permissive | [
{
"docstring": ":param flow_in: Flow in to basic unit [m3/hr] :type flow_in: float",
"name": "fixed_cap",
"signature": "def fixed_cap(self)"
},
{
"docstring": "Electricity intensity for basic units. :return: Electricity intensity [kWh/m3]",
"name": "elect",
"signature": "def elect(self)"... | 3 | stack_v2_sparse_classes_30k_train_000783 | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self): :param flow_in: Flow in to basic unit [m3/hr] :type flow_in: float
- def elect(self): Electricity intensity for basic units. :return: Electricity inten... | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self): :param flow_in: Flow in to basic unit [m3/hr] :type flow_in: float
- def elect(self): Electricity intensity for basic units. :return: Electricity inten... | 0e9713a195b50824c4d38ff6ea5db244a6f1ad57 | <|skeleton|>
class UnitProcess:
def fixed_cap(self):
""":param flow_in: Flow in to basic unit [m3/hr] :type flow_in: float"""
<|body_0|>
def elect(self):
"""Electricity intensity for basic units. :return: Electricity intensity [kWh/m3]"""
<|body_1|>
def get_costing(self, u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitProcess:
def fixed_cap(self):
""":param flow_in: Flow in to basic unit [m3/hr] :type flow_in: float"""
time = self.flowsheet().config.time.first()
sys_cost_params = self.parent_block().costing_param
flow_in_m3yr = pyunits.convert(self.flow_in, to_units=pyunits.m ** 3 / pyun... | the_stack_v2_python_sparse | watertap3/watertap3/wt_units/basic_unit.py | JamariMurke/WaterTAP3 | train | 0 | |
4eef498f79aa600c8c1a94fd9f337e2091e43c50 | [
"tools.validate_int(routine_id, min=0, max=65535, name='Routine ID')\ntools.validate_int(control_type, min=0, max=127, name='Routine control type')\nif data is not None:\n if not isinstance(data, bytes):\n raise ValueError('data must be a valid bytes object')\nrequest = Request(service=cls, subfunction=co... | <|body_start_0|>
tools.validate_int(routine_id, min=0, max=65535, name='Routine ID')
tools.validate_int(control_type, min=0, max=127, name='Routine control type')
if data is not None:
if not isinstance(data, bytes):
raise ValueError('data must be a valid bytes object'... | RoutineControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoutineControl:
def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfuncti... | stack_v2_sparse_classes_36k_train_034252 | 4,320 | permissive | [
{
"docstring": "Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfunction. Allowed values are from 0 to 0x7F :type control_type: int :param data: Optional additional data to provide to the server ... | 2 | stack_v2_sparse_classes_30k_train_007959 | Implement the Python class `RoutineControl` described below.
Class description:
Implement the RoutineControl class.
Method signatures and docstrings:
- def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request: Generates a request for RoutineControl :param routine_id: The routin... | Implement the Python class `RoutineControl` described below.
Class description:
Implement the RoutineControl class.
Method signatures and docstrings:
- def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request: Generates a request for RoutineControl :param routine_id: The routin... | 1b93cc3cd0e09a21d48881ba53aed257f841bb89 | <|skeleton|>
class RoutineControl:
def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfuncti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoutineControl:
def make_request(cls, routine_id: int, control_type: int, data: Optional[bytes]=None) -> Request:
"""Generates a request for RoutineControl :param routine_id: The routine ID. Value should be between 0 and 0xFFFF :type routine_id: int :param control_type: Service subfunction. Allowed va... | the_stack_v2_python_sparse | udsoncan/services/RoutineControl.py | pylessard/python-udsoncan | train | 477 | |
eac9947fe8db536ca3633fdd7bb41f100c38b9dd | [
"super().__init__()\nself.attention = Attention(**attention)\nself.feedforward = nn.Sequential(nn.Linear(features, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, features))\nself.attention_norm = nn.LayerNorm(features)\nself.feedforward_norm = nn.LayerNorm(features, elementwise_affine=False)",
"X = self.attention_... | <|body_start_0|>
super().__init__()
self.attention = Attention(**attention)
self.feedforward = nn.Sequential(nn.Linear(features, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, features))
self.attention_norm = nn.LayerNorm(features)
self.feedforward_norm = nn.LayerNorm(features, el... | Layer based on the original Attention is All You Need paper and is usable in graph network setups | AttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionLayer:
"""Layer based on the original Attention is All You Need paper and is usable in graph network setups"""
def __init__(self, features, hidden_dim, attention):
"""features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the... | stack_v2_sparse_classes_36k_train_034253 | 1,534 | permissive | [
{
"docstring": "features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the feedforward network",
"name": "__init__",
"signature": "def __init__(self, features, hidden_dim, attention)"
},
{
"docstring": "X - data tensor, torch.FloatTensor(batch_si... | 2 | stack_v2_sparse_classes_30k_train_009161 | Implement the Python class `AttentionLayer` described below.
Class description:
Layer based on the original Attention is All You Need paper and is usable in graph network setups
Method signatures and docstrings:
- def __init__(self, features, hidden_dim, attention): features - the number of features the layer has at ... | Implement the Python class `AttentionLayer` described below.
Class description:
Layer based on the original Attention is All You Need paper and is usable in graph network setups
Method signatures and docstrings:
- def __init__(self, features, hidden_dim, attention): features - the number of features the layer has at ... | 327844cea18a6dfe35e0dc8f5de0832343487366 | <|skeleton|>
class AttentionLayer:
"""Layer based on the original Attention is All You Need paper and is usable in graph network setups"""
def __init__(self, features, hidden_dim, attention):
"""features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentionLayer:
"""Layer based on the original Attention is All You Need paper and is usable in graph network setups"""
def __init__(self, features, hidden_dim, attention):
"""features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the feedforward ... | the_stack_v2_python_sparse | neuralDX7/models/attention/attention_layer.py | jGambit/NeuralDX7 | train | 0 |
12aa9b8b04d1fb31bc5a3b595a96e7f6f3cff27d | [
"assert self.split, 'must run {self}.split(**kwargs)'\nself.fold_loaders = []\nfor train, valid, test in self.folds:\n test_dataset_kwargs = self.dataset_kwargs.copy()\n test_dataset_kwargs['transform'] = None\n train_dataset = self.dataset_method(train, **self.dataset_kwargs)\n valid_dataset = self.dat... | <|body_start_0|>
assert self.split, 'must run {self}.split(**kwargs)'
self.fold_loaders = []
for train, valid, test in self.folds:
test_dataset_kwargs = self.dataset_kwargs.copy()
test_dataset_kwargs['transform'] = None
train_dataset = self.dataset_method(trai... | KFoldCrossTrainTestSplit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KFoldCrossTrainTestSplit:
def __call__(self, **loader_kwargs):
"""Args: batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``). sampler (Sampler, optional):... | stack_v2_sparse_classes_36k_train_034254 | 16,117 | no_license | [
{
"docstring": "Args: batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``). sampler (Sampler, optional): defines the strategy to draw samples from the dataset. If specified, :att... | 2 | null | Implement the Python class `KFoldCrossTrainTestSplit` described below.
Class description:
Implement the KFoldCrossTrainTestSplit class.
Method signatures and docstrings:
- def __call__(self, **loader_kwargs): Args: batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optiona... | Implement the Python class `KFoldCrossTrainTestSplit` described below.
Class description:
Implement the KFoldCrossTrainTestSplit class.
Method signatures and docstrings:
- def __call__(self, **loader_kwargs): Args: batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optiona... | dbb5e6a58b0ecfdb4ed3b05e5ca1841a321bd11b | <|skeleton|>
class KFoldCrossTrainTestSplit:
def __call__(self, **loader_kwargs):
"""Args: batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``). sampler (Sampler, optional):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KFoldCrossTrainTestSplit:
def __call__(self, **loader_kwargs):
"""Args: batch_size (int, optional): how many samples per batch to load (default: ``1``). shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``). sampler (Sampler, optional): defines the s... | the_stack_v2_python_sparse | myTorch/Data/DataLoaders.py | cubayang/DeepLearningForWallShearStressPredictionAndImageSegmentation | train | 0 | |
256022da831061ff2299df75f17072deb2ae98a6 | [
"direction = ((0, 1), (0, -1), (1, 0), (-1, 0))\n\ndef dfs(i, j):\n if not 0 <= i < len(grid) or not 0 <= j < len(grid[0]) or grid[i][j] == '0':\n return\n grid[i][j] = '0'\n for d in direction:\n dfs(i + d[0], j + d[1])\ncnt = 0\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\... | <|body_start_0|>
direction = ((0, 1), (0, -1), (1, 0), (-1, 0))
def dfs(i, j):
if not 0 <= i < len(grid) or not 0 <= j < len(grid[0]) or grid[i][j] == '0':
return
grid[i][j] = '0'
for d in direction:
dfs(i + d[0], j + d[1])
cnt... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands_8dir(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
direction = ((0, 1), (0, -1), ... | stack_v2_sparse_classes_36k_train_034255 | 2,293 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands_8dir",
"signature": "def numIslands_8dir(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands_8dir(self, grid): :type grid: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands_8dir(self, grid): :type grid: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands_8dir(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
direction = ((0, 1), (0, -1), (1, 0), (-1, 0))
def dfs(i, j):
if not 0 <= i < len(grid) or not 0 <= j < len(grid[0]) or grid[i][j] == '0':
return
grid[i][j] = '0... | the_stack_v2_python_sparse | co_apple/200_Number_of_Islands.py | vsdrun/lc_public | train | 6 | |
19a6329a24310d7d5560a73d590348b88b070b87 | [
"super(Encoder, self).__init__()\nself.hidden_size = hidden_size\nself.embedding = nn.Embedding(input_size, hidden_size, padding_idx=0)\nself.encoder = nn.LSTM(input_size=hidden_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True, bidirectional=True)",
"embedded = self.embedding(x)\nencoder_out... | <|body_start_0|>
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size, padding_idx=0)
self.encoder = nn.LSTM(input_size=hidden_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True, bidirectional=True)
<|end... | Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, input_size, hidden_size, num_layers):
""":param input_size: vob_size :param hidden_size: 越大可以夠更好地記憶長序列中的信息 :param num_layers: 越大更好地捕捉輸入序列中的抽象特徵"""
<|body_0|>
def forward(self, x, encoder_hidden):
""":param x: (batch_size, seq_len) :param e... | stack_v2_sparse_classes_36k_train_034256 | 16,677 | permissive | [
{
"docstring": ":param input_size: vob_size :param hidden_size: 越大可以夠更好地記憶長序列中的信息 :param num_layers: 越大更好地捕捉輸入序列中的抽象特徵",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size, num_layers)"
},
{
"docstring": ":param x: (batch_size, seq_len) :param encoder_hidden:",
"nam... | 2 | stack_v2_sparse_classes_30k_train_006207 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, num_layers): :param input_size: vob_size :param hidden_size: 越大可以夠更好地記憶長序列中的信息 :param num_layers: 越大更好地捕捉輸入序列中的抽象特徵
- def forward(self, ... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, num_layers): :param input_size: vob_size :param hidden_size: 越大可以夠更好地記憶長序列中的信息 :param num_layers: 越大更好地捕捉輸入序列中的抽象特徵
- def forward(self, ... | c360e81624296c9243fd662dea618042164e0aa7 | <|skeleton|>
class Encoder:
def __init__(self, input_size, hidden_size, num_layers):
""":param input_size: vob_size :param hidden_size: 越大可以夠更好地記憶長序列中的信息 :param num_layers: 越大更好地捕捉輸入序列中的抽象特徵"""
<|body_0|>
def forward(self, x, encoder_hidden):
""":param x: (batch_size, seq_len) :param e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, input_size, hidden_size, num_layers):
""":param input_size: vob_size :param hidden_size: 越大可以夠更好地記憶長序列中的信息 :param num_layers: 越大更好地捕捉輸入序列中的抽象特徵"""
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size... | the_stack_v2_python_sparse | torch-qa/test-lstm2.py | flashlin/Samples | train | 3 | |
1ec298c2d7a17d99819f79975aa1d550328f4b91 | [
"my_player_id = current_user['player_id']\npg = get_playergroup(group_name, player_id)\nif player_id != my_player_id:\n secret_ok = pg['secret'] == args.get('secret')\n is_service = 'service' in current_user['roles']\n if not secret_ok and (not is_service):\n message = \"'player_id' does not match c... | <|body_start_0|>
my_player_id = current_user['player_id']
pg = get_playergroup(group_name, player_id)
if player_id != my_player_id:
secret_ok = pg['secret'] == args.get('secret')
is_service = 'service' in current_user['roles']
if not secret_ok and (not is_serv... | Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session). | PlayerGroupsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, args, player_id, group_name):
"""Get group f... | stack_v2_sparse_classes_36k_train_034257 | 5,033 | permissive | [
{
"docstring": "Get group for player Returns user identities group 'group_name' associated with 'player_id'.",
"name": "get",
"signature": "def get(self, args, player_id, group_name)"
},
{
"docstring": "Create a player group Creates a new player group for the player. Can only be called by the pl... | 2 | stack_v2_sparse_classes_30k_train_016374 | Implement the Python class `PlayerGroupsAPI` described below.
Class description:
Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session).
Method signatures and docstrings:
... | Implement the Python class `PlayerGroupsAPI` described below.
Class description:
Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session).
Method signatures and docstrings:
... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, args, player_id, group_name):
"""Get group f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, args, player_id, group_name):
"""Get group for player Ret... | the_stack_v2_python_sparse | driftbase/api/players/playergroups.py | dgnorth/drift-base | train | 1 |
1f880c1e77ea9ab73e7f73b24f1171cdde73f14b | [
"for i in range(fmin, int(n ** 0.5) + 1):\n if n % i == 0:\n self.ans.append(prefix + [i, n // i])\n self.recusive(prefix + [i], i, n // i)",
"self.ans = []\nself.recusive([], 2, n)\nreturn self.ans"
] | <|body_start_0|>
for i in range(fmin, int(n ** 0.5) + 1):
if n % i == 0:
self.ans.append(prefix + [i, n // i])
self.recusive(prefix + [i], i, n // i)
<|end_body_0|>
<|body_start_1|>
self.ans = []
self.recusive([], 2, n)
return self.ans
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recusive(self, prefix, fmin, n):
"""Args: fmin: min factor, in recursive, control the fmin to eliminate repeatition."""
<|body_0|>
def getFactors(self, n: int) -> List[List[int]]:
"""Q0039 backtrack."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_034258 | 737 | no_license | [
{
"docstring": "Args: fmin: min factor, in recursive, control the fmin to eliminate repeatition.",
"name": "recusive",
"signature": "def recusive(self, prefix, fmin, n)"
},
{
"docstring": "Q0039 backtrack.",
"name": "getFactors",
"signature": "def getFactors(self, n: int) -> List[List[in... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recusive(self, prefix, fmin, n): Args: fmin: min factor, in recursive, control the fmin to eliminate repeatition.
- def getFactors(self, n: int) -> List[List[int]]: Q0039 bac... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recusive(self, prefix, fmin, n): Args: fmin: min factor, in recursive, control the fmin to eliminate repeatition.
- def getFactors(self, n: int) -> List[List[int]]: Q0039 bac... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Solution:
def recusive(self, prefix, fmin, n):
"""Args: fmin: min factor, in recursive, control the fmin to eliminate repeatition."""
<|body_0|>
def getFactors(self, n: int) -> List[List[int]]:
"""Q0039 backtrack."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recusive(self, prefix, fmin, n):
"""Args: fmin: min factor, in recursive, control the fmin to eliminate repeatition."""
for i in range(fmin, int(n ** 0.5) + 1):
if n % i == 0:
self.ans.append(prefix + [i, n // i])
self.recusive(prefix +... | the_stack_v2_python_sparse | src/0200-0299/0254.factor.combination.py | gyang274/leetcode | train | 1 | |
fd82353ae6bf963e0fb25bd10dd152f4792466c3 | [
"self._destVortexName = destVortexName\nself._filt = dict(name=tupleActionProcessorName, key='tupleActionProcessorName')\nif additionalFilt:\n self._filt.update(additionalFilt)",
"filt = copy(self._filt)\nif additionalFilt:\n filt.update(additionalFilt)\nd = Payload(filt=filt, tuples=[tupleAction]).makePayl... | <|body_start_0|>
self._destVortexName = destVortexName
self._filt = dict(name=tupleActionProcessorName, key='tupleActionProcessorName')
if additionalFilt:
self._filt.update(additionalFilt)
<|end_body_0|>
<|body_start_1|>
filt = copy(self._filt)
if additionalFilt:
... | TupleDataActionClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TupleDataActionClient:
def __init__(self, destVortexName: str, tupleActionProcessorName: str, additionalFilt: dict=None) -> None:
"""Constructor :param destVortexName: The name of the destination vortex to send to. :param tupleActionProcessorName: The name of this observable :param addit... | stack_v2_sparse_classes_36k_train_034259 | 2,112 | permissive | [
{
"docstring": "Constructor :param destVortexName: The name of the destination vortex to send to. :param tupleActionProcessorName: The name of this observable :param additionalFilt: Any additional filter keys that are required",
"name": "__init__",
"signature": "def __init__(self, destVortexName: str, t... | 2 | null | Implement the Python class `TupleDataActionClient` described below.
Class description:
Implement the TupleDataActionClient class.
Method signatures and docstrings:
- def __init__(self, destVortexName: str, tupleActionProcessorName: str, additionalFilt: dict=None) -> None: Constructor :param destVortexName: The name o... | Implement the Python class `TupleDataActionClient` described below.
Class description:
Implement the TupleDataActionClient class.
Method signatures and docstrings:
- def __init__(self, destVortexName: str, tupleActionProcessorName: str, additionalFilt: dict=None) -> None: Constructor :param destVortexName: The name o... | 2c4867aea6799c9ec2c93a16c37a6395281e1412 | <|skeleton|>
class TupleDataActionClient:
def __init__(self, destVortexName: str, tupleActionProcessorName: str, additionalFilt: dict=None) -> None:
"""Constructor :param destVortexName: The name of the destination vortex to send to. :param tupleActionProcessorName: The name of this observable :param addit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TupleDataActionClient:
def __init__(self, destVortexName: str, tupleActionProcessorName: str, additionalFilt: dict=None) -> None:
"""Constructor :param destVortexName: The name of the destination vortex to send to. :param tupleActionProcessorName: The name of this observable :param additionalFilt: Any... | the_stack_v2_python_sparse | vortex/handler/TupleDataActionClient.py | Synerty/vortexpy | train | 1 | |
1555ed6279191954a0addf95277b7fc3d0e8cc6a | [
"name_prefix = self._set_name_or_get_name_prefix(name, name_prefix=name_prefix)\nsuper(PlaceholderInputNode, self).__init__(builder, state_sizes, is_sequence=is_sequence, name_prefix=name_prefix, **dirs)\nself.free_oslots = list(range(self.num_expected_outputs))",
"this_node_dirs = {'dtype': 'float64'}\nthis_node... | <|body_start_0|>
name_prefix = self._set_name_or_get_name_prefix(name, name_prefix=name_prefix)
super(PlaceholderInputNode, self).__init__(builder, state_sizes, is_sequence=is_sequence, name_prefix=name_prefix, **dirs)
self.free_oslots = list(range(self.num_expected_outputs))
<|end_body_0|>
<|b... | An InputNode to represent data to be fed to the Model Graph (MG). Data fed to the MG, for instance for training or sampling purposes is represented by a PlaceholdeInputNode. On build, a tensorflow placeholder is created and added to the MG. PlaceholderInputNodes have a single output slot that maps to a tensorflow Place... | PlaceholderInputNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaceholderInputNode:
"""An InputNode to represent data to be fed to the Model Graph (MG). Data fed to the MG, for instance for training or sampling purposes is represented by a PlaceholdeInputNode. On build, a tensorflow placeholder is created and added to the MG. PlaceholderInputNodes have a si... | stack_v2_sparse_classes_36k_train_034260 | 14,547 | no_license | [
{
"docstring": "Initialize the PlaceholderInputNode Args: builder (Builder): An instance of Builder necessary to declare the secondary output nodes. state_sizes (int or list of ints): The shape of the main output code. This excludes the 0th dimension - batch size - and the 1st dimension when the data is a seque... | 5 | stack_v2_sparse_classes_30k_train_002036 | Implement the Python class `PlaceholderInputNode` described below.
Class description:
An InputNode to represent data to be fed to the Model Graph (MG). Data fed to the MG, for instance for training or sampling purposes is represented by a PlaceholdeInputNode. On build, a tensorflow placeholder is created and added to ... | Implement the Python class `PlaceholderInputNode` described below.
Class description:
An InputNode to represent data to be fed to the Model Graph (MG). Data fed to the MG, for instance for training or sampling purposes is represented by a PlaceholdeInputNode. On build, a tensorflow placeholder is created and added to ... | 12ee60e78f384a9fa9b780a614fae7b72d9b5b19 | <|skeleton|>
class PlaceholderInputNode:
"""An InputNode to represent data to be fed to the Model Graph (MG). Data fed to the MG, for instance for training or sampling purposes is represented by a PlaceholdeInputNode. On build, a tensorflow placeholder is created and added to the MG. PlaceholderInputNodes have a si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaceholderInputNode:
"""An InputNode to represent data to be fed to the Model Graph (MG). Data fed to the MG, for instance for training or sampling purposes is represented by a PlaceholdeInputNode. On build, a tensorflow placeholder is created and added to the MG. PlaceholderInputNodes have a single output s... | the_stack_v2_python_sparse | neurolib/encoder/input.py | gumpfly/neurolib | train | 0 |
91201728441ca58c4e83f156ddb088b37387d498 | [
"self.SetStartDate(2013, 10, 7)\nself.SetEndDate(2013, 10, 11)\nself.SetCash(100000)\nself.symbols = [['SPY', SecurityType.Equity], ['EURUSD', SecurityType.Forex]]\nself.targets = []\nfor item in self.symbols:\n symbol = self.AddSecurity(item[1], item[0]).Symbol\n self.targets.append(PortfolioTarget(symbol, 0... | <|body_start_0|>
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 11)
self.SetCash(100000)
self.symbols = [['SPY', SecurityType.Equity], ['EURUSD', SecurityType.Forex]]
self.targets = []
for item in self.symbols:
symbol = self.AddSecurity(item[1], item... | Collective2SignalExportDemonstrationAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collective2SignalExportDemonstrationAlgorithm:
def Initialize(self):
"""Initialize the date and add all equity symbols present in list _symbols"""
<|body_0|>
def OnData(self, data):
"""Reduce the quantity of holdings for one security and increase the holdings to the ... | stack_v2_sparse_classes_36k_train_034261 | 4,637 | permissive | [
{
"docstring": "Initialize the date and add all equity symbols present in list _symbols",
"name": "Initialize",
"signature": "def Initialize(self)"
},
{
"docstring": "Reduce the quantity of holdings for one security and increase the holdings to the another one when the EMA's indicators crosses b... | 2 | stack_v2_sparse_classes_30k_train_011394 | Implement the Python class `Collective2SignalExportDemonstrationAlgorithm` described below.
Class description:
Implement the Collective2SignalExportDemonstrationAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialize the date and add all equity symbols present in list _symbols
- def OnDa... | Implement the Python class `Collective2SignalExportDemonstrationAlgorithm` described below.
Class description:
Implement the Collective2SignalExportDemonstrationAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialize the date and add all equity symbols present in list _symbols
- def OnDa... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class Collective2SignalExportDemonstrationAlgorithm:
def Initialize(self):
"""Initialize the date and add all equity symbols present in list _symbols"""
<|body_0|>
def OnData(self, data):
"""Reduce the quantity of holdings for one security and increase the holdings to the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Collective2SignalExportDemonstrationAlgorithm:
def Initialize(self):
"""Initialize the date and add all equity symbols present in list _symbols"""
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 11)
self.SetCash(100000)
self.symbols = [['SPY', SecurityType.Equi... | the_stack_v2_python_sparse | Algorithm.Python/Collective2SignalExportDemonstrationAlgorithm.py | Capnode/Algoloop | train | 87 | |
6e57c2fcd6212da0ad38e9cd29c7f4d32e859712 | [
"super().__init__(*args, **kwargs)\ninput_size = sum((x.output_size for x in self._input_layers))\noutput_size = self.output_size\nif input_size != output_size:\n raise ValueError('Highway network layer cannot change the number of connections.')\nself._init_weight('input/W', (input_size, output_size), scale=0.01... | <|body_start_0|>
super().__init__(*args, **kwargs)
input_size = sum((x.output_size for x in self._input_layers))
output_size = self.output_size
if input_size != output_size:
raise ValueError('Highway network layer cannot change the number of connections.')
self._init_... | Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop | HighwayLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighwayLayer:
"""Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop"""
def __init__(self, *args, **kwargs):
"""Initializes the parameters for this layer."""
<|body_0|>
def create_structure(se... | stack_v2_sparse_classes_36k_train_034262 | 2,081 | permissive | [
{
"docstring": "Initializes the parameters for this layer.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Creates the symbolic graph of this layer. Sets self.output to a symbolic matrix that describes the output of this layer.",
"name": "create_st... | 2 | stack_v2_sparse_classes_30k_train_017050 | Implement the Python class `HighwayLayer` described below.
Class description:
Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the parameters for this ... | Implement the Python class `HighwayLayer` described below.
Class description:
Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the parameters for this ... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class HighwayLayer:
"""Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop"""
def __init__(self, *args, **kwargs):
"""Initializes the parameters for this layer."""
<|body_0|>
def create_structure(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HighwayLayer:
"""Highway Network Layer with Hyperbolic Tangent Activation R. K. Srivastava (2015) Highway Networks ICML 2015 Deep Learning Workshop"""
def __init__(self, *args, **kwargs):
"""Initializes the parameters for this layer."""
super().__init__(*args, **kwargs)
input_size... | the_stack_v2_python_sparse | theanolm/network/highwaylayer.py | senarvi/theanolm | train | 95 |
f5c5a18915ab0e0258610c43e7a7109d16e7bf9a | [
"Parametre.__init__(self, 'boire', 'drink')\nself.tronquer = True\nself.schema = '<nom_familier>'\nself.aide_courte = 'demande à un familier de boire'\nself.aide_longue = \"Cette commande demande au familier dont le nom est précisé en paramètre de boire dans la salle où vous vous trouvez. Les familiers peuvent boir... | <|body_start_0|>
Parametre.__init__(self, 'boire', 'drink')
self.tronquer = True
self.schema = '<nom_familier>'
self.aide_courte = 'demande à un familier de boire'
self.aide_longue = "Cette commande demande au familier dont le nom est précisé en paramètre de boire dans la salle o... | Commande 'familier boire'. | PrmBoire | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmBoire:
"""Commande 'familier boire'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__... | stack_v2_sparse_classes_36k_train_034263 | 3,357 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019584 | Implement the Python class `PrmBoire` described below.
Class description:
Commande 'familier boire'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmBoire` described below.
Class description:
Commande 'familier boire'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmBoire:
"""Commande 'familier b... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmBoire:
"""Commande 'familier boire'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmBoire:
"""Commande 'familier boire'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'boire', 'drink')
self.tronquer = True
self.schema = '<nom_familier>'
self.aide_courte = 'demande à un familier de boire'
self.aide_longu... | the_stack_v2_python_sparse | src/secondaires/familier/commandes/familier/boire.py | vincent-lg/tsunami | train | 5 |
3aadf998d7cacef58865c4df5ef84f534c284662 | [
"captcha = field.data\nemail = self.email.data\ncaptcha_cache = zlcache.get(email)\nif not captcha_cache or captcha.lower() != captcha_cache.lower():\n raise ValidationError('邮箱验证码错误!')",
"email = filed.data\nuser = g.cms_user\nif user.email == email:\n raise ValidationError('不能修改为相同的邮箱!')"
] | <|body_start_0|>
captcha = field.data
email = self.email.data
captcha_cache = zlcache.get(email)
if not captcha_cache or captcha.lower() != captcha_cache.lower():
raise ValidationError('邮箱验证码错误!')
<|end_body_0|>
<|body_start_1|>
email = filed.data
user = g.cm... | ResetEmailForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetEmailForm:
def validate_captcha(self, field):
"""验证输入的验证码和memcahced的验证码是否保持一致"""
<|body_0|>
def validate_email(self, filed):
"""验证是否为相同的邮箱"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
captcha = field.data
email = self.email.data
... | stack_v2_sparse_classes_36k_train_034264 | 3,297 | no_license | [
{
"docstring": "验证输入的验证码和memcahced的验证码是否保持一致",
"name": "validate_captcha",
"signature": "def validate_captcha(self, field)"
},
{
"docstring": "验证是否为相同的邮箱",
"name": "validate_email",
"signature": "def validate_email(self, filed)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003208 | Implement the Python class `ResetEmailForm` described below.
Class description:
Implement the ResetEmailForm class.
Method signatures and docstrings:
- def validate_captcha(self, field): 验证输入的验证码和memcahced的验证码是否保持一致
- def validate_email(self, filed): 验证是否为相同的邮箱 | Implement the Python class `ResetEmailForm` described below.
Class description:
Implement the ResetEmailForm class.
Method signatures and docstrings:
- def validate_captcha(self, field): 验证输入的验证码和memcahced的验证码是否保持一致
- def validate_email(self, filed): 验证是否为相同的邮箱
<|skeleton|>
class ResetEmailForm:
def validate_ca... | 8818390a4f131491c409c9daffc6a3e8abfdd36c | <|skeleton|>
class ResetEmailForm:
def validate_captcha(self, field):
"""验证输入的验证码和memcahced的验证码是否保持一致"""
<|body_0|>
def validate_email(self, filed):
"""验证是否为相同的邮箱"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResetEmailForm:
def validate_captcha(self, field):
"""验证输入的验证码和memcahced的验证码是否保持一致"""
captcha = field.data
email = self.email.data
captcha_cache = zlcache.get(email)
if not captcha_cache or captcha.lower() != captcha_cache.lower():
raise ValidationError('邮箱验... | the_stack_v2_python_sparse | apps/cms/forms.py | xiao2912008572/plateform | train | 0 | |
467168a994e6c6d2095af81b687b53666759c490 | [
"if other is None:\n raise PycroftModelException('You cannot use `.contains()` with `null` (`None`)!')\nop = self.op('@>', is_comparison=True)\nif isinstance(other, datetime):\n if not other.tzinfo:\n raise PycroftModelException(f'You cannot use `.contains()` with a non-timezone-aware datetime ({other}... | <|body_start_0|>
if other is None:
raise PycroftModelException('You cannot use `.contains()` with `null` (`None`)!')
op = self.op('@>', is_comparison=True)
if isinstance(other, datetime):
if not other.tzinfo:
raise PycroftModelException(f'You cannot use `.... | comparator_factory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class comparator_factory:
def contains(self, other: Any, **kwargs) -> None:
"""Provide the functionality of the `@>` operator for Intervals. :param other: can be an interval, a tz-aware datetime, or column-like sql expressions with these types. If any `.contains()` call does not work, you can ... | stack_v2_sparse_classes_36k_train_034265 | 6,850 | permissive | [
{
"docstring": "Provide the functionality of the `@>` operator for Intervals. :param other: can be an interval, a tz-aware datetime, or column-like sql expressions with these types. If any `.contains()` call does not work, you can add support here.",
"name": "contains",
"signature": "def contains(self, ... | 2 | null | Implement the Python class `comparator_factory` described below.
Class description:
Implement the comparator_factory class.
Method signatures and docstrings:
- def contains(self, other: Any, **kwargs) -> None: Provide the functionality of the `@>` operator for Intervals. :param other: can be an interval, a tz-aware d... | Implement the Python class `comparator_factory` described below.
Class description:
Implement the comparator_factory class.
Method signatures and docstrings:
- def contains(self, other: Any, **kwargs) -> None: Provide the functionality of the `@>` operator for Intervals. :param other: can be an interval, a tz-aware d... | 9f3abb5dc1a7dd54c577af37d5004dd2204739cd | <|skeleton|>
class comparator_factory:
def contains(self, other: Any, **kwargs) -> None:
"""Provide the functionality of the `@>` operator for Intervals. :param other: can be an interval, a tz-aware datetime, or column-like sql expressions with these types. If any `.contains()` call does not work, you can ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class comparator_factory:
def contains(self, other: Any, **kwargs) -> None:
"""Provide the functionality of the `@>` operator for Intervals. :param other: can be an interval, a tz-aware datetime, or column-like sql expressions with these types. If any `.contains()` call does not work, you can add support he... | the_stack_v2_python_sparse | pycroft/model/types.py | agdsn/pycroft | train | 21 | |
f4f7f68c824073bbddf20a8e737cc0f0f5c15e8b | [
"self.min_heap, self.max_heap, self.count = ([], [], 0)\nheapq.heapify(self.min_heap)\nheapq.heapify(self.max_heap)",
"if self.count == 0 or num > self.min_heap[0]:\n heapq.heappush(self.min_heap, num)\nelse:\n heapq.heappush(self.max_heap, -num)\nself.count += 1\nleft_count = self.count // 2\nif len(self.m... | <|body_start_0|>
self.min_heap, self.max_heap, self.count = ([], [], 0)
heapq.heapify(self.min_heap)
heapq.heapify(self.max_heap)
<|end_body_0|>
<|body_start_1|>
if self.count == 0 or num > self.min_heap[0]:
heapq.heappush(self.min_heap, num)
else:
heapq.... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k_train_034266 | 1,678 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | 3873502679a5def6af4be03028542f07d059d1a9 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.min_heap, self.max_heap, self.count = ([], [], 0)
heapq.heapify(self.min_heap)
heapq.heapify(self.max_heap)
def addNum(self, num):
"""Adds a num into the data structure. :type num: in... | the_stack_v2_python_sparse | Python-Algorithms-DataStructure/src/leet/295_FindMedianfromDataStream.py | coremedy/Python-Algorithms-DataStructure | train | 0 | |
cf84c3d572c10e281bac5f75e61ed3f432e71777 | [
"super().__init__()\nkwargs = {'growth': growth, 'interval_width': threshold, 'holidays': holidays, 'holidays_prior_scale': holidays_prior_scale, 'changepoint_prior_scale': changepoint_prior_scale, 'changepoint_range': changepoint_range, 'seasonality_mode': seasonality_mode, 'daily_seasonality': daily_seasonality, ... | <|body_start_0|>
super().__init__()
kwargs = {'growth': growth, 'interval_width': threshold, 'holidays': holidays, 'holidays_prior_scale': holidays_prior_scale, 'changepoint_prior_scale': changepoint_prior_scale, 'changepoint_range': changepoint_range, 'seasonality_mode': seasonality_mode, 'daily_season... | OutlierProphet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_se... | stack_v2_sparse_classes_36k_train_034267 | 8,498 | permissive | [
{
"docstring": "Outlier detector for time series data using fbprophet. See https://facebook.github.io/prophet/ for more details. Parameters ---------- threshold Width of the uncertainty intervals of the forecast, used as outlier threshold. Equivalent to `interval_width`. If the instance lies outside of the unce... | 4 | stack_v2_sparse_classes_30k_test_000419 | Implement the Python class `OutlierProphet` described below.
Class description:
Implement the OutlierProphet class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=N... | Implement the Python class `OutlierProphet` described below.
Class description:
Implement the OutlierProphet class.
Method signatures and docstrings:
- def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=N... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutlierProphet:
def __init__(self, threshold: float=0.8, growth: str='linear', cap: float=None, holidays: pd.DataFrame=None, holidays_prior_scale: float=10.0, country_holidays: str=None, changepoint_prior_scale: float=0.05, changepoint_range: float=0.8, seasonality_mode: str='additive', daily_seasonality: Uni... | the_stack_v2_python_sparse | alibi_detect/od/prophet.py | SeldonIO/alibi-detect | train | 1,922 | |
aecd9ab2c2fdb5339a51cdda2264c774395821ff | [
"recentHistory = ticker.getHistoryWindow(20)\nif recentHistory != None:\n if self.isUpwardTrend(recentHistory):\n amount = self.portfolio.calculateStockAmountFromBalancePercentage(tick['close'], 10)\n initialValue = amount * tick['close']\n self.portfolio.buyLong(ticker.getSymbol(), amount, ... | <|body_start_0|>
recentHistory = ticker.getHistoryWindow(20)
if recentHistory != None:
if self.isUpwardTrend(recentHistory):
amount = self.portfolio.calculateStockAmountFromBalancePercentage(tick['close'], 10)
initialValue = amount * tick['close']
... | This class represents an investment strategy based on simple trend analysis. | SimpleTrendStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTrendStrategy:
"""This class represents an investment strategy based on simple trend analysis."""
def handleTick(self, ticker: StockTicker, tick: dict):
"""Handle a new stock market tick."""
<|body_0|>
def isUpwardTrend(self, history: StockTicker):
"""Retur... | stack_v2_sparse_classes_36k_train_034268 | 1,296 | no_license | [
{
"docstring": "Handle a new stock market tick.",
"name": "handleTick",
"signature": "def handleTick(self, ticker: StockTicker, tick: dict)"
},
{
"docstring": "Return whether the given history shows an upward trend.",
"name": "isUpwardTrend",
"signature": "def isUpwardTrend(self, history... | 2 | stack_v2_sparse_classes_30k_train_016267 | Implement the Python class `SimpleTrendStrategy` described below.
Class description:
This class represents an investment strategy based on simple trend analysis.
Method signatures and docstrings:
- def handleTick(self, ticker: StockTicker, tick: dict): Handle a new stock market tick.
- def isUpwardTrend(self, history... | Implement the Python class `SimpleTrendStrategy` described below.
Class description:
This class represents an investment strategy based on simple trend analysis.
Method signatures and docstrings:
- def handleTick(self, ticker: StockTicker, tick: dict): Handle a new stock market tick.
- def isUpwardTrend(self, history... | 0b0908fdffaba0a58eb568081fa23d1071b1193e | <|skeleton|>
class SimpleTrendStrategy:
"""This class represents an investment strategy based on simple trend analysis."""
def handleTick(self, ticker: StockTicker, tick: dict):
"""Handle a new stock market tick."""
<|body_0|>
def isUpwardTrend(self, history: StockTicker):
"""Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleTrendStrategy:
"""This class represents an investment strategy based on simple trend analysis."""
def handleTick(self, ticker: StockTicker, tick: dict):
"""Handle a new stock market tick."""
recentHistory = ticker.getHistoryWindow(20)
if recentHistory != None:
if... | the_stack_v2_python_sparse | modules/strategies/trends.py | HansSchouten/Stock-Farm | train | 2 |
f6d1f647314402614269a9164695b39490de2cfd | [
"self.weights = weights if weights is not None else np.random.randn(n_input, n_neurons)\nself.activation = activation\nself.bias = bias if bias is not None else np.random.randn(n_neurons)\nself.last_activation = None\nself.error = None\nself.delta = None",
"r = np.dot(x, self.weights) + self.bias\nself.last_activ... | <|body_start_0|>
self.weights = weights if weights is not None else np.random.randn(n_input, n_neurons)
self.activation = activation
self.bias = bias if bias is not None else np.random.randn(n_neurons)
self.last_activation = None
self.error = None
self.delta = None
<|end_... | Represents a layer (hidden or output) in our neural network. | Layer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Layer:
"""Represents a layer (hidden or output) in our neural network."""
def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None):
"""Initial parameters for the Layer class. Bias is not used."""
<|body_0|>
def activate(self, x):
"""Calcul... | stack_v2_sparse_classes_36k_train_034269 | 5,072 | no_license | [
{
"docstring": "Initial parameters for the Layer class. Bias is not used.",
"name": "__init__",
"signature": "def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None)"
},
{
"docstring": "Calculates the dot product of this layer.",
"name": "activate",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_005977 | Implement the Python class `Layer` described below.
Class description:
Represents a layer (hidden or output) in our neural network.
Method signatures and docstrings:
- def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None): Initial parameters for the Layer class. Bias is not used.
- def acti... | Implement the Python class `Layer` described below.
Class description:
Represents a layer (hidden or output) in our neural network.
Method signatures and docstrings:
- def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None): Initial parameters for the Layer class. Bias is not used.
- def acti... | 8e528fc0804b837450b2e4cd5a4b4d4195249629 | <|skeleton|>
class Layer:
"""Represents a layer (hidden or output) in our neural network."""
def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None):
"""Initial parameters for the Layer class. Bias is not used."""
<|body_0|>
def activate(self, x):
"""Calcul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Layer:
"""Represents a layer (hidden or output) in our neural network."""
def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None):
"""Initial parameters for the Layer class. Bias is not used."""
self.weights = weights if weights is not None else np.random.randn(n_... | the_stack_v2_python_sparse | en605.649/pa5/nn.py | jakesciotto/jhu | train | 0 |
87c5dd54ebe8d2f19b1f2a6e92fceb38cb1234fa | [
"url = utils.urljoin(self.base_path, self.id, 'root')\nresp = session.post(url)\nreturn resp.json()['user']",
"url = utils.urljoin(self.base_path, self.id, 'root')\nresp = session.get(url)\nreturn resp.json()['rootEnabled']",
"body = {'restart': {}}\nurl = utils.urljoin(self.base_path, self.id, 'action')\nsessi... | <|body_start_0|>
url = utils.urljoin(self.base_path, self.id, 'root')
resp = session.post(url)
return resp.json()['user']
<|end_body_0|>
<|body_start_1|>
url = utils.urljoin(self.base_path, self.id, 'root')
resp = session.get(url)
return resp.json()['rootEnabled']
<|end_... | Instance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Instance:
def enable_root_user(self, session):
"""Enable login for the root user. This operation enables login from any host for the root user and provides the user with a generated root password. :param session: The session to use for making this request. :type session: :class:`~keyston... | stack_v2_sparse_classes_36k_train_034270 | 3,825 | permissive | [
{
"docstring": "Enable login for the root user. This operation enables login from any host for the root user and provides the user with a generated root password. :param session: The session to use for making this request. :type session: :class:`~keystoneauth1.adapter.Adapter` :returns: A dictionary with keys `... | 5 | stack_v2_sparse_classes_30k_train_009720 | Implement the Python class `Instance` described below.
Class description:
Implement the Instance class.
Method signatures and docstrings:
- def enable_root_user(self, session): Enable login for the root user. This operation enables login from any host for the root user and provides the user with a generated root pass... | Implement the Python class `Instance` described below.
Class description:
Implement the Instance class.
Method signatures and docstrings:
- def enable_root_user(self, session): Enable login for the root user. This operation enables login from any host for the root user and provides the user with a generated root pass... | d474eb84c605c429bb9cccb166cabbdd1654d73c | <|skeleton|>
class Instance:
def enable_root_user(self, session):
"""Enable login for the root user. This operation enables login from any host for the root user and provides the user with a generated root password. :param session: The session to use for making this request. :type session: :class:`~keyston... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Instance:
def enable_root_user(self, session):
"""Enable login for the root user. This operation enables login from any host for the root user and provides the user with a generated root password. :param session: The session to use for making this request. :type session: :class:`~keystoneauth1.adapter... | the_stack_v2_python_sparse | openstack/database/v1/instance.py | openstack/openstacksdk | train | 124 | |
25ffbaeb0c583799a0f7dd43eb4b845a30dab815 | [
"expired_date = generate_expired_date()\nfor medialive_channel in list_medialive_channels():\n if medialive_channel.get('Tags', {}).get('environment') != settings.AWS_BASE_NAME:\n continue\n if medialive_channel.get('State') != 'IDLE':\n continue\n _environment, live_pk, _stamp = medialive_ch... | <|body_start_0|>
expired_date = generate_expired_date()
for medialive_channel in list_medialive_channels():
if medialive_channel.get('Tags', {}).get('environment') != settings.AWS_BASE_NAME:
continue
if medialive_channel.get('State') != 'IDLE':
con... | Once a live started, all AWS elemental stack are created. Once stopped, the instructor must do an action. Restart it and/or convert it in VOD. If nothing is done, the AWS element resources are leaved unused and use the quota we have on our AWS account. These unused resources must be removed after several days of inacti... | Command | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Once a live started, all AWS elemental stack are created. Once stopped, the instructor must do an action. Restart it and/or convert it in VOD. If nothing is done, the AWS element resources are leaved unused and use the quota we have on our AWS account. These unused resources must be r... | stack_v2_sparse_classes_36k_train_034271 | 4,123 | permissive | [
{
"docstring": "Execute management command.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Set the live_state to ENDED, the upload_state to DELETED and delete all AWS resources",
"name": "_delete_live",
"signature": "def _delete_live(self, live, ... | 2 | stack_v2_sparse_classes_30k_train_021482 | Implement the Python class `Command` described below.
Class description:
Once a live started, all AWS elemental stack are created. Once stopped, the instructor must do an action. Restart it and/or convert it in VOD. If nothing is done, the AWS element resources are leaved unused and use the quota we have on our AWS ac... | Implement the Python class `Command` described below.
Class description:
Once a live started, all AWS elemental stack are created. Once stopped, the instructor must do an action. Restart it and/or convert it in VOD. If nothing is done, the AWS element resources are leaved unused and use the quota we have on our AWS ac... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class Command:
"""Once a live started, all AWS elemental stack are created. Once stopped, the instructor must do an action. Restart it and/or convert it in VOD. If nothing is done, the AWS element resources are leaved unused and use the quota we have on our AWS account. These unused resources must be r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Once a live started, all AWS elemental stack are created. Once stopped, the instructor must do an action. Restart it and/or convert it in VOD. If nothing is done, the AWS element resources are leaved unused and use the quota we have on our AWS account. These unused resources must be removed after ... | the_stack_v2_python_sparse | src/backend/marsha/core/management/commands/clean_aws_elemental_stack.py | openfun/marsha | train | 92 |
cbe4cbc3fee31d55bdd7cff6c9c2cc97f258ea14 | [
"logging.debug('%sTest: Accessibility of the WebInterface: Wizard-Page', LoggerSetup.get_log_deep(1))\nassert self.remote_system.mode == Mode.configuration\nlogging.debug('%s[' + u'✔' + '] Correct Mode', LoggerSetup.get_log_deep(2))\npre_command = ['ip', 'netns', 'exec', self.remote_system.namespace_name]\nbrowser ... | <|body_start_0|>
logging.debug('%sTest: Accessibility of the WebInterface: Wizard-Page', LoggerSetup.get_log_deep(1))
assert self.remote_system.mode == Mode.configuration
logging.debug('%s[' + u'✔' + '] Correct Mode', LoggerSetup.get_log_deep(2))
pre_command = ['ip', 'netns', 'exec', sel... | Tests if WebInterface (wizard and expert) of the Router is accessible. The Router has to be in configuration-mode therefore | TestAccessibilityWebConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAccessibilityWebConfig:
"""Tests if WebInterface (wizard and expert) of the Router is accessible. The Router has to be in configuration-mode therefore"""
def test_accessibility_of_wizard(self):
"""Test: 1. Router is in configuration-mode 2. The page-source of the wizard-page does... | stack_v2_sparse_classes_36k_train_034272 | 2,358 | no_license | [
{
"docstring": "Test: 1. Router is in configuration-mode 2. The page-source of the wizard-page doesn't contain \"Not Found\" => wizard-page exist",
"name": "test_accessibility_of_wizard",
"signature": "def test_accessibility_of_wizard(self)"
},
{
"docstring": "Test: 1. Router is in configuration... | 2 | null | Implement the Python class `TestAccessibilityWebConfig` described below.
Class description:
Tests if WebInterface (wizard and expert) of the Router is accessible. The Router has to be in configuration-mode therefore
Method signatures and docstrings:
- def test_accessibility_of_wizard(self): Test: 1. Router is in conf... | Implement the Python class `TestAccessibilityWebConfig` described below.
Class description:
Tests if WebInterface (wizard and expert) of the Router is accessible. The Router has to be in configuration-mode therefore
Method signatures and docstrings:
- def test_accessibility_of_wizard(self): Test: 1. Router is in conf... | 551fb53a6d4f865f076d9485e7290699d988731c | <|skeleton|>
class TestAccessibilityWebConfig:
"""Tests if WebInterface (wizard and expert) of the Router is accessible. The Router has to be in configuration-mode therefore"""
def test_accessibility_of_wizard(self):
"""Test: 1. Router is in configuration-mode 2. The page-source of the wizard-page does... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAccessibilityWebConfig:
"""Tests if WebInterface (wizard and expert) of the Router is accessible. The Router has to be in configuration-mode therefore"""
def test_accessibility_of_wizard(self):
"""Test: 1. Router is in configuration-mode 2. The page-source of the wizard-page doesn't contain "... | the_stack_v2_python_sparse | firmware_tests/test_C_accessibility_web_config.py | PumucklOnTheAir/TestFramework | train | 9 |
1ae0290dcd59bc3adf4b4d2c1b805ba3d1a27e42 | [
"if nums:\n nums = list(set(nums))\n for j in range(len(nums) - 1, 0, -1):\n for i in range(j):\n if nums[i] > nums[i + 1]:\n nums[i], nums[i + 1] = (nums[i + 1], nums[i])\n cur = 1\n MAX = 1\n for i in range(len(nums)):\n if nums[i - 1] + 1 == nums[i]:\n ... | <|body_start_0|>
if nums:
nums = list(set(nums))
for j in range(len(nums) - 1, 0, -1):
for i in range(j):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = (nums[i + 1], nums[i])
cur = 1
MAX = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive_Hash(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if nums:
nums ... | stack_v2_sparse_classes_36k_train_034273 | 2,241 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive_Hash",
"signature": "def longestConsecutive_Hash(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002643 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive_Hash(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 longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive_Hash(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 3f7b2ea959308eb80f4c65be35aaeed666570f80 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive_Hash(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 longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
if nums:
nums = list(set(nums))
for j in range(len(nums) - 1, 0, -1):
for i in range(j):
if nums[i] > nums[i + 1]:
nums[i], ... | the_stack_v2_python_sparse | 128. 最长连续序列.py | dxc19951001/Everyday_LeetCode | train | 1 | |
5969474fa3c92f5089d35dbfabadb8e6b0364fb8 | [
"kth = None\ncnt = 0\n\ndef find_kth_smallest(node):\n if not node:\n return False\n if find_kth_smallest(node.left):\n return True\n nonlocal cnt, kth\n cnt += 1\n if cnt == k:\n kth = node.val\n return True\n return find_kth_smallest(node.right)\nfind_kth_smallest(roo... | <|body_start_0|>
kth = None
cnt = 0
def find_kth_smallest(node):
if not node:
return False
if find_kth_smallest(node.left):
return True
nonlocal cnt, kth
cnt += 1
if cnt == k:
kth = node.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""08/25/2019 16:16"""
<|body_0|>
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
"""05/01/2022 19:49"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kth = None
... | stack_v2_sparse_classes_36k_train_034274 | 2,893 | no_license | [
{
"docstring": "08/25/2019 16:16",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: TreeNode, k: int) -> int"
},
{
"docstring": "05/01/2022 19:49",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: Optional[TreeNode], k: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_019937 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: 08/25/2019 16:16
- def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 05/01/2022 19:49 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: 08/25/2019 16:16
- def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 05/01/2022 19:49
<|skeleton|>
class Solu... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""08/25/2019 16:16"""
<|body_0|>
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
"""05/01/2022 19:49"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""08/25/2019 16:16"""
kth = None
cnt = 0
def find_kth_smallest(node):
if not node:
return False
if find_kth_smallest(node.left):
return True
non... | the_stack_v2_python_sparse | leetcode/solved/230_Kth_Smallest_Element_in_a_BST/solution.py | sungminoh/algorithms | train | 0 | |
8b2fe18a12eafa35398360f6e569a220e3450582 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ItemActivityStat()",
"from .entity import Entity\nfrom .incomplete_data import IncompleteData\nfrom .item_action_stat import ItemActionStat\nfrom .item_activity import ItemActivity\nfrom .entity import Entity\nfrom .incomplete_data imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ItemActivityStat()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .incomplete_data import IncompleteData
from .item_action_stat import ItemActionStat
fro... | ItemActivityStat | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemActivityStat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat:
"""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_034275 | 4,958 | 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: ItemActivityStat",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_010329 | Implement the Python class `ItemActivityStat` described below.
Class description:
Implement the ItemActivityStat class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ItemActivityStat` described below.
Class description:
Implement the ItemActivityStat class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ItemActivityStat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat:
"""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 ItemActivityStat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemActivityStat:
"""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: ItemAc... | the_stack_v2_python_sparse | msgraph/generated/models/item_activity_stat.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2de5fbc0cc05cd99533f7e28c71a3bf2f9501eec | [
"try:\n if request.user.is_superuser:\n workspace_list = workspace_api.get_all()\n else:\n workspace_list = workspace_api.get_all_by_owner(request.user)\n serializer = WorkspaceSerializer(workspace_list, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Excep... | <|body_start_0|>
try:
if request.user.is_superuser:
workspace_list = workspace_api.get_all()
else:
workspace_list = workspace_api.get_all_by_owner(request.user)
serializer = WorkspaceSerializer(workspace_list, many=True)
return Resp... | List all user Workspace, or create a new one | WorkspaceList | [
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspaceList:
"""List all user Workspace, or create a new one"""
def get(self, request):
"""Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error"""
<|body_0|>
def post(self, reques... | stack_v2_sparse_classes_36k_train_034276 | 23,285 | permissive | [
{
"docstring": "Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a Workspace Parameters: { \"title\": \"document_title\",... | 2 | stack_v2_sparse_classes_30k_train_005925 | Implement the Python class `WorkspaceList` described below.
Class description:
List all user Workspace, or create a new one
Method signatures and docstrings:
- def get(self, request): Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal serv... | Implement the Python class `WorkspaceList` described below.
Class description:
List all user Workspace, or create a new one
Method signatures and docstrings:
- def get(self, request): Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal serv... | f032036d95076f92b164389fdbec7415567e7b0f | <|skeleton|>
class WorkspaceList:
"""List all user Workspace, or create a new one"""
def get(self, request):
"""Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error"""
<|body_0|>
def post(self, reques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkspaceList:
"""List all user Workspace, or create a new one"""
def get(self, request):
"""Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error"""
try:
if request.user.is_superuser:
... | the_stack_v2_python_sparse | core_main_app/rest/workspace/views.py | usnistgov/core_main_app | train | 3 |
224ee86b1b335501d77a4ca4092a1c7b893bc2c5 | [
"TFBaseLayer.__init__(self)\nself.in_hidden = in_hidden\nself.emb_size = self.in_hidden.get_shape()[-1]\nself.max_seq_len = max_seq_len\nself.filter_sizes = filter_sizes\nself.num_filters = num_filters\nself.training = training\nself.scope = scope",
"embedded_words_expanded = tf.expand_dims(self.in_hidden, -1)\np... | <|body_start_0|>
TFBaseLayer.__init__(self)
self.in_hidden = in_hidden
self.emb_size = self.in_hidden.get_shape()[-1]
self.max_seq_len = max_seq_len
self.filter_sizes = filter_sizes
self.num_filters = num_filters
self.training = training
self.scope = scope... | TextCNN Layer 底层embedding layer, 再接多窗口多核卷积,最后最大池化max-pooling | TFTextCNNLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFTextCNNLayer:
"""TextCNN Layer 底层embedding layer, 再接多窗口多核卷积,最后最大池化max-pooling"""
def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'):
"""TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型,所有卷... | stack_v2_sparse_classes_36k_train_034277 | 4,283 | permissive | [
{
"docstring": "TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型,所有卷积核的大小,支持多个窗口同时卷积 num_filters: 卷积核个数",
"name": "__init__",
"signature": "def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn')"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_007858 | Implement the Python class `TFTextCNNLayer` described below.
Class description:
TextCNN Layer 底层embedding layer, 再接多窗口多核卷积,最后最大池化max-pooling
Method signatures and docstrings:
- def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'): TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是... | Implement the Python class `TFTextCNNLayer` described below.
Class description:
TextCNN Layer 底层embedding layer, 再接多窗口多核卷积,最后最大池化max-pooling
Method signatures and docstrings:
- def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'): TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是... | c4423c2625c398f5a93c747f3516f378b31ece46 | <|skeleton|>
class TFTextCNNLayer:
"""TextCNN Layer 底层embedding layer, 再接多窗口多核卷积,最后最大池化max-pooling"""
def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'):
"""TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型,所有卷... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFTextCNNLayer:
"""TextCNN Layer 底层embedding layer, 再接多窗口多核卷积,最后最大池化max-pooling"""
def __init__(self, in_hidden, max_seq_len, filter_sizes, num_filters, training, scope='text_cnn'):
"""TextCNN初始化 Args: in_hidden: 输入层tensor, 通常是一个batch的词向量 max_seq_len: 序列最大长度 filter_sizes: array类型,所有卷积核的大小,支持多个窗口同... | the_stack_v2_python_sparse | layers/tf_textcnn_layer.py | snowhws/deeplearning | train | 10 |
8a299c426800f713d9c009179e5fedad20afa1fc | [
"train_data, eval_data = cifar10.load_data()\ntest_data = eval_data.split(0.5)\ncollaborator_count = kwargs['collaborator_count']\ntrain_data, eval_data, test_data = self.split_data(train_data, eval_data, test_data, int(data_path), collaborator_count)\nprint(f'train_data = {train_data}')\nprint(f'eval_data = {eval_... | <|body_start_0|>
train_data, eval_data = cifar10.load_data()
test_data = eval_data.split(0.5)
collaborator_count = kwargs['collaborator_count']
train_data, eval_data, test_data = self.split_data(train_data, eval_data, test_data, int(data_path), collaborator_count)
print(f'train_d... | TensorFlow Data Loader for MNIST Dataset. | FastEstimatorCifarInMemory | [
"LicenseRef-scancode-protobuf",
"MPL-2.0",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastEstimatorCifarInMemory:
"""TensorFlow Data Loader for MNIST Dataset."""
def __init__(self, data_path, batch_size, **kwargs):
"""Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to su... | stack_v2_sparse_classes_36k_train_034278 | 3,070 | permissive | [
{
"docstring": "Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to super init and load_mnist_shard",
"name": "__init__",
"signature": "def __init__(self, data_path, batch_size, **kwargs)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_017367 | Implement the Python class `FastEstimatorCifarInMemory` described below.
Class description:
TensorFlow Data Loader for MNIST Dataset.
Method signatures and docstrings:
- def __init__(self, data_path, batch_size, **kwargs): Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the... | Implement the Python class `FastEstimatorCifarInMemory` described below.
Class description:
TensorFlow Data Loader for MNIST Dataset.
Method signatures and docstrings:
- def __init__(self, data_path, batch_size, **kwargs): Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the... | bd73b749a9ea1b92dbcdd07e639752101d769fc0 | <|skeleton|>
class FastEstimatorCifarInMemory:
"""TensorFlow Data Loader for MNIST Dataset."""
def __init__(self, data_path, batch_size, **kwargs):
"""Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastEstimatorCifarInMemory:
"""TensorFlow Data Loader for MNIST Dataset."""
def __init__(self, data_path, batch_size, **kwargs):
"""Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to super init and ... | the_stack_v2_python_sparse | openfl-workspace/fe_tf_adversarial_cifar/src/fecifar_inmemory.py | PDuckworth/openfl | train | 0 |
d5b6bb0647d0564a976f302d4a49e021878f14b1 | [
"if not root:\n return '$'\nreturn ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])",
"nodes = data.split(',')\nself.i, self.n = (0, len(nodes))\n\ndef dfs():\n if self.i == self.n or nodes[self.i] == '$':\n self.i += 1\n return None\n node = TreeNode(int(nod... | <|body_start_0|>
if not root:
return '$'
return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
<|end_body_0|>
<|body_start_1|>
nodes = data.split(',')
self.i, self.n = (0, len(nodes))
def dfs():
if self.i == self.n or no... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_034279 | 2,035 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 35010d67341e6038ae4ddffb4beba4a9dba05d2a | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return '$'
return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
def deserialize(self, data: str) -> TreeNode:
"""Decodes ... | the_stack_v2_python_sparse | src/0449-serialize-and-deserialize-bst/serialize-and-deserialize-bst.py | HLNN/leetcode | train | 6 | |
98d1401cb23017cd46df09ba02d662d1739e6a39 | [
"if User.objects.filter(username=request.data['username']).exists():\n return Response({'error': 'LOGIN', 'message': 'User was NOT created, because LOGIN is exists'}, status=status.HTTP_409_CONFLICT)\nif User.objects.filter(email=request.data['email']).exists():\n return Response({'error': 'EMAIL', 'message':... | <|body_start_0|>
if User.objects.filter(username=request.data['username']).exists():
return Response({'error': 'LOGIN', 'message': 'User was NOT created, because LOGIN is exists'}, status=status.HTTP_409_CONFLICT)
if User.objects.filter(email=request.data['email']).exists():
retu... | RegistrationAPIView | RegistrationAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationAPIView:
"""RegistrationAPIView"""
def create(self, request, *args, **kwargs):
"""rewrite method create"""
<|body_0|>
def perform_create(self, serializer):
"""rewrite method perform_create"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_034280 | 12,972 | no_license | [
{
"docstring": "rewrite method create",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "rewrite method perform_create",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020205 | Implement the Python class `RegistrationAPIView` described below.
Class description:
RegistrationAPIView
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): rewrite method create
- def perform_create(self, serializer): rewrite method perform_create | Implement the Python class `RegistrationAPIView` described below.
Class description:
RegistrationAPIView
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): rewrite method create
- def perform_create(self, serializer): rewrite method perform_create
<|skeleton|>
class RegistrationAPIView:
... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class RegistrationAPIView:
"""RegistrationAPIView"""
def create(self, request, *args, **kwargs):
"""rewrite method create"""
<|body_0|>
def perform_create(self, serializer):
"""rewrite method perform_create"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationAPIView:
"""RegistrationAPIView"""
def create(self, request, *args, **kwargs):
"""rewrite method create"""
if User.objects.filter(username=request.data['username']).exists():
return Response({'error': 'LOGIN', 'message': 'User was NOT created, because LOGIN is exis... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/authorization/api/views.py | HeCToR74/Python | train | 1 |
09a4b2d8bcd22f3491c67dfa41c12d6ed4ecb4c4 | [
"regions = {'HadCRUT': '', 'CRUTEM': '_Land', 'HadSST': '_Ocean'}\nif isinstance(data, xr.Dataset) or isinstance(data, xr.DataArray):\n _data = data\n self.region = ''\nelif type(data) == str and data.endswith('.nc'):\n _data = xr.open_dataset(data)\n self.region = regions[data.split('/')[-1].split('.')... | <|body_start_0|>
regions = {'HadCRUT': '', 'CRUTEM': '_Land', 'HadSST': '_Ocean'}
if isinstance(data, xr.Dataset) or isinstance(data, xr.DataArray):
_data = data
self.region = ''
elif type(data) == str and data.endswith('.nc'):
_data = xr.open_dataset(data)
... | This class takes an instance of the netCDF datasets from the data/temp/crudata folder. It provides features to prepare the datasets for compatibility for the functions in the Analysis class. This includes the averaging of temperature on spatial and temporal scales and conversion of cfdatetime time objects to datetime. ... | SpatialAve | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialAve:
"""This class takes an instance of the netCDF datasets from the data/temp/crudata folder. It provides features to prepare the datasets for compatibility for the functions in the Analysis class. This includes the averaging of temperature on spatial and temporal scales and conversion of... | stack_v2_sparse_classes_36k_train_034281 | 7,521 | no_license | [
{
"docstring": "Initialise an instance of an SpatialAve.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Returns a list or slice object of a range of time points, as is required when selecting time points for other functions. Parameters ========== start_time: str... | 4 | null | Implement the Python class `SpatialAve` described below.
Class description:
This class takes an instance of the netCDF datasets from the data/temp/crudata folder. It provides features to prepare the datasets for compatibility for the functions in the Analysis class. This includes the averaging of temperature on spatia... | Implement the Python class `SpatialAve` described below.
Class description:
This class takes an instance of the netCDF datasets from the data/temp/crudata folder. It provides features to prepare the datasets for compatibility for the functions in the Analysis class. This includes the averaging of temperature on spatia... | 9bf6fa6a8675dd941185b33757a9817e4dae3ef2 | <|skeleton|>
class SpatialAve:
"""This class takes an instance of the netCDF datasets from the data/temp/crudata folder. It provides features to prepare the datasets for compatibility for the functions in the Analysis class. This includes the averaging of temperature on spatial and temporal scales and conversion of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialAve:
"""This class takes an instance of the netCDF datasets from the data/temp/crudata folder. It provides features to prepare the datasets for compatibility for the functions in the Analysis class. This includes the averaging of temperature on spatial and temporal scales and conversion of cfdatetime t... | the_stack_v2_python_sparse | scripts/core/TEMP.py | rursino/carbon-cycle-feedbacks | train | 1 |
8be088dda6bf281c0a914a1d9b5ca899b01e3fc0 | [
"self.k = k\nself.hash_func = hash_func\nself.elements = {}\nself.advice_obj = advice_obj\nself.func_of_freq = lambda x: x ** p",
"sorted_elements = sorted(self.elements.items(), key=lambda x: x[1][0])\nfor i in range(self.k, len(sorted_elements)):\n del self.elements[sorted_elements[i][0]]",
"if key in self... | <|body_start_0|>
self.k = k
self.hash_func = hash_func
self.elements = {}
self.advice_obj = advice_obj
self.func_of_freq = lambda x: x ** p
<|end_body_0|>
<|body_start_1|>
sorted_elements = sorted(self.elements.items(), key=lambda x: x[1][0])
for i in range(self.... | Sketch for estimating frequency moments using advice. The sketch maintains a sample of at most k keys. For each key, we store its seed, which is computed using a hash function, and its frequency so far (the sum of weights of elements with that key). The sample always contains the k keys with lowest seed. For each key x... | MomentEstimatorSketch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MomentEstimatorSketch:
"""Sketch for estimating frequency moments using advice. The sketch maintains a sample of at most k keys. For each key, we store its seed, which is computed using a hash function, and its frequency so far (the sum of weights of elements with that key). The sample always con... | stack_v2_sparse_classes_36k_train_034282 | 24,996 | permissive | [
{
"docstring": "Initializes an empty sketch/sample of specified size. Args: k: Sample size hash_func: The randomness used for the sample (a hash function that maps each key into a supposedly independent exponential random variable with parameter 1) p: The moment estimated by the sketch advice_obj: An object tha... | 4 | stack_v2_sparse_classes_30k_train_013607 | Implement the Python class `MomentEstimatorSketch` described below.
Class description:
Sketch for estimating frequency moments using advice. The sketch maintains a sample of at most k keys. For each key, we store its seed, which is computed using a hash function, and its frequency so far (the sum of weights of element... | Implement the Python class `MomentEstimatorSketch` described below.
Class description:
Sketch for estimating frequency moments using advice. The sketch maintains a sample of at most k keys. For each key, we store its seed, which is computed using a hash function, and its frequency so far (the sum of weights of element... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class MomentEstimatorSketch:
"""Sketch for estimating frequency moments using advice. The sketch maintains a sample of at most k keys. For each key, we store its seed, which is computed using a hash function, and its frequency so far (the sum of weights of elements with that key). The sample always con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MomentEstimatorSketch:
"""Sketch for estimating frequency moments using advice. The sketch maintains a sample of at most k keys. For each key, we store its seed, which is computed using a hash function, and its frequency so far (the sum of weights of elements with that key). The sample always contains the k k... | the_stack_v2_python_sparse | moment_advice/moment_advice.py | Ayoob7/google-research | train | 2 |
2600976fde526ba9176dabb72e76ada8016158f8 | [
"self.split = split.lower()\nself.crop_size = crop_size\nself.scaling_factor = scaling_factor\nself.lr_img_type, self.hr_img_type = ('imagenet-norm', 'imagenet-norm')\nassert self.split in {'train', 'test'}",
"lr_img = hr_img.resize((int(hr_img.width / self.scaling_factor), int(hr_img.height / self.scaling_factor... | <|body_start_0|>
self.split = split.lower()
self.crop_size = crop_size
self.scaling_factor = scaling_factor
self.lr_img_type, self.hr_img_type = ('imagenet-norm', 'imagenet-norm')
assert self.split in {'train', 'test'}
<|end_body_0|>
<|body_start_1|>
lr_img = hr_img.resi... | Image transformation pipeline. | ImageTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTransformer:
"""Image transformation pipeline."""
def __init__(self, split, crop_size, scaling_factor):
""":param split: one of 'train' or 'test' :param crop_size: crop size of HR images :param scaling_factor: LR images will be downsampled from the HR images by this factor"""
... | stack_v2_sparse_classes_36k_train_034283 | 3,561 | permissive | [
{
"docstring": ":param split: one of 'train' or 'test' :param crop_size: crop size of HR images :param scaling_factor: LR images will be downsampled from the HR images by this factor",
"name": "__init__",
"signature": "def __init__(self, split, crop_size, scaling_factor)"
},
{
"docstring": ":par... | 2 | stack_v2_sparse_classes_30k_test_000586 | Implement the Python class `ImageTransformer` described below.
Class description:
Image transformation pipeline.
Method signatures and docstrings:
- def __init__(self, split, crop_size, scaling_factor): :param split: one of 'train' or 'test' :param crop_size: crop size of HR images :param scaling_factor: LR images wi... | Implement the Python class `ImageTransformer` described below.
Class description:
Image transformation pipeline.
Method signatures and docstrings:
- def __init__(self, split, crop_size, scaling_factor): :param split: one of 'train' or 'test' :param crop_size: crop size of HR images :param scaling_factor: LR images wi... | b9a10c18a30080c7ae4f8c75d860477cb884aec8 | <|skeleton|>
class ImageTransformer:
"""Image transformation pipeline."""
def __init__(self, split, crop_size, scaling_factor):
""":param split: one of 'train' or 'test' :param crop_size: crop size of HR images :param scaling_factor: LR images will be downsampled from the HR images by this factor"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageTransformer:
"""Image transformation pipeline."""
def __init__(self, split, crop_size, scaling_factor):
""":param split: one of 'train' or 'test' :param crop_size: crop size of HR images :param scaling_factor: LR images will be downsampled from the HR images by this factor"""
self.sp... | the_stack_v2_python_sparse | src/utils/image_operations.py | wvitzthum/DL_super_resolution | train | 1 |
286342270909fcc1e02f8c60a70b9e23a607b65d | [
"if 'table' not in k:\n k['table'] = self.table\nif 'engine' not in k:\n k['engine'] = k['table'].bind\nreturn alter_column(self, *p, **k)",
"table = _normalize_table(self, table)\nengine = table.bind\nvisitorcallable = get_engine_visitor(engine, 'columngenerator')\nengine._run_visitor(visitorcallable, self... | <|body_start_0|>
if 'table' not in k:
k['table'] = self.table
if 'engine' not in k:
k['engine'] = k['table'].bind
return alter_column(self, *p, **k)
<|end_body_0|>
<|body_start_1|>
table = _normalize_table(self, table)
engine = table.bind
visitorc... | Changeset extensions to SQLAlchemy columns | ChangesetColumn | [
"CC-BY-2.5",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangesetColumn:
"""Changeset extensions to SQLAlchemy columns"""
def alter(self, *p, **k):
"""Alter a column's definition: ``ALTER TABLE ALTER COLUMN``. May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('my... | stack_v2_sparse_classes_36k_train_034284 | 13,759 | permissive | [
{
"docstring": "Alter a column's definition: ``ALTER TABLE ALTER COLUMN``. May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('myint', Integer, nullable=False)) col.alter('myint', Integer, nullable=False) col.alter(name='myint', type=In... | 3 | stack_v2_sparse_classes_30k_train_007912 | Implement the Python class `ChangesetColumn` described below.
Class description:
Changeset extensions to SQLAlchemy columns
Method signatures and docstrings:
- def alter(self, *p, **k): Alter a column's definition: ``ALTER TABLE ALTER COLUMN``. May supply a new column object, or a list of properties to change. For ex... | Implement the Python class `ChangesetColumn` described below.
Class description:
Changeset extensions to SQLAlchemy columns
Method signatures and docstrings:
- def alter(self, *p, **k): Alter a column's definition: ``ALTER TABLE ALTER COLUMN``. May supply a new column object, or a list of properties to change. For ex... | 3c44ecaf4b2e1f2d7269eabef19cbd2e88b3a99c | <|skeleton|>
class ChangesetColumn:
"""Changeset extensions to SQLAlchemy columns"""
def alter(self, *p, **k):
"""Alter a column's definition: ``ALTER TABLE ALTER COLUMN``. May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('my... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangesetColumn:
"""Changeset extensions to SQLAlchemy columns"""
def alter(self, *p, **k):
"""Alter a column's definition: ``ALTER TABLE ALTER COLUMN``. May supply a new column object, or a list of properties to change. For example; the following are equivalent: col.alter(Column('myint', Integer... | the_stack_v2_python_sparse | eggs/sqlalchemy_migrate-0.5.4-py2.7.egg/migrate/changeset/schema.py | JCVI-Cloud/galaxy-tools-prok | train | 0 |
01f69e4541f9144b164c9c5256d6c2e6a1317b49 | [
"super(PairedDataset, self).__init__(preprocess)\nself.dataroot = dataroot\nself.data_infos = self.prepare_data_infos()",
"data_infos = []\npair_paths = sorted(self.scan_folder(self.dataroot))\nfor pair_path in pair_paths:\n data_infos.append(dict(pair_path=pair_path))\nreturn data_infos"
] | <|body_start_0|>
super(PairedDataset, self).__init__(preprocess)
self.dataroot = dataroot
self.data_infos = self.prepare_data_infos()
<|end_body_0|>
<|body_start_1|>
data_infos = []
pair_paths = sorted(self.scan_folder(self.dataroot))
for pair_path in pair_paths:
... | A dataset class for paired image dataset. | PairedDataset | [
"MIT",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairedDataset:
"""A dataset class for paired image dataset."""
def __init__(self, dataroot, preprocess):
"""Initialize this dataset class. Args: dataroot (str): Directory of dataset. preprocess (list[dict]): A sequence of data preprocess config."""
<|body_0|>
def prepare... | stack_v2_sparse_classes_36k_train_034285 | 1,546 | permissive | [
{
"docstring": "Initialize this dataset class. Args: dataroot (str): Directory of dataset. preprocess (list[dict]): A sequence of data preprocess config.",
"name": "__init__",
"signature": "def __init__(self, dataroot, preprocess)"
},
{
"docstring": "Load paired image paths. Returns: list[dict]:... | 2 | null | Implement the Python class `PairedDataset` described below.
Class description:
A dataset class for paired image dataset.
Method signatures and docstrings:
- def __init__(self, dataroot, preprocess): Initialize this dataset class. Args: dataroot (str): Directory of dataset. preprocess (list[dict]): A sequence of data ... | Implement the Python class `PairedDataset` described below.
Class description:
A dataset class for paired image dataset.
Method signatures and docstrings:
- def __init__(self, dataroot, preprocess): Initialize this dataset class. Args: dataroot (str): Directory of dataset. preprocess (list[dict]): A sequence of data ... | 038fb5afe017b82334ad39a256531d2c4e9e1e1a | <|skeleton|>
class PairedDataset:
"""A dataset class for paired image dataset."""
def __init__(self, dataroot, preprocess):
"""Initialize this dataset class. Args: dataroot (str): Directory of dataset. preprocess (list[dict]): A sequence of data preprocess config."""
<|body_0|>
def prepare... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PairedDataset:
"""A dataset class for paired image dataset."""
def __init__(self, dataroot, preprocess):
"""Initialize this dataset class. Args: dataroot (str): Directory of dataset. preprocess (list[dict]): A sequence of data preprocess config."""
super(PairedDataset, self).__init__(prep... | the_stack_v2_python_sparse | 15.PaddleGAN/PaddleGAN/ppgan/datasets/paired_dataset.py | yingshaoxo/ML | train | 5 |
21be91b5fccc606b32d9fa1bb818ef5780396ae9 | [
"token = self.token\nif token is None:\n self.error.line('no token to decode')\n self.error.line('please supply a token')\n self.error.line(' using:')\n self.error.log(' {.pyre_namespace} {.pyre_spec} decode --token=<str>'.format(plexus, self))\n return 1\nidd = plexus.idd\ntoken = idd.normalize(... | <|body_start_0|>
token = self.token
if token is None:
self.error.line('no token to decode')
self.error.line('please supply a token')
self.error.line(' using:')
self.error.log(' {.pyre_namespace} {.pyre_spec} decode --token=<str>'.format(plexus, self))
... | Direct access to the token generator | IDD | [
"Plexus"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IDD:
"""Direct access to the token generator"""
def decode(self, plexus, **kwds):
"""Decode the given {token} on the command line"""
<|body_0|>
def encode(self, plexus, **kwds):
"""Decode the given {token} on the command line"""
<|body_1|>
def peek(s... | stack_v2_sparse_classes_36k_train_034286 | 4,099 | permissive | [
{
"docstring": "Decode the given {token} on the command line",
"name": "decode",
"signature": "def decode(self, plexus, **kwds)"
},
{
"docstring": "Decode the given {token} on the command line",
"name": "encode",
"signature": "def encode(self, plexus, **kwds)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_020580 | Implement the Python class `IDD` described below.
Class description:
Direct access to the token generator
Method signatures and docstrings:
- def decode(self, plexus, **kwds): Decode the given {token} on the command line
- def encode(self, plexus, **kwds): Decode the given {token} on the command line
- def peek(self,... | Implement the Python class `IDD` described below.
Class description:
Direct access to the token generator
Method signatures and docstrings:
- def decode(self, plexus, **kwds): Decode the given {token} on the command line
- def encode(self, plexus, **kwds): Decode the given {token} on the command line
- def peek(self,... | 5b1e846d0dcd80934c8238ab0890b2bbb5126d41 | <|skeleton|>
class IDD:
"""Direct access to the token generator"""
def decode(self, plexus, **kwds):
"""Decode the given {token} on the command line"""
<|body_0|>
def encode(self, plexus, **kwds):
"""Decode the given {token} on the command line"""
<|body_1|>
def peek(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IDD:
"""Direct access to the token generator"""
def decode(self, plexus, **kwds):
"""Decode the given {token} on the command line"""
token = self.token
if token is None:
self.error.line('no token to decode')
self.error.line('please supply a token')
... | the_stack_v2_python_sparse | praxis/actions/IDD.py | Orthologue/praxis | train | 0 |
120f5bedbd541f283a3887ba924cf866e3decf02 | [
"self.K = len(lists)\nself.list_index = [0] * self.K\nself.next_list_index = 0\nself.lists = lists",
"result = self.lists[self.next_list_index][self.list_index[self.next_list_index]]\nself.list_index[self.next_list_index] += 1\nself.next_list_index = (self.next_list_index + 1) % self.K\nreturn result",
"index =... | <|body_start_0|>
self.K = len(lists)
self.list_index = [0] * self.K
self.next_list_index = 0
self.lists = lists
<|end_body_0|>
<|body_start_1|>
result = self.lists[self.next_list_index][self.list_index[self.next_list_index]]
self.list_index[self.next_list_index] += 1
... | KZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KZigzagIterator:
def __init__(self, lists):
"""Initialize your data structure here. :type lists: List[List[Int] :type K"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k_train_034287 | 2,234 | no_license | [
{
"docstring": "Initialize your data structure here. :type lists: List[List[Int] :type K",
"name": "__init__",
"signature": "def __init__(self, lists)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "ha... | 3 | null | Implement the Python class `KZigzagIterator` described below.
Class description:
Implement the KZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, lists): Initialize your data structure here. :type lists: List[List[Int] :type K
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `KZigzagIterator` described below.
Class description:
Implement the KZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, lists): Initialize your data structure here. :type lists: List[List[Int] :type K
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
... | 08c6d27498e35f636045fed05a6f94b760ab69ca | <|skeleton|>
class KZigzagIterator:
def __init__(self, lists):
"""Initialize your data structure here. :type lists: List[List[Int] :type K"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KZigzagIterator:
def __init__(self, lists):
"""Initialize your data structure here. :type lists: List[List[Int] :type K"""
self.K = len(lists)
self.list_index = [0] * self.K
self.next_list_index = 0
self.lists = lists
def next(self):
""":rtype: int"""
... | the_stack_v2_python_sparse | solutions/design/281.Zigzag.Iterator.py | ljia2/leetcode.py | train | 0 | |
cba7a500f720314998b806e07249b0856f963d60 | [
"self.auto_lock_after_duration_idle = auto_lock_after_duration_idle\nself.default_file_retention_duration_msecs = default_file_retention_duration_msecs\nself.expiry_timestamp_msecs = expiry_timestamp_msecs\nself.locking_protocol = locking_protocol\nself.max_retention_duration_msecs = max_retention_duration_msecs\ns... | <|body_start_0|>
self.auto_lock_after_duration_idle = auto_lock_after_duration_idle
self.default_file_retention_duration_msecs = default_file_retention_duration_msecs
self.expiry_timestamp_msecs = expiry_timestamp_msecs
self.locking_protocol = locking_protocol
self.max_retention_... | Implementation of the 'FileLevelDataLockConfig' model. Specifies a config to lock files in a view - to protect from malicious or an accidental attempt to delete or modify the files in this view. Attributes: auto_lock_after_duration_idle (long|int): Specifies the duration to lock a file that has not been accessed or mod... | FileLevelDataLockConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileLevelDataLockConfig:
"""Implementation of the 'FileLevelDataLockConfig' model. Specifies a config to lock files in a view - to protect from malicious or an accidental attempt to delete or modify the files in this view. Attributes: auto_lock_after_duration_idle (long|int): Specifies the durati... | stack_v2_sparse_classes_36k_train_034288 | 6,693 | permissive | [
{
"docstring": "Constructor for the FileLevelDataLockConfig class",
"name": "__init__",
"signature": "def __init__(self, auto_lock_after_duration_idle=None, default_file_retention_duration_msecs=None, expiry_timestamp_msecs=None, locking_protocol=None, max_retention_duration_msecs=None, min_retention_du... | 2 | null | Implement the Python class `FileLevelDataLockConfig` described below.
Class description:
Implementation of the 'FileLevelDataLockConfig' model. Specifies a config to lock files in a view - to protect from malicious or an accidental attempt to delete or modify the files in this view. Attributes: auto_lock_after_duratio... | Implement the Python class `FileLevelDataLockConfig` described below.
Class description:
Implementation of the 'FileLevelDataLockConfig' model. Specifies a config to lock files in a view - to protect from malicious or an accidental attempt to delete or modify the files in this view. Attributes: auto_lock_after_duratio... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FileLevelDataLockConfig:
"""Implementation of the 'FileLevelDataLockConfig' model. Specifies a config to lock files in a view - to protect from malicious or an accidental attempt to delete or modify the files in this view. Attributes: auto_lock_after_duration_idle (long|int): Specifies the durati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileLevelDataLockConfig:
"""Implementation of the 'FileLevelDataLockConfig' model. Specifies a config to lock files in a view - to protect from malicious or an accidental attempt to delete or modify the files in this view. Attributes: auto_lock_after_duration_idle (long|int): Specifies the duration to lock a ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_level_data_lock_config.py | cohesity/management-sdk-python | train | 24 |
67425d66f165e89fb8ebd9d1d52ad4d98ae8c381 | [
"batch_size = 4\npadded_length = 6\nnum_classes = 4\nnp.random.seed(1234)\nsequence_length = np.random.randint(0, padded_length + 1, batch_size)\nactivations = np.random.rand(batch_size, padded_length, num_classes)\nlabels = np.random.randint(0, num_classes, [batch_size, padded_length])\nactivations_masked_t, label... | <|body_start_0|>
batch_size = 4
padded_length = 6
num_classes = 4
np.random.seed(1234)
sequence_length = np.random.randint(0, padded_length + 1, batch_size)
activations = np.random.rand(batch_size, padded_length, num_classes)
labels = np.random.randint(0, num_clas... | RnnCommonTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RnnCommonTest:
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
<|body_0|>
def testSelectLastActivations(self):
"""Test `select_last_activations`."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
batch_size = 4
... | stack_v2_sparse_classes_36k_train_034289 | 4,838 | permissive | [
{
"docstring": "Test `mask_activations_and_labels`.",
"name": "testMaskActivationsAndLabels",
"signature": "def testMaskActivationsAndLabels(self)"
},
{
"docstring": "Test `select_last_activations`.",
"name": "testSelectLastActivations",
"signature": "def testSelectLastActivations(self)"... | 2 | stack_v2_sparse_classes_30k_train_010772 | Implement the Python class `RnnCommonTest` described below.
Class description:
Implement the RnnCommonTest class.
Method signatures and docstrings:
- def testMaskActivationsAndLabels(self): Test `mask_activations_and_labels`.
- def testSelectLastActivations(self): Test `select_last_activations`. | Implement the Python class `RnnCommonTest` described below.
Class description:
Implement the RnnCommonTest class.
Method signatures and docstrings:
- def testMaskActivationsAndLabels(self): Test `mask_activations_and_labels`.
- def testSelectLastActivations(self): Test `select_last_activations`.
<|skeleton|>
class R... | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | <|skeleton|>
class RnnCommonTest:
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
<|body_0|>
def testSelectLastActivations(self):
"""Test `select_last_activations`."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RnnCommonTest:
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
batch_size = 4
padded_length = 6
num_classes = 4
np.random.seed(1234)
sequence_length = np.random.randint(0, padded_length + 1, batch_size)
activations = np.... | the_stack_v2_python_sparse | tensorflow/contrib/learn/python/learn/estimators/rnn_common_test.py | NVIDIA/tensorflow | train | 763 | |
a0e49acc8c730929c378924c601b41a8d7cf4485 | [
"super().__init__(detect_lines, detect_lines=detect_lines)\nself._negatives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAYSCALE)) / 255 for path in glob.glob(os.path.join(path, '**', 'negative-*.png'), recursive=True)]\nself._positives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAYSCALE)) / 255 for path in glob.glo... | <|body_start_0|>
super().__init__(detect_lines, detect_lines=detect_lines)
self._negatives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAYSCALE)) / 255 for path in glob.glob(os.path.join(path, '**', 'negative-*.png'), recursive=True)]
self._positives = [np.float32(cv2.imread(path, cv2.IMREAD_GRAY... | Obtains edges for for further processing. | EdgeDetectionTemplateMatching | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeDetectionTemplateMatching:
"""Obtains edges for for further processing."""
def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False):
"""Initializes a new instance of the EdgeDetection class."""
<|body_0|>
def filter(sel... | stack_v2_sparse_classes_36k_train_034290 | 2,342 | permissive | [
{
"docstring": "Initializes a new instance of the EdgeDetection class.",
"name": "__init__",
"signature": "def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False)"
},
{
"docstring": "Filters the specified image. :param img: The image to obtain mas... | 2 | stack_v2_sparse_classes_30k_train_006924 | Implement the Python class `EdgeDetectionTemplateMatching` described below.
Class description:
Obtains edges for for further processing.
Method signatures and docstrings:
- def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False): Initializes a new instance of the EdgeD... | Implement the Python class `EdgeDetectionTemplateMatching` described below.
Class description:
Obtains edges for for further processing.
Method signatures and docstrings:
- def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False): Initializes a new instance of the EdgeD... | 9692cf242f6d531fe37dca9ec462c632f1bcf832 | <|skeleton|>
class EdgeDetectionTemplateMatching:
"""Obtains edges for for further processing."""
def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False):
"""Initializes a new instance of the EdgeDetection class."""
<|body_0|>
def filter(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeDetectionTemplateMatching:
"""Obtains edges for for further processing."""
def __init__(self, path: str, workers: int=8, mask: Optional[np.ndarray]=None, detect_lines: bool=False):
"""Initializes a new instance of the EdgeDetection class."""
super().__init__(detect_lines, detect_lines... | the_stack_v2_python_sparse | pipeline/edges/EdgeDetectionTemplateMatching.py | sunsided/CarND-Advanced-Lane-Lines | train | 1 |
b8af26faeb4444367f05b43d3ffe9fba193942e1 | [
"obj = context.object\nif obj is None:\n return False\nreturn all([bool(obj), obj.type == 'MESH', obj.mode == 'EDIT'])",
"scene = context.scene\npg = scene.pdt_pg\nobj = bpy.context.view_layer.objects.active\nif obj is None:\n self.report({'ERROR'}, PDT_ERR_NO_ACT_OBJ)\n return {'FINISHED'}\nif obj.mode ... | <|body_start_0|>
obj = context.object
if obj is None:
return False
return all([bool(obj), obj.type == 'MESH', obj.mode == 'EDIT'])
<|end_body_0|>
<|body_start_1|>
scene = context.scene
pg = scene.pdt_pg
obj = bpy.context.view_layer.objects.active
if o... | Scale Selected Vertices about Pivot Point | PDT_OT_ViewPlaneScale | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDT_OT_ViewPlaneScale:
"""Scale Selected Vertices about Pivot Point"""
def poll(cls, context):
"""Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing."""
<|body_0|>
def execute(self, context):
"""Scales Selected Vertices about Pivot... | stack_v2_sparse_classes_36k_train_034291 | 13,734 | permissive | [
{
"docstring": "Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.",
"name": "poll",
"signature": "def poll(cls, context)"
},
{
"docstring": "Scales Selected Vertices about Pivot Point. Note: Scales any selected vertices about the Pivot Point in View Oriented coo... | 2 | stack_v2_sparse_classes_30k_train_010184 | Implement the Python class `PDT_OT_ViewPlaneScale` described below.
Class description:
Scale Selected Vertices about Pivot Point
Method signatures and docstrings:
- def poll(cls, context): Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.
- def execute(self, context): Scales Selected... | Implement the Python class `PDT_OT_ViewPlaneScale` described below.
Class description:
Scale Selected Vertices about Pivot Point
Method signatures and docstrings:
- def poll(cls, context): Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.
- def execute(self, context): Scales Selected... | 4d5c304878c1e0018d97c1b07bcaa3981632265a | <|skeleton|>
class PDT_OT_ViewPlaneScale:
"""Scale Selected Vertices about Pivot Point"""
def poll(cls, context):
"""Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing."""
<|body_0|>
def execute(self, context):
"""Scales Selected Vertices about Pivot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PDT_OT_ViewPlaneScale:
"""Scale Selected Vertices about Pivot Point"""
def poll(cls, context):
"""Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing."""
obj = context.object
if obj is None:
return False
return all([bool(obj), obj... | the_stack_v2_python_sparse | src/bpy/3.6/scripts/addons/precision_drawing_tools/pdt_pivot_point.py | RnoB/3DVisualSwarm | train | 0 |
a862c2e928dbe9884d24eab882b3f0fbcecc06bb | [
"if root is None:\n return True\nelif root.left is None and root.right is None:\n return True\nelse:\n if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1:\n if self.isBalanced(root.left) and self.isBalanced(root.right):\n return True\n return False",
"if root is None:\... | <|body_start_0|>
if root is None:
return True
elif root.left is None and root.right is None:
return True
else:
if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1:
if self.isBalanced(root.left) and self.isBalanced(root.right):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return True
e... | stack_v2_sparse_classes_36k_train_034292 | 1,194 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007141 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def maxDepth(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 isBalanced(self, root): :type root: TreeNode :rtype: bool
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def isBalanced(self,... | 26fddfdbd09c30376cb0720e13baf0402c3a1e90 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def maxDepth(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 isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
elif root.left is None and root.right is None:
return True
else:
if abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1:
... | the_stack_v2_python_sparse | old/Tree/110.py | cosJin/LeetCode | train | 0 | |
1ce9646cc7a8a4278dfbfcde159bdfa0b06f05b5 | [
"gt_bboxes, gt_bboxes_ignore = ([], [])\ngt_masks, gt_masks_ignore = ([], [])\ngt_labels = []\nfor ann in annotations:\n if ann.get('iscrowd', False):\n gt_bboxes_ignore.append(ann['bbox'])\n gt_masks_ignore.append(ann.get('segmentation', None))\n else:\n gt_bboxes.append(ann['bbox'])\n ... | <|body_start_0|>
gt_bboxes, gt_bboxes_ignore = ([], [])
gt_masks, gt_masks_ignore = ([], [])
gt_labels = []
for ann in annotations:
if ann.get('iscrowd', False):
gt_bboxes_ignore.append(ann['bbox'])
gt_masks_ignore.append(ann.get('segmentation'... | TextDetDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextDetDataset:
def _parse_anno_info(self, annotations):
"""Parse bbox and mask annotation. Args: annotations (dict): Annotations of one image. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, masks_ignore. "masks" and "masks_ignore" are represen... | stack_v2_sparse_classes_36k_train_034293 | 4,665 | permissive | [
{
"docstring": "Parse bbox and mask annotation. Args: annotations (dict): Annotations of one image. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, masks_ignore. \"masks\" and \"masks_ignore\" are represented by polygon boundary point sequences.",
"name": "_parse_a... | 3 | stack_v2_sparse_classes_30k_train_008920 | Implement the Python class `TextDetDataset` described below.
Class description:
Implement the TextDetDataset class.
Method signatures and docstrings:
- def _parse_anno_info(self, annotations): Parse bbox and mask annotation. Args: annotations (dict): Annotations of one image. Returns: dict: A dict containing the foll... | Implement the Python class `TextDetDataset` described below.
Class description:
Implement the TextDetDataset class.
Method signatures and docstrings:
- def _parse_anno_info(self, annotations): Parse bbox and mask annotation. Args: annotations (dict): Annotations of one image. Returns: dict: A dict containing the foll... | 89bf8a218881b250d0ead7a0287526c69586c92a | <|skeleton|>
class TextDetDataset:
def _parse_anno_info(self, annotations):
"""Parse bbox and mask annotation. Args: annotations (dict): Annotations of one image. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, masks_ignore. "masks" and "masks_ignore" are represen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextDetDataset:
def _parse_anno_info(self, annotations):
"""Parse bbox and mask annotation. Args: annotations (dict): Annotations of one image. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, masks_ignore. "masks" and "masks_ignore" are represented by polygon... | the_stack_v2_python_sparse | mmocr/datasets/text_det_dataset.py | xdxie/WordArt | train | 106 | |
c1bb8b08ee0d38c31aa160e1ac2d690940904a3a | [
"super(XDATCAR, self).__init__()\nself.configurations = []\nif filename:\n self.load_file(open_by_suffix(str(filename)))",
"self.system_name = next(thefile).strip()\nself.scaling_factor = float(next(thefile).strip())\nself.cell_vecs[0] = np.array([float(x) for x in next(thefile).split()])\nself.cell_vecs[1] = ... | <|body_start_0|>
super(XDATCAR, self).__init__()
self.configurations = []
if filename:
self.load_file(open_by_suffix(str(filename)))
<|end_body_0|>
<|body_start_1|>
self.system_name = next(thefile).strip()
self.scaling_factor = float(next(thefile).strip())
se... | Class for XDATCAR. Attributes ---------- configurations: list | XDATCAR | [
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XDATCAR:
"""Class for XDATCAR. Attributes ---------- configurations: list"""
def __init__(self, filename: Union[str, Path, None]=None) -> None:
"""Initialize. Parameters ---------- arg: str XDATCAR file name"""
<|body_0|>
def load_file(self, thefile: IO[str]) -> None:
... | stack_v2_sparse_classes_36k_train_034294 | 2,761 | permissive | [
{
"docstring": "Initialize. Parameters ---------- arg: str XDATCAR file name",
"name": "__init__",
"signature": "def __init__(self, filename: Union[str, Path, None]=None) -> None"
},
{
"docstring": "Parse PROCAR. Parameters ---------- thefile: StringIO 'XDATCAR' file",
"name": "load_file",
... | 3 | stack_v2_sparse_classes_30k_train_013284 | Implement the Python class `XDATCAR` described below.
Class description:
Class for XDATCAR. Attributes ---------- configurations: list
Method signatures and docstrings:
- def __init__(self, filename: Union[str, Path, None]=None) -> None: Initialize. Parameters ---------- arg: str XDATCAR file name
- def load_file(sel... | Implement the Python class `XDATCAR` described below.
Class description:
Class for XDATCAR. Attributes ---------- configurations: list
Method signatures and docstrings:
- def __init__(self, filename: Union[str, Path, None]=None) -> None: Initialize. Parameters ---------- arg: str XDATCAR file name
- def load_file(sel... | 36342eb9b2523fc5c878db5e269e77a51352364c | <|skeleton|>
class XDATCAR:
"""Class for XDATCAR. Attributes ---------- configurations: list"""
def __init__(self, filename: Union[str, Path, None]=None) -> None:
"""Initialize. Parameters ---------- arg: str XDATCAR file name"""
<|body_0|>
def load_file(self, thefile: IO[str]) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XDATCAR:
"""Class for XDATCAR. Attributes ---------- configurations: list"""
def __init__(self, filename: Union[str, Path, None]=None) -> None:
"""Initialize. Parameters ---------- arg: str XDATCAR file name"""
super(XDATCAR, self).__init__()
self.configurations = []
if fi... | the_stack_v2_python_sparse | vaspy/xdatcar.py | sailfish009/vaspy-1 | train | 0 |
46f324c5e26717807963c5ebe1bd34e28eacbc0e | [
"worlds = World.objects.all()\nserializer = WorldListSerializer(worlds, many=True)\nreturn Response(serializer.data)",
"queryset = World.objects.all()\nworld = get_object_or_404(queryset, pk=pk)\nserializer = WorldSerializer(world)\nreturn Response(serializer.data)"
] | <|body_start_0|>
worlds = World.objects.all()
serializer = WorldListSerializer(worlds, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = World.objects.all()
world = get_object_or_404(queryset, pk=pk)
serializer = WorldSerializer(world... | WorldsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorldsView:
def list(self, request):
"""Получение списка миров"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение мира по идентификатору pk = идентификатор мира"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
worlds = World.objects.all... | stack_v2_sparse_classes_36k_train_034295 | 12,404 | no_license | [
{
"docstring": "Получение списка миров",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Получение мира по идентификатору pk = идентификатор мира",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004894 | Implement the Python class `WorldsView` described below.
Class description:
Implement the WorldsView class.
Method signatures and docstrings:
- def list(self, request): Получение списка миров
- def retrieve(self, request, pk=None): Получение мира по идентификатору pk = идентификатор мира | Implement the Python class `WorldsView` described below.
Class description:
Implement the WorldsView class.
Method signatures and docstrings:
- def list(self, request): Получение списка миров
- def retrieve(self, request, pk=None): Получение мира по идентификатору pk = идентификатор мира
<|skeleton|>
class WorldsVie... | be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d | <|skeleton|>
class WorldsView:
def list(self, request):
"""Получение списка миров"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение мира по идентификатору pk = идентификатор мира"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorldsView:
def list(self, request):
"""Получение списка миров"""
worlds = World.objects.all()
serializer = WorldListSerializer(worlds, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Получение мира по идентификатору pk = иденти... | the_stack_v2_python_sparse | StarfinderBack/starfinder/views.py | Skirgus/StarfinderMasterAssistant | train | 0 | |
e04f857ccfad76cbf06f8c74727bc55653faa71a | [
"self.cardinality = cardinality\nif norm_factory is None:\n norm_factory = nn.BatchNorm2d\nself.norm_factory = norm_factory\nself.resnext_class = copy(models.resnet.Bottleneck)\nself.resnext_class.expansion = 2",
"stride = 1\nprojection = None\nif downsample > 1:\n stride = downsample\nif downsample > 1 or ... | <|body_start_0|>
self.cardinality = cardinality
if norm_factory is None:
norm_factory = nn.BatchNorm2d
self.norm_factory = norm_factory
self.resnext_class = copy(models.resnet.Bottleneck)
self.resnext_class.expansion = 2
<|end_body_0|>
<|body_start_1|>
stride... | Factory wrapper for ``torchvision`` ResNeXt blocks. | ResNeXtBlockFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNeXtBlockFactory:
"""Factory wrapper for ``torchvision`` ResNeXt blocks."""
def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None):
"""Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory obje... | stack_v2_sparse_classes_36k_train_034296 | 6,999 | permissive | [
{
"docstring": "Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory object to produce the normalization layers used in the ResNet blocks. Defaults to batch norm.",
"name": "__init__",
"signature": "def __init__(self, cardinality=32, norm_factory: Opti... | 2 | stack_v2_sparse_classes_30k_train_015309 | Implement the Python class `ResNeXtBlockFactory` described below.
Class description:
Factory wrapper for ``torchvision`` ResNeXt blocks.
Method signatures and docstrings:
- def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): Args: cardinality: The cardinality of the block as d... | Implement the Python class `ResNeXtBlockFactory` described below.
Class description:
Factory wrapper for ``torchvision`` ResNeXt blocks.
Method signatures and docstrings:
- def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): Args: cardinality: The cardinality of the block as d... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class ResNeXtBlockFactory:
"""Factory wrapper for ``torchvision`` ResNeXt blocks."""
def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None):
"""Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResNeXtBlockFactory:
"""Factory wrapper for ``torchvision`` ResNeXt blocks."""
def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None):
"""Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory object to produce... | the_stack_v2_python_sparse | quantnn/models/pytorch/torchvision.py | simonpf/quantnn | train | 7 |
82d34310be5d25a69fe0fa5a10fa86cc430c2ff7 | [
"super().__init__(pipes)\nself.pipes = pipes\nlog.info(f'Produced pipeline: {self}')",
"def reducer(state: PwnState, pipe: Tuple[int, Pipe]) -> PwnState:\n log.debug(repr(state))\n log.info(f'Pipeline [{pipe[0] + 1}/{len(self.pipes)}]: {pipe[1]}')\n return pipe[1](copy(state))\nreturn reduce(reducer, enu... | <|body_start_0|>
super().__init__(pipes)
self.pipes = pipes
log.info(f'Produced pipeline: {self}')
<|end_body_0|>
<|body_start_1|>
def reducer(state: PwnState, pipe: Tuple[int, Pipe]) -> PwnState:
log.debug(repr(state))
log.info(f'Pipeline [{pipe[0] + 1}/{len(sel... | Pipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipeline:
def __init__(self, *pipes: Pipe):
"""Produce a pipeline to put ``PwnState`` through a sequence of Pipes. Produce a state-copying function pipeline, which executes ``funcs`` sequentially, with the output of each function serving as the input to the next function. The state is co... | stack_v2_sparse_classes_36k_train_034297 | 1,641 | permissive | [
{
"docstring": "Produce a pipeline to put ``PwnState`` through a sequence of Pipes. Produce a state-copying function pipeline, which executes ``funcs`` sequentially, with the output of each function serving as the input to the next function. The state is copied on every call, for future black magic caching reas... | 2 | stack_v2_sparse_classes_30k_train_017822 | Implement the Python class `Pipeline` described below.
Class description:
Implement the Pipeline class.
Method signatures and docstrings:
- def __init__(self, *pipes: Pipe): Produce a pipeline to put ``PwnState`` through a sequence of Pipes. Produce a state-copying function pipeline, which executes ``funcs`` sequenti... | Implement the Python class `Pipeline` described below.
Class description:
Implement the Pipeline class.
Method signatures and docstrings:
- def __init__(self, *pipes: Pipe): Produce a pipeline to put ``PwnState`` through a sequence of Pipes. Produce a state-copying function pipeline, which executes ``funcs`` sequenti... | 5735073008f722fab00f3866ef4a05f04620593b | <|skeleton|>
class Pipeline:
def __init__(self, *pipes: Pipe):
"""Produce a pipeline to put ``PwnState`` through a sequence of Pipes. Produce a state-copying function pipeline, which executes ``funcs`` sequentially, with the output of each function serving as the input to the next function. The state is co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pipeline:
def __init__(self, *pipes: Pipe):
"""Produce a pipeline to put ``PwnState`` through a sequence of Pipes. Produce a state-copying function pipeline, which executes ``funcs`` sequentially, with the output of each function serving as the input to the next function. The state is copied on every ... | the_stack_v2_python_sparse | autorop/toplevel/Pipeline.py | Licae/autorop | train | 0 | |
85d6d96659e6ab8df9179e891d05df56649e2e6d | [
"if not root:\n return\nt = TreeNode(root.val)\nif root.children:\n t.left = self.encode(root.children[0])\ncur = t.left\nfor node in root.children[1:]:\n cur.right = self.encode(node)\n cur = cur.right\nreturn t",
"if not data:\n return\nroot = Node(data.val, [])\ncur = data.left\nwhile cur:\n ... | <|body_start_0|>
if not root:
return
t = TreeNode(root.val)
if root.children:
t.left = self.encode(root.children[0])
cur = t.left
for node in root.children[1:]:
cur.right = self.encode(node)
cur = cur.right
return t
<|end_bo... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_034298 | 1,213 | no_license | [
{
"docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode",
"name": "encode",
"signature": "def encode(self, root)"
},
{
"docstring": "Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node",
"name": "decode",
"signature": "def decode... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
if not root:
return
t = TreeNode(root.val)
if root.children:
t.left = self.encode(root.children[0])
cur = t.left
for node in ro... | the_stack_v2_python_sparse | problems/N431_Encode_Nary_Tree_To_Binary_Tree.py | wan-catherine/Leetcode | train | 5 | |
88e253e1c2b70ae5ed98a5c1e2d8a96d38490333 | [
"self._loop = loop\nself.raw = KytosEventBuffer('raw_event', loop=self._loop)\nself.msg_in = KytosEventBuffer('msg_in_event', loop=self._loop)\nself.msg_out = KytosEventBuffer('msg_out_event', loop=self._loop)\nself.app = KytosEventBuffer('app_event', loop=self._loop)",
"LOG.info('Stop signal received by Kytos bu... | <|body_start_0|>
self._loop = loop
self.raw = KytosEventBuffer('raw_event', loop=self._loop)
self.msg_in = KytosEventBuffer('msg_in_event', loop=self._loop)
self.msg_out = KytosEventBuffer('msg_out_event', loop=self._loop)
self.app = KytosEventBuffer('app_event', loop=self._loop)... | Set of KytosEventBuffer used in Kytos. | KytosBuffers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KytosBuffers:
"""Set of KytosEventBuffer used in Kytos."""
def __init__(self, loop=None):
"""Build four KytosEventBuffers. :attr:`raw`: :class:`~kytos.core.buffers.KytosEventBuffer` with events received from network. :attr:`msg_in`: :class:`~kytos.core.buffers.KytosEventBuffer` with ... | stack_v2_sparse_classes_36k_train_034299 | 5,301 | permissive | [
{
"docstring": "Build four KytosEventBuffers. :attr:`raw`: :class:`~kytos.core.buffers.KytosEventBuffer` with events received from network. :attr:`msg_in`: :class:`~kytos.core.buffers.KytosEventBuffer` with events to be received. :attr:`msg_out`: :class:`~kytos.core.buffers.KytosEventBuffer` with events to be s... | 2 | stack_v2_sparse_classes_30k_train_020844 | Implement the Python class `KytosBuffers` described below.
Class description:
Set of KytosEventBuffer used in Kytos.
Method signatures and docstrings:
- def __init__(self, loop=None): Build four KytosEventBuffers. :attr:`raw`: :class:`~kytos.core.buffers.KytosEventBuffer` with events received from network. :attr:`msg... | Implement the Python class `KytosBuffers` described below.
Class description:
Set of KytosEventBuffer used in Kytos.
Method signatures and docstrings:
- def __init__(self, loop=None): Build four KytosEventBuffers. :attr:`raw`: :class:`~kytos.core.buffers.KytosEventBuffer` with events received from network. :attr:`msg... | 3b9731c08fe7550a27d159f4e2de71419c9445f1 | <|skeleton|>
class KytosBuffers:
"""Set of KytosEventBuffer used in Kytos."""
def __init__(self, loop=None):
"""Build four KytosEventBuffers. :attr:`raw`: :class:`~kytos.core.buffers.KytosEventBuffer` with events received from network. :attr:`msg_in`: :class:`~kytos.core.buffers.KytosEventBuffer` with ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KytosBuffers:
"""Set of KytosEventBuffer used in Kytos."""
def __init__(self, loop=None):
"""Build four KytosEventBuffers. :attr:`raw`: :class:`~kytos.core.buffers.KytosEventBuffer` with events received from network. :attr:`msg_in`: :class:`~kytos.core.buffers.KytosEventBuffer` with events to be ... | the_stack_v2_python_sparse | kytos/core/buffers.py | kytos/kytos | train | 45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.