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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b7dc8a89471cf6f7a28f0fabf5af25e096e69961 | [
"length = len(data)\nif length == 0:\n return 0\nfirst = self.get_first_k(data, k, 0, length - 1)\nend = self.get_last_k(data, k, 0, length - 1)\nif first != -1 and end != -1:\n return end - first + 1\nreturn 0",
"if start > end:\n return -1\nmid = start + (end - start) / 2\nif data[mid] > k:\n return... | <|body_start_0|>
length = len(data)
if length == 0:
return 0
first = self.get_first_k(data, k, 0, length - 1)
end = self.get_last_k(data, k, 0, length - 1)
if first != -1 and end != -1:
return end - first + 1
return 0
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def GetNumberOfK(self, data, k):
"""在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:"""
<|body_0|>
def get_first_k(self, data, k, start, end):
"""递归写法二分查找 :param data: :param k: :param start: :param end: :return:"""
<|... | stack_v2_sparse_classes_36k_train_009000 | 1,814 | no_license | [
{
"docstring": "在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:",
"name": "GetNumberOfK",
"signature": "def GetNumberOfK(self, data, k)"
},
{
"docstring": "递归写法二分查找 :param data: :param k: :param start: :param end: :return:",
"name": "get_first_k",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_001802 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def GetNumberOfK(self, data, k): 在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:
- def get_first_k(self, data, k, start, end): 递归写法二分查找 :param dat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def GetNumberOfK(self, data, k): 在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:
- def get_first_k(self, data, k, start, end): 递归写法二分查找 :param dat... | c756fe54e8e17e9ba0bfdab5fccc24ac89263d90 | <|skeleton|>
class Solution:
def GetNumberOfK(self, data, k):
"""在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:"""
<|body_0|>
def get_first_k(self, data, k, start, end):
"""递归写法二分查找 :param data: :param k: :param start: :param end: :return:"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def GetNumberOfK(self, data, k):
"""在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:"""
length = len(data)
if length == 0:
return 0
first = self.get_first_k(data, k, 0, length - 1)
end = self.get_last_k(data, k, 0, le... | the_stack_v2_python_sparse | newcoder_offer/get_number_of_K.py | EarthChen/LeetCode_Record | train | 0 | |
2fdd641c3d0a9d739289256755c8d9aca2bb94a0 | [
"if self._listeners is None:\n self._listeners = weakref.WeakValueDictionary()\nself._listeners[id(listener)] = listener",
"if self._listeners is None:\n return\nwith ignored(KeyError):\n del self._listeners[id(listener)]",
"if self._listeners is None:\n return\nmethod_name = '_update_{0}'.format(no... | <|body_start_0|>
if self._listeners is None:
self._listeners = weakref.WeakValueDictionary()
self._listeners[id(listener)] = listener
<|end_body_0|>
<|body_start_1|>
if self._listeners is None:
return
with ignored(KeyError):
del self._listeners[id(lis... | Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be exposed to users of the classes involved.... | NotifierMixin | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ... | stack_v2_sparse_classes_36k_train_009001 | 31,014 | permissive | [
{
"docstring": "Add an object to the list of listeners to notify of changes to this object. This adds a weakref to the list of listeners that is removed from the listeners list when the listener has no other references to it.",
"name": "_add_listener",
"signature": "def _add_listener(self, listener)"
... | 4 | null | Implement the Python class `NotifierMixin` described below.
Class description:
Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic wa... | Implement the Python class `NotifierMixin` described below.
Class description:
Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic wa... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be exposed to us... | the_stack_v2_python_sparse | pkgs/astropy-1.1.2-np110py27_0/lib/python2.7/site-packages/astropy/io/fits/util.py | wangyum/Anaconda | train | 11 |
90fefe51db7d6e3dfab78e5e507da34f4a091f02 | [
"self.physics_controller = physics_controller\nbumper_width = 3.25 * units.inch\nself.drivetrain = tankmodel.TankModel.theory(motor_cfgs.MOTOR_CFG_CIM, 110 * units.lbs, 7, 2, 22 * units.inch, 23 * units.inch + bumper_width * 2, 32 * units.inch + bumper_width * 2, 6 * units.inch)",
"lr_motor = hal_data['pwm'][1]['... | <|body_start_0|>
self.physics_controller = physics_controller
bumper_width = 3.25 * units.inch
self.drivetrain = tankmodel.TankModel.theory(motor_cfgs.MOTOR_CFG_CIM, 110 * units.lbs, 7, 2, 22 * units.inch, 23 * units.inch + bumper_width * 2, 32 * units.inch + bumper_width * 2, 6 * units.inch)
<|... | Simulates a 4-wheel robot using Tank Drive joystick control | PhysicsEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhysicsEngine:
"""Simulates a 4-wheel robot using Tank Drive joystick control"""
def __init__(self, physics_controller):
""":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to"""
<|body_0|>
def update_sim(self, hal_data, no... | stack_v2_sparse_classes_36k_train_009002 | 2,069 | permissive | [
{
"docstring": ":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to",
"name": "__init__",
"signature": "def __init__(self, physics_controller)"
},
{
"docstring": "Called when the simulation parameters for the program need to be updated. :param now:... | 2 | stack_v2_sparse_classes_30k_train_007788 | Implement the Python class `PhysicsEngine` described below.
Class description:
Simulates a 4-wheel robot using Tank Drive joystick control
Method signatures and docstrings:
- def __init__(self, physics_controller): :param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to
- d... | Implement the Python class `PhysicsEngine` described below.
Class description:
Simulates a 4-wheel robot using Tank Drive joystick control
Method signatures and docstrings:
- def __init__(self, physics_controller): :param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to
- d... | a6f002625c9326de6995bc52960f25f78e9b2843 | <|skeleton|>
class PhysicsEngine:
"""Simulates a 4-wheel robot using Tank Drive joystick control"""
def __init__(self, physics_controller):
""":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to"""
<|body_0|>
def update_sim(self, hal_data, no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhysicsEngine:
"""Simulates a 4-wheel robot using Tank Drive joystick control"""
def __init__(self, physics_controller):
""":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to"""
self.physics_controller = physics_controller
bumper_wi... | the_stack_v2_python_sparse | ButtonMadness/physics.py | RocketRedNeck/PythonPlayground | train | 1 |
96c3c8269a94c616ef28c297d27c495375792512 | [
"TestFunction.__init__(self)\nproblem_type = get_problem_type(dataset)\nassert problem_type in (ProblemType.clf, ProblemType.reg)\n_, _, self.api_config = MODELS_CLF[model] if problem_type == ProblemType.clf else MODELS_REG[model]\nself.space = JointSpace(self.api_config)\nfname = SklearnModel.test_case_str(model, ... | <|body_start_0|>
TestFunction.__init__(self)
problem_type = get_problem_type(dataset)
assert problem_type in (ProblemType.clf, ProblemType.reg)
_, _, self.api_config = MODELS_CLF[model] if problem_type == ProblemType.clf else MODELS_REG[model]
self.space = JointSpace(self.api_con... | Test class for sklearn classifier/regressor CV score objective function surrogates. | SklearnSurrogate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnSurrogate:
"""Test class for sklearn classifier/regressor CV score objective function surrogates."""
def __init__(self, model, dataset, scorer, path):
"""Build class that wraps sklearn classifier/regressor CV score for use as an objective function surrogate. Parameters -------... | stack_v2_sparse_classes_36k_train_009003 | 21,494 | permissive | [
{
"docstring": "Build class that wraps sklearn classifier/regressor CV score for use as an objective function surrogate. Parameters ---------- model : str Which classifier to use, must be key in `MODELS_CLF` or `MODELS_REG` dict depending on if dataset is classification or regression. dataset : str Which data s... | 2 | null | Implement the Python class `SklearnSurrogate` described below.
Class description:
Test class for sklearn classifier/regressor CV score objective function surrogates.
Method signatures and docstrings:
- def __init__(self, model, dataset, scorer, path): Build class that wraps sklearn classifier/regressor CV score for u... | Implement the Python class `SklearnSurrogate` described below.
Class description:
Test class for sklearn classifier/regressor CV score objective function surrogates.
Method signatures and docstrings:
- def __init__(self, model, dataset, scorer, path): Build class that wraps sklearn classifier/regressor CV score for u... | d1d51ae8df0780ffbb7f33b78dc388f58d130958 | <|skeleton|>
class SklearnSurrogate:
"""Test class for sklearn classifier/regressor CV score objective function surrogates."""
def __init__(self, model, dataset, scorer, path):
"""Build class that wraps sklearn classifier/regressor CV score for use as an objective function surrogate. Parameters -------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SklearnSurrogate:
"""Test class for sklearn classifier/regressor CV score objective function surrogates."""
def __init__(self, model, dataset, scorer, path):
"""Build class that wraps sklearn classifier/regressor CV score for use as an objective function surrogate. Parameters ---------- model : s... | the_stack_v2_python_sparse | bayesmark/sklearn_funcs.py | Neeratyoy/bayesmark | train | 0 |
b7de35712aced104adb988ce27bbd6fc05d50af0 | [
"super().__init__(*args, **kwargs)\nignore_fields = ('about_me', 'romanized_first_name', 'romanized_last_name', 'postal_code')\nset_fields_to_required(self, ignore_fields=ignore_fields)",
"if 'filled_out' in attrs and (not attrs['filled_out']):\n raise ValidationError('filled_out cannot be set to false')\nif '... | <|body_start_0|>
super().__init__(*args, **kwargs)
ignore_fields = ('about_me', 'romanized_first_name', 'romanized_last_name', 'postal_code')
set_fields_to_required(self, ignore_fields=ignore_fields)
<|end_body_0|>
<|body_start_1|>
if 'filled_out' in attrs and (not attrs['filled_out']):... | Serializer for Profile objects which require filled_out = True | ProfileFilledOutSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileFilledOutSerializer:
"""Serializer for Profile objects which require filled_out = True"""
def __init__(self, *args, **kwargs):
"""Update serializer_field_mapping to use fields setting required=True"""
<|body_0|>
def validate(self, attrs):
"""Assert that fi... | stack_v2_sparse_classes_36k_train_009004 | 9,928 | permissive | [
{
"docstring": "Update serializer_field_mapping to use fields setting required=True",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Assert that filled_out can't be turned off and that agreed_to_terms_of_service is true",
"name": "validate",
"si... | 2 | stack_v2_sparse_classes_30k_train_002443 | Implement the Python class `ProfileFilledOutSerializer` described below.
Class description:
Serializer for Profile objects which require filled_out = True
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Update serializer_field_mapping to use fields setting required=True
- def validate(self, a... | Implement the Python class `ProfileFilledOutSerializer` described below.
Class description:
Serializer for Profile objects which require filled_out = True
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Update serializer_field_mapping to use fields setting required=True
- def validate(self, a... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class ProfileFilledOutSerializer:
"""Serializer for Profile objects which require filled_out = True"""
def __init__(self, *args, **kwargs):
"""Update serializer_field_mapping to use fields setting required=True"""
<|body_0|>
def validate(self, attrs):
"""Assert that fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileFilledOutSerializer:
"""Serializer for Profile objects which require filled_out = True"""
def __init__(self, *args, **kwargs):
"""Update serializer_field_mapping to use fields setting required=True"""
super().__init__(*args, **kwargs)
ignore_fields = ('about_me', 'romanized... | the_stack_v2_python_sparse | profiles/serializers.py | mitodl/micromasters | train | 35 |
cefb21902a54cc524c3ac59c288ac71bfbb3a75b | [
"import collections\nself.userIDToTweet = collections.defaultdict(collections.deque)\nself.followerToFollowee = collections.defaultdict(set)\nself.tweetCount = 0",
"self.tweetCount += 1\nself.userIDToTweet[userId].appendleft((self.tweetCount, tweetId))\nwhile len(self.userIDToTweet[userId]) > 10:\n self.userID... | <|body_start_0|>
import collections
self.userIDToTweet = collections.defaultdict(collections.deque)
self.followerToFollowee = collections.defaultdict(set)
self.tweetCount = 0
<|end_body_0|>
<|body_start_1|>
self.tweetCount += 1
self.userIDToTweet[userId].appendleft((self... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k_train_009005 | 2,695 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. :type userId: int :type tweetId: int :rtype: void",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"... | 5 | null | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | e61776bcfd5d93c663b247d71e00f1b298683714 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
import collections
self.userIDToTweet = collections.defaultdict(collections.deque)
self.followerToFollowee = collections.defaultdict(set)
self.tweetCount = 0
def postTweet(self, userId, tweetId... | the_stack_v2_python_sparse | design_twitter/Twitter.py | Omega094/lc_practice | train | 0 | |
9649de1fa39eeba6ff22ee66fe7f8285b650c110 | [
"self._K_P = K_P\nself._K_D = K_D\nself._K_I = K_I\nself._e_buffer = deque(maxlen=10)\nself.error = 0.0\nself.error_integral = 0.0\nself.error_derivative = 0.0",
"v_begin = current_pose.position\nquaternion = (current_pose.orientation.w, current_pose.orientation.x, current_pose.orientation.y, current_pose.orienta... | <|body_start_0|>
self._K_P = K_P
self._K_D = K_D
self._K_I = K_I
self._e_buffer = deque(maxlen=10)
self.error = 0.0
self.error_integral = 0.0
self.error_derivative = 0.0
<|end_body_0|>
<|body_start_1|>
v_begin = current_pose.position
quaternion = ... | PIDLateralController implements lateral control using a PID. | PIDLateralController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIDLateralController:
"""PIDLateralController implements lateral control using a PID."""
def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0):
""":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differential term :param K_I: Integral term"... | stack_v2_sparse_classes_36k_train_009006 | 6,324 | permissive | [
{
"docstring": ":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differential term :param K_I: Integral term",
"name": "__init__",
"signature": "def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0)"
},
{
"docstring": "Estimate the steering angle of th... | 2 | stack_v2_sparse_classes_30k_train_000549 | Implement the Python class `PIDLateralController` described below.
Class description:
PIDLateralController implements lateral control using a PID.
Method signatures and docstrings:
- def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0): :param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term... | Implement the Python class `PIDLateralController` described below.
Class description:
PIDLateralController implements lateral control using a PID.
Method signatures and docstrings:
- def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0): :param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term... | e9063d97ff5a724f76adbb1b852dc71da1dcfeec | <|skeleton|>
class PIDLateralController:
"""PIDLateralController implements lateral control using a PID."""
def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0):
""":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differential term :param K_I: Integral term"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PIDLateralController:
"""PIDLateralController implements lateral control using a PID."""
def __init__(self, K_P=1.0, K_D=0.0, K_I=0.0):
""":param vehicle: actor to apply to local planner logic onto :param K_P: Proportional term :param K_D: Differential term :param K_I: Integral term"""
se... | the_stack_v2_python_sparse | carla_ad_agent/src/carla_ad_agent/vehicle_pid_controller.py | carla-simulator/ros-bridge | train | 448 |
f7d491e730c8392fb354a8858579bbc6398909a7 | [
"if len(nums) <= 1:\n return len(nums)\nstar = 0\nfor i in range(1, len(nums)):\n if nums[i] != nums[star]:\n star += 1\n nums[star] = nums[i]\nreturn star + 1",
"if not nums:\n return 0\nif len(nums) < 2:\n return 1\nlower = index = 0\nfast = 1\nwhile fast < len(nums):\n if nums[fast... | <|body_start_0|>
if len(nums) <= 1:
return len(nums)
star = 0
for i in range(1, len(nums)):
if nums[i] != nums[star]:
star += 1
nums[star] = nums[i]
return star + 1
<|end_body_0|>
<|body_start_1|>
if not nums:
r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def __removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rty... | stack_v2_sparse_classes_36k_train_009007 | 3,447 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "_removeDuplicates",
"signature": "def _removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "__removeDuplicates",
"signature": "def __removeDuplicates(self, nums)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_008479 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def __removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def __removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def __removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) <= 1:
return len(nums)
star = 0
for i in range(1, len(nums)):
if nums[i] != nums[star]:
star += 1
nums[star] = nums[i]
... | the_stack_v2_python_sparse | 26.remove-duplicates-from-sorted-array.py | windard/leeeeee | train | 0 | |
f89f6898a7a43e5844b18fda3a1ecdf6737bf5ad | [
"m = len(triangle)\ndp = [[float('inf')] * (len(triangle[i]) + 2) for i in range(m)]\ndp[0][1] = triangle[0][0]\nfor i in range(1, m):\n for j in range(1, len(triangle[i]) + 1):\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j - 1]\nreturn min(dp[-1])",
"size = len(triangle)\nfor i in ra... | <|body_start_0|>
m = len(triangle)
dp = [[float('inf')] * (len(triangle[i]) + 2) for i in range(m)]
dp[0][1] = triangle[0][0]
for i in range(1, m):
for j in range(1, len(triangle[i]) + 1):
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j - 1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
"""自顶向下 开大数组"""
<|body_0|>
def minimumTotal2(self, triangle: List[List[int]]) -> int:
"""自底向上 天秀"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(triangle)
dp = [[flo... | stack_v2_sparse_classes_36k_train_009008 | 1,171 | no_license | [
{
"docstring": "自顶向下 开大数组",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle: List[List[int]]) -> int"
},
{
"docstring": "自底向上 天秀",
"name": "minimumTotal2",
"signature": "def minimumTotal2(self, triangle: List[List[int]]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle: List[List[int]]) -> int: 自顶向下 开大数组
- def minimumTotal2(self, triangle: List[List[int]]) -> int: 自底向上 天秀 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle: List[List[int]]) -> int: 自顶向下 开大数组
- def minimumTotal2(self, triangle: List[List[int]]) -> int: 自底向上 天秀
<|skeleton|>
class Solution:
def mi... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
"""自顶向下 开大数组"""
<|body_0|>
def minimumTotal2(self, triangle: List[List[int]]) -> int:
"""自底向上 天秀"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
"""自顶向下 开大数组"""
m = len(triangle)
dp = [[float('inf')] * (len(triangle[i]) + 2) for i in range(m)]
dp[0][1] = triangle[0][0]
for i in range(1, m):
for j in range(1, len(triangle[i]) + 1):
... | the_stack_v2_python_sparse | 二刷+题解/中等/minimumTotal.py | 1oser5/LeetCode | train | 0 | |
967e54d85e510846849f361498527a3ba9d17e28 | [
"result = root.val\nwhile root:\n result = min((root.val, result), key=lambda x: abs(target - x))\n root = root.left if target < root.val else root.right\nreturn result",
"child = root.left if root.val > target else root.right\nif not child:\n return root.val\nchild_val = self.closestValue(child, target)... | <|body_start_0|>
result = root.val
while root:
result = min((root.val, result), key=lambda x: abs(target - x))
root = root.left if target < root.val else root.right
return result
<|end_body_0|>
<|body_start_1|>
child = root.left if root.val > target else root.rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_0|>
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_009009 | 947 | no_license | [
{
"docstring": ":type root: TreeNode :type target: float :rtype: int",
"name": "closestValue",
"signature": "def closestValue(self, root, target)"
},
{
"docstring": ":type root: TreeNode :type target: float :rtype: int",
"name": "closestValue",
"signature": "def closestValue(self, root, ... | 2 | stack_v2_sparse_classes_30k_train_008510 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype: int
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype: int
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype... | 9513e215d40145a5f2f40095b459693c79c4b560 | <|skeleton|>
class Solution:
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_0|>
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
result = root.val
while root:
result = min((root.val, result), key=lambda x: abs(target - x))
root = root.left if target < root.val else root.right
... | the_stack_v2_python_sparse | 270.py | huangyingw/Leetcode-Python | train | 1 | |
895caaa0d40b4a75e0672c736457e7aff78cedff | [
"Parametre.__init__(self, 'liste', 'list')\nself.aide_courte = 'affiche la liste des modules chargés'\nself.aide_longue = \"Affiche la liste des modules actuellement chargés et un petit descriptif sur chacun. Si vous déchargez un module, il n'apparaîtra plus dans cette liste.\"",
"modules = type(self).importeur.m... | <|body_start_0|>
Parametre.__init__(self, 'liste', 'list')
self.aide_courte = 'affiche la liste des modules chargés'
self.aide_longue = "Affiche la liste des modules actuellement chargés et un petit descriptif sur chacun. Si vous déchargez un module, il n'apparaîtra plus dans cette liste."
<|end... | Commande 'module liste'. | PrmListe | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmListe:
"""Commande 'module liste'."""
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.__in... | stack_v2_sparse_classes_36k_train_009010 | 2,930 | 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 | null | Implement the Python class `PrmListe` described below.
Class description:
Commande 'module liste'.
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 `PrmListe` described below.
Class description:
Commande 'module liste'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmListe:
"""Commande 'module liste... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmListe:
"""Commande 'module liste'."""
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 PrmListe:
"""Commande 'module liste'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'liste', 'list')
self.aide_courte = 'affiche la liste des modules chargés'
self.aide_longue = "Affiche la liste des modules actuellement chargés et un peti... | the_stack_v2_python_sparse | src/primaires/joueur/commandes/module/liste.py | vincent-lg/tsunami | train | 5 |
0b0b05d98513cba036357a1f8a10a764d96b92b5 | [
"frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_alex_v0.1_27.pb', 'vgg_lin': 'net-lin_vgg_v0.1_27.pb', 'vgg': 'net_vgg_v0.1_27.pb'}\nfrozen_graph_path = osp.join(frozen_graphs_parent_dir, frozen_graph_name[net])\ninputs = ['0:0', '1:0']\noutputs = {'alex_lin': 'Reshape_10:0', 'alex': 'Add_... | <|body_start_0|>
frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_alex_v0.1_27.pb', 'vgg_lin': 'net-lin_vgg_v0.1_27.pb', 'vgg': 'net_vgg_v0.1_27.pb'}
frozen_graph_path = osp.join(frozen_graphs_parent_dir, frozen_graph_name[net])
inputs = ['0:0', '1:0']
outputs = {... | LPIPS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
<|body_0|>
def __call__(self, x, y, axis=None):
"... | stack_v2_sparse_classes_36k_train_009011 | 7,391 | permissive | [
{
"docstring": "Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips",
"name": "__init__",
"signature": "def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips')"
},
{
"docstring": "Computes LPIPS loss ... | 2 | stack_v2_sparse_classes_30k_train_004864 | Implement the Python class `LPIPS` described below.
Class description:
Implement the LPIPS class.
Method signatures and docstrings:
- def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'): Frozen graphs can be downloaded from the following link: http://rail.eecs.berke... | Implement the Python class `LPIPS` described below.
Class description:
Implement the LPIPS class.
Method signatures and docstrings:
- def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'): Frozen graphs can be downloaded from the following link: http://rail.eecs.berke... | a9a6643968a7b6b29cab3b53b73ab80d14fb32b7 | <|skeleton|>
class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
<|body_0|>
def __call__(self, x, y, axis=None):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_ale... | the_stack_v2_python_sparse | losses/losses.py | czero69/lsr | train | 0 | |
353f608b3493e4366dda502c85da12cfa360637c | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing PostgreSQL Database resources. | DatabaseServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseServiceServicer:
"""A set of methods for managing PostgreSQL Database resources."""
def Get(self, request, context):
"""Returns the specified PostgreSQL Database resource. To get the list of available PostgreSQL Database resources, make a [List] request."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_009012 | 10,680 | permissive | [
{
"docstring": "Returns the specified PostgreSQL Database resource. To get the list of available PostgreSQL Database resources, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of PostgreSQL Database resources in the spe... | 5 | null | Implement the Python class `DatabaseServiceServicer` described below.
Class description:
A set of methods for managing PostgreSQL Database resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified PostgreSQL Database resource. To get the list of available PostgreSQL Databas... | Implement the Python class `DatabaseServiceServicer` described below.
Class description:
A set of methods for managing PostgreSQL Database resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified PostgreSQL Database resource. To get the list of available PostgreSQL Databas... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class DatabaseServiceServicer:
"""A set of methods for managing PostgreSQL Database resources."""
def Get(self, request, context):
"""Returns the specified PostgreSQL Database resource. To get the list of available PostgreSQL Database resources, make a [List] request."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseServiceServicer:
"""A set of methods for managing PostgreSQL Database resources."""
def Get(self, request, context):
"""Returns the specified PostgreSQL Database resource. To get the list of available PostgreSQL Database resources, make a [List] request."""
context.set_code(grpc.S... | the_stack_v2_python_sparse | yandex/cloud/mdb/postgresql/v1/database_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
6de6495f5d64be3fd6c6c388574d69e1ab0249da | [
"super(BPTTUpdater, self).__init__(train_iter, optimizer)\nself.model = model\nself.device = device\nself.gradclip = gradclip\nself.use_apex = use_apex\nself.scheduler = PyTorchScheduler(schedulers, optimizer)\nself.accum_grad = accum_grad",
"train_iter = self.get_iterator('main')\noptimizer = self.get_optimizer(... | <|body_start_0|>
super(BPTTUpdater, self).__init__(train_iter, optimizer)
self.model = model
self.device = device
self.gradclip = gradclip
self.use_apex = use_apex
self.scheduler = PyTorchScheduler(schedulers, optimizer)
self.accum_grad = accum_grad
<|end_body_0|>... | An updater for a pytorch LM. | BPTTUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BPTTUpdater:
"""An updater for a pytorch LM."""
def __init__(self, train_iter, model, optimizer, schedulers, device, gradclip=None, use_apex=False, accum_grad=1):
"""Initialize class. Args: train_iter (chainer.dataset.Iterator): The train iterator model (LMInterface) : The model to u... | stack_v2_sparse_classes_36k_train_009013 | 14,856 | permissive | [
{
"docstring": "Initialize class. Args: train_iter (chainer.dataset.Iterator): The train iterator model (LMInterface) : The model to update optimizer (torch.optim.Optimizer): The optimizer for training schedulers (espnet.scheduler.scheduler.SchedulerInterface): The schedulers of `optimizer` device (int): The de... | 2 | null | Implement the Python class `BPTTUpdater` described below.
Class description:
An updater for a pytorch LM.
Method signatures and docstrings:
- def __init__(self, train_iter, model, optimizer, schedulers, device, gradclip=None, use_apex=False, accum_grad=1): Initialize class. Args: train_iter (chainer.dataset.Iterator)... | Implement the Python class `BPTTUpdater` described below.
Class description:
An updater for a pytorch LM.
Method signatures and docstrings:
- def __init__(self, train_iter, model, optimizer, schedulers, device, gradclip=None, use_apex=False, accum_grad=1): Initialize class. Args: train_iter (chainer.dataset.Iterator)... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class BPTTUpdater:
"""An updater for a pytorch LM."""
def __init__(self, train_iter, model, optimizer, schedulers, device, gradclip=None, use_apex=False, accum_grad=1):
"""Initialize class. Args: train_iter (chainer.dataset.Iterator): The train iterator model (LMInterface) : The model to u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BPTTUpdater:
"""An updater for a pytorch LM."""
def __init__(self, train_iter, model, optimizer, schedulers, device, gradclip=None, use_apex=False, accum_grad=1):
"""Initialize class. Args: train_iter (chainer.dataset.Iterator): The train iterator model (LMInterface) : The model to update optimiz... | the_stack_v2_python_sparse | espnet/lm/pytorch_backend/lm.py | espnet/espnet | train | 7,242 |
3b48e2938beccf2a2930ac0550b87b493c85f270 | [
"stack = []\nres = 0\nn = len(nums)\nfor i in range(n):\n while stack and stack[-1][1] > nums[i]:\n res += i - stack.pop()[0]\n stack.append([i, nums[i]])\nwhile stack:\n res += n - stack.pop()[0]\nreturn res",
"n = len(nums)\nres = n\nfor i in range(n - 1):\n for j in range(i + 1, n):\n ... | <|body_start_0|>
stack = []
res = 0
n = len(nums)
for i in range(n):
while stack and stack[-1][1] > nums[i]:
res += i - stack.pop()[0]
stack.append([i, nums[i]])
while stack:
res += n - stack.pop()[0]
return res
<|end_bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validSubarrays(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def validSubarrays2(self, nums):
"""超时 :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = []
res = 0
... | stack_v2_sparse_classes_36k_train_009014 | 1,772 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "validSubarrays",
"signature": "def validSubarrays(self, nums)"
},
{
"docstring": "超时 :type nums: List[int] :rtype: int",
"name": "validSubarrays2",
"signature": "def validSubarrays2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validSubarrays(self, nums): :type nums: List[int] :rtype: int
- def validSubarrays2(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 validSubarrays(self, nums): :type nums: List[int] :rtype: int
- def validSubarrays2(self, nums): 超时 :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def v... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def validSubarrays(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def validSubarrays2(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 validSubarrays(self, nums):
""":type nums: List[int] :rtype: int"""
stack = []
res = 0
n = len(nums)
for i in range(n):
while stack and stack[-1][1] > nums[i]:
res += i - stack.pop()[0]
stack.append([i, nums[i]])
... | the_stack_v2_python_sparse | contest/全国高校春季编程大赛/决赛/4_有效子数组的数目.py | lovehhf/LeetCode | train | 0 | |
91f0b1ad868614320f65d62713e4db67ec6b3fda | [
"self.structure = structure\nself.include_bv_charge = include_bv_charge\nsga = SpacegroupAnalyzer(self.structure)\nself.symm_structure = sga.get_symmetrized_structure()\nself.equiv_site_seq = list(self.symm_structure.equivalent_sites)\nself.struct_valences = None\nif self.include_bv_charge:\n bv = BVAnalyzer()\n... | <|body_start_0|>
self.structure = structure
self.include_bv_charge = include_bv_charge
sga = SpacegroupAnalyzer(self.structure)
self.symm_structure = sga.get_symmetrized_structure()
self.equiv_site_seq = list(self.symm_structure.equivalent_sites)
self.struct_valences = No... | Simple generator for vacancies based on periodically equivalent sites | VacancyGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VacancyGenerator:
"""Simple generator for vacancies based on periodically equivalent sites"""
def __init__(self, structure, include_bv_charge=False):
"""Initializes a Vacancy Generator Args: structure(Structure): pymatgen structure object"""
<|body_0|>
def __next__(self)... | stack_v2_sparse_classes_36k_train_009015 | 10,935 | permissive | [
{
"docstring": "Initializes a Vacancy Generator Args: structure(Structure): pymatgen structure object",
"name": "__init__",
"signature": "def __init__(self, structure, include_bv_charge=False)"
},
{
"docstring": "Returns the next vacancy in the sequence or raises StopIteration",
"name": "__n... | 2 | stack_v2_sparse_classes_30k_train_013466 | Implement the Python class `VacancyGenerator` described below.
Class description:
Simple generator for vacancies based on periodically equivalent sites
Method signatures and docstrings:
- def __init__(self, structure, include_bv_charge=False): Initializes a Vacancy Generator Args: structure(Structure): pymatgen struc... | Implement the Python class `VacancyGenerator` described below.
Class description:
Simple generator for vacancies based on periodically equivalent sites
Method signatures and docstrings:
- def __init__(self, structure, include_bv_charge=False): Initializes a Vacancy Generator Args: structure(Structure): pymatgen struc... | 62ecae1c7382a41861e3a5d9b9c8dd1207472409 | <|skeleton|>
class VacancyGenerator:
"""Simple generator for vacancies based on periodically equivalent sites"""
def __init__(self, structure, include_bv_charge=False):
"""Initializes a Vacancy Generator Args: structure(Structure): pymatgen structure object"""
<|body_0|>
def __next__(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VacancyGenerator:
"""Simple generator for vacancies based on periodically equivalent sites"""
def __init__(self, structure, include_bv_charge=False):
"""Initializes a Vacancy Generator Args: structure(Structure): pymatgen structure object"""
self.structure = structure
self.include... | the_stack_v2_python_sparse | pymatgen/analysis/defects/generators.py | montoyjh/pymatgen | train | 2 |
8dc5e9bb5ba448a18a48ebd9823108b5c8aeaca4 | [
"this_module = sys.modules[__name__]\nresult = {}\nfor key in dir(this_module):\n if key.startswith('_'):\n continue\n o = getattr(this_module, key)\n if isinstance(o, type) and o is not cls and issubclass(o, cls):\n result[o.__name__] = o\nreturn result",
"if isinstance(blocker, cls):\n ... | <|body_start_0|>
this_module = sys.modules[__name__]
result = {}
for key in dir(this_module):
if key.startswith('_'):
continue
o = getattr(this_module, key)
if isinstance(o, type) and o is not cls and issubclass(o, cls):
result[... | Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, ``self.__dict__["kwargs"] = kwargs`` must be done! Failing to do this will render some of the functionality disabled ;). | Blocker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blocker:
"""Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, ``self.__dict__["kwargs"] = kwargs`` must be done! Failing to do this will render some of the functionality disabled ;)."""
... | stack_v2_sparse_classes_36k_train_009016 | 6,471 | no_license | [
{
"docstring": "Return mapping of name:class of all the blocker engines in this module. Having this as a separate function will later enable to scatter the engines across modules in case of extraction into a separate library.",
"name": "all_blocker_engines",
"signature": "def all_blocker_engines(cls)"
... | 2 | null | Implement the Python class `Blocker` described below.
Class description:
Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, ``self.__dict__["kwargs"] = kwargs`` must be done! Failing to do this will render some of... | Implement the Python class `Blocker` described below.
Class description:
Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, ``self.__dict__["kwargs"] = kwargs`` must be done! Failing to do this will render some of... | 73b3e1b0717b5cb0449157dc5d85e89820b62c57 | <|skeleton|>
class Blocker:
"""Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, ``self.__dict__["kwargs"] = kwargs`` must be done! Failing to do this will render some of the functionality disabled ;)."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Blocker:
"""Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, ``self.__dict__["kwargs"] = kwargs`` must be done! Failing to do this will render some of the functionality disabled ;)."""
def all_bloc... | the_stack_v2_python_sparse | utils/blockers.py | richardfontana/cfme_tests | train | 0 |
a6fe4fceaeacd915c9e40ab1af13fc6f0518e332 | [
"wx.PopupWindow.__init__(self, parent)\nPopupListBase.__init__(self)\nself._list = wx.ListBox(self, choices=choices, pos=(0, 0), style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER)\nsizer = wx.BoxSizer(wx.HORIZONTAL)\nsizer.Add(self._list, 0, wx.EXPAND)\nself.SetSizer(sizer)\ntxt_h = self.GetTextExtent('/')[1]... | <|body_start_0|>
wx.PopupWindow.__init__(self, parent)
PopupListBase.__init__(self)
self._list = wx.ListBox(self, choices=choices, pos=(0, 0), style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self._list, 0, wx.EXPAND)
s... | Popuplist for Windows/GTK | PopupWinList | [
"BSD-3-Clause",
"LicenseRef-scancode-python-cwi",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Python-2.0",
"LGPL-2.0-or-later",
"WxWindows-exception-3.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopupWinList:
"""Popuplist for Windows/GTK"""
def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
"""Create the popup window and its list control"""
<|body_0|>
def OnSize(self, evt):
"""Resize the list box to the correct size to fit."""
<|... | stack_v2_sparse_classes_36k_train_009017 | 44,291 | permissive | [
{
"docstring": "Create the popup window and its list control",
"name": "__init__",
"signature": "def __init__(self, parent, choices=list(), pos=wx.DefaultPosition)"
},
{
"docstring": "Resize the list box to the correct size to fit.",
"name": "OnSize",
"signature": "def OnSize(self, evt)"... | 5 | stack_v2_sparse_classes_30k_train_002152 | Implement the Python class `PopupWinList` described below.
Class description:
Popuplist for Windows/GTK
Method signatures and docstrings:
- def __init__(self, parent, choices=list(), pos=wx.DefaultPosition): Create the popup window and its list control
- def OnSize(self, evt): Resize the list box to the correct size ... | Implement the Python class `PopupWinList` described below.
Class description:
Popuplist for Windows/GTK
Method signatures and docstrings:
- def __init__(self, parent, choices=list(), pos=wx.DefaultPosition): Create the popup window and its list control
- def OnSize(self, evt): Resize the list box to the correct size ... | 77d66c719b5746f37af51ad593e2941ed6fbba17 | <|skeleton|>
class PopupWinList:
"""Popuplist for Windows/GTK"""
def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
"""Create the popup window and its list control"""
<|body_0|>
def OnSize(self, evt):
"""Resize the list box to the correct size to fit."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PopupWinList:
"""Popuplist for Windows/GTK"""
def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
"""Create the popup window and its list control"""
wx.PopupWindow.__init__(self, parent)
PopupListBase.__init__(self)
self._list = wx.ListBox(self, choices=cho... | the_stack_v2_python_sparse | base/lib/python2.7/site-packages/wx-3.0-gtk2/wx/tools/Editra/src/ed_cmdbar.py | jorgediazjr/dials-dev20191018 | train | 0 |
8f9c390c5648cab114bb016c6e322e21d6bbc6b8 | [
"user = UserModel.objects.create_user(username='saimer')\nself.assertEqual(user.email, '')\nself.assertEqual(user.username, 'saimer')\nself.assertFalse(user.has_usable_password())",
"self.test_user_creation()\nwith self.assertRaisesMessage(IntegrityError, 'UNIQUE constraint failed: auths_user.username'):\n Use... | <|body_start_0|>
user = UserModel.objects.create_user(username='saimer')
self.assertEqual(user.email, '')
self.assertEqual(user.username, 'saimer')
self.assertFalse(user.has_usable_password())
<|end_body_0|>
<|body_start_1|>
self.test_user_creation()
with self.assertRais... | Test case to create user. | UserCreationTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationTestCase:
"""Test case to create user."""
def test_user_creation(self):
"""Testing to create a user. Expected result: - User created successfully"""
<|body_0|>
def test_user_recreate(self):
"""Testing to re-create same user. Expected result: - Raise e... | stack_v2_sparse_classes_36k_train_009018 | 1,526 | no_license | [
{
"docstring": "Testing to create a user. Expected result: - User created successfully",
"name": "test_user_creation",
"signature": "def test_user_creation(self)"
},
{
"docstring": "Testing to re-create same user. Expected result: - Raise exception IntegrityError",
"name": "test_user_recreat... | 3 | stack_v2_sparse_classes_30k_train_015825 | Implement the Python class `UserCreationTestCase` described below.
Class description:
Test case to create user.
Method signatures and docstrings:
- def test_user_creation(self): Testing to create a user. Expected result: - User created successfully
- def test_user_recreate(self): Testing to re-create same user. Expec... | Implement the Python class `UserCreationTestCase` described below.
Class description:
Test case to create user.
Method signatures and docstrings:
- def test_user_creation(self): Testing to create a user. Expected result: - User created successfully
- def test_user_recreate(self): Testing to re-create same user. Expec... | 7312cf04599fbc3575764b8d14fa88353a6d0baa | <|skeleton|>
class UserCreationTestCase:
"""Test case to create user."""
def test_user_creation(self):
"""Testing to create a user. Expected result: - User created successfully"""
<|body_0|>
def test_user_recreate(self):
"""Testing to re-create same user. Expected result: - Raise e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreationTestCase:
"""Test case to create user."""
def test_user_creation(self):
"""Testing to create a user. Expected result: - User created successfully"""
user = UserModel.objects.create_user(username='saimer')
self.assertEqual(user.email, '')
self.assertEqual(user.u... | the_stack_v2_python_sparse | src/auths/tests.py | saimer/core | train | 0 |
b362a0e417f7b65a00ffe0a5e38b4348bd9e75fc | [
"super(ConvolutionalBoxPredictor, self).__init__(is_training, num_classes, freeze_batchnorm=freeze_batchnorm, inplace_batchnorm_update=inplace_batchnorm_update, name=name)\nif min_depth > max_depth:\n raise ValueError('min_depth should be less than or equal to max_depth')\nif len(box_prediction_heads) != len(cla... | <|body_start_0|>
super(ConvolutionalBoxPredictor, self).__init__(is_training, num_classes, freeze_batchnorm=freeze_batchnorm, inplace_batchnorm_update=inplace_batchnorm_update, name=name)
if min_depth > max_depth:
raise ValueError('min_depth should be less than or equal to max_depth')
... | Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across classes --- that is each anchor makes box predictions w... | ConvolutionalBoxPredictor | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalBoxPredictor:
"""Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across cl... | stack_v2_sparse_classes_36k_train_009019 | 21,160 | permissive | [
{
"docstring": "Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned ... | 3 | null | Implement the Python class `ConvolutionalBoxPredictor` described below.
Class description:
Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes ... | Implement the Python class `ConvolutionalBoxPredictor` described below.
Class description:
Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes ... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class ConvolutionalBoxPredictor:
"""Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvolutionalBoxPredictor:
"""Convolutional Keras Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across classes --- tha... | the_stack_v2_python_sparse | models/research/object_detection/predictors/convolutional_keras_box_predictor.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
9b724d89b3bcc9be48eb4f6ccefcee798916df85 | [
"lo = sl.bisect_left(rate)\nhi = len(sl) - lo\nreturn (lo, hi)",
"teams = 0\nleft = SortedList()\nright = SortedList(rating)\nfor rate in rating:\n right.remove(rate)\n loL, hiL = self.get_high_low(left, rate)\n loR, hiR = self.get_high_low(right, rate)\n teams += loL * hiR + loR * hiL\n left.add(r... | <|body_start_0|>
lo = sl.bisect_left(rate)
hi = len(sl) - lo
return (lo, hi)
<|end_body_0|>
<|body_start_1|>
teams = 0
left = SortedList()
right = SortedList(rating)
for rate in rating:
right.remove(rate)
loL, hiL = self.get_high_low(left,... | Soldiers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Soldiers:
def get_high_low(self, sl, rate):
""":param ls: :param s: :return:"""
<|body_0|>
def team_numbers_(self, rating: List[int]) -> int:
"""Approach: Using SortedList Time Complexity: O(N) Space Complexity: O(N) :param rating: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_009020 | 1,814 | no_license | [
{
"docstring": ":param ls: :param s: :return:",
"name": "get_high_low",
"signature": "def get_high_low(self, sl, rate)"
},
{
"docstring": "Approach: Using SortedList Time Complexity: O(N) Space Complexity: O(N) :param rating: :return:",
"name": "team_numbers_",
"signature": "def team_num... | 3 | stack_v2_sparse_classes_30k_train_017802 | Implement the Python class `Soldiers` described below.
Class description:
Implement the Soldiers class.
Method signatures and docstrings:
- def get_high_low(self, sl, rate): :param ls: :param s: :return:
- def team_numbers_(self, rating: List[int]) -> int: Approach: Using SortedList Time Complexity: O(N) Space Comple... | Implement the Python class `Soldiers` described below.
Class description:
Implement the Soldiers class.
Method signatures and docstrings:
- def get_high_low(self, sl, rate): :param ls: :param s: :return:
- def team_numbers_(self, rating: List[int]) -> int: Approach: Using SortedList Time Complexity: O(N) Space Comple... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Soldiers:
def get_high_low(self, sl, rate):
""":param ls: :param s: :return:"""
<|body_0|>
def team_numbers_(self, rating: List[int]) -> int:
"""Approach: Using SortedList Time Complexity: O(N) Space Complexity: O(N) :param rating: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Soldiers:
def get_high_low(self, sl, rate):
""":param ls: :param s: :return:"""
lo = sl.bisect_left(rate)
hi = len(sl) - lo
return (lo, hi)
def team_numbers_(self, rating: List[int]) -> int:
"""Approach: Using SortedList Time Complexity: O(N) Space Complexity: O(N)... | the_stack_v2_python_sparse | revisited_2021/arrays/count_number_of_teams.py | Shiv2157k/leet_code | train | 1 | |
0e75294380d0bc2bb9663169123bb09648ec7a93 | [
"context = {}\ncontext['form'] = ItemForm()\nreturn render(self.request, self.template_name, context)",
"form = ItemForm(self.request.POST)\nif form.is_valid():\n item = form.save(commit=False)\n item.owner = self.request.user\n item.company = self.request.user.company\n item.save()\n messages.succ... | <|body_start_0|>
context = {}
context['form'] = ItemForm()
return render(self.request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
form = ItemForm(self.request.POST)
if form.is_valid():
item = form.save(commit=False)
item.owner = self.req... | Adding invoice | ItemAddView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemAddView:
"""Adding invoice"""
def get(self, *args, **kwargs):
"""Display invoice form"""
<|body_0|>
def post(self, *args, **kwargs):
"""Get filled invoice form and create"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context = {}
c... | stack_v2_sparse_classes_36k_train_009021 | 4,064 | no_license | [
{
"docstring": "Display invoice form",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Get filled invoice form and create",
"name": "post",
"signature": "def post(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006809 | Implement the Python class `ItemAddView` described below.
Class description:
Adding invoice
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display invoice form
- def post(self, *args, **kwargs): Get filled invoice form and create | Implement the Python class `ItemAddView` described below.
Class description:
Adding invoice
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display invoice form
- def post(self, *args, **kwargs): Get filled invoice form and create
<|skeleton|>
class ItemAddView:
"""Adding invoice"""
def ... | 17615ea9bfb1edebe41d60dbf2e977f0018d5339 | <|skeleton|>
class ItemAddView:
"""Adding invoice"""
def get(self, *args, **kwargs):
"""Display invoice form"""
<|body_0|>
def post(self, *args, **kwargs):
"""Get filled invoice form and create"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemAddView:
"""Adding invoice"""
def get(self, *args, **kwargs):
"""Display invoice form"""
context = {}
context['form'] = ItemForm()
return render(self.request, self.template_name, context)
def post(self, *args, **kwargs):
"""Get filled invoice form and crea... | the_stack_v2_python_sparse | items/views.py | Swiftkind/invoice | train | 0 |
73045ec8d70163c4fbe1b4da631c9cd239dfab37 | [
"if os.path.isdir(episode_directory):\n self.episode_directory = episode_directory\n info_path = os.path.join(self.episode_directory, 'info.json')\n with open(info_path, 'r') as json_file:\n info_dict = json.load(json_file)\n self.max_episode_index = info_dict['max_episode_index']\n se... | <|body_start_0|>
if os.path.isdir(episode_directory):
self.episode_directory = episode_directory
info_path = os.path.join(self.episode_directory, 'info.json')
with open(info_path, 'r') as json_file:
info_dict = json.load(json_file)
self.max_epi... | DataLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLoader:
def __init__(self, episode_directory):
""":param episode_directory:"""
<|body_0|>
def get_episodes(self, indices):
""":param indices: :return:"""
<|body_1|>
def get_episode(self, index):
""":param index: :return:"""
<|body_2|>... | stack_v2_sparse_classes_36k_train_009022 | 1,895 | permissive | [
{
"docstring": ":param episode_directory:",
"name": "__init__",
"signature": "def __init__(self, episode_directory)"
},
{
"docstring": ":param indices: :return:",
"name": "get_episodes",
"signature": "def get_episodes(self, indices)"
},
{
"docstring": ":param index: :return:",
... | 3 | null | Implement the Python class `DataLoader` described below.
Class description:
Implement the DataLoader class.
Method signatures and docstrings:
- def __init__(self, episode_directory): :param episode_directory:
- def get_episodes(self, indices): :param indices: :return:
- def get_episode(self, index): :param index: :re... | Implement the Python class `DataLoader` described below.
Class description:
Implement the DataLoader class.
Method signatures and docstrings:
- def __init__(self, episode_directory): :param episode_directory:
- def get_episodes(self, indices): :param indices: :return:
- def get_episode(self, index): :param index: :re... | 4c0ac37e559daa0dd89668e5bff5eec82a4158c5 | <|skeleton|>
class DataLoader:
def __init__(self, episode_directory):
""":param episode_directory:"""
<|body_0|>
def get_episodes(self, indices):
""":param indices: :return:"""
<|body_1|>
def get_episode(self, index):
""":param index: :return:"""
<|body_2|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataLoader:
def __init__(self, episode_directory):
""":param episode_directory:"""
if os.path.isdir(episode_directory):
self.episode_directory = episode_directory
info_path = os.path.join(self.episode_directory, 'info.json')
with open(info_path, 'r') as json... | the_stack_v2_python_sparse | Trifinger/causal_world/loggers/data_loader.py | emigmo/BenTDM | train | 0 | |
98dd2e765fe136b119e68884ec8c9091608a5676 | [
"if not root:\n return 0\nstack = []\nstack.append(root)\nleft = None\nwhile stack:\n nz = len(stack)\n for i in range(nz):\n cur = stack.pop(0)\n if i == 0:\n left = cur.val\n if cur.left:\n stack.append(cur.left)\n if cur.right:\n stack.append(... | <|body_start_0|>
if not root:
return 0
stack = []
stack.append(root)
left = None
while stack:
nz = len(stack)
for i in range(nz):
cur = stack.pop(0)
if i == 0:
left = cur.val
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findBottomLeftValue1(self, root):
""":type root: TreeNode :rtype: int 层次遍历"""
<|body_0|>
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int 递归"""
<|body_1|>
def findBottomLeftValue2(self, root):
""":type root: ... | stack_v2_sparse_classes_36k_train_009023 | 2,235 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int 层次遍历",
"name": "findBottomLeftValue1",
"signature": "def findBottomLeftValue1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int 递归",
"name": "findBottomLeftValue",
"signature": "def findBottomLeftValue(self, root)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue1(self, root): :type root: TreeNode :rtype: int 层次遍历
- def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int 递归
- def findBottomLeftValue2(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue1(self, root): :type root: TreeNode :rtype: int 层次遍历
- def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int 递归
- def findBottomLeftValue2(... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def findBottomLeftValue1(self, root):
""":type root: TreeNode :rtype: int 层次遍历"""
<|body_0|>
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int 递归"""
<|body_1|>
def findBottomLeftValue2(self, root):
""":type root: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findBottomLeftValue1(self, root):
""":type root: TreeNode :rtype: int 层次遍历"""
if not root:
return 0
stack = []
stack.append(root)
left = None
while stack:
nz = len(stack)
for i in range(nz):
cur =... | the_stack_v2_python_sparse | out/production/leetcode/513.找树左下角的值.py | yangyuxiang1996/leetcode | train | 0 | |
91a3945e0a5c64e742044561e604036f4a408ea6 | [
"max_sum = nums[0]\nmax_sub_sum = nums[0]\nfor i in range(1, len(nums)):\n max_sub_sum = max(nums[i], max_sub_sum + nums[i])\n max_sum = max(max_sub_sum, max_sum)\nreturn max_sum",
"max_sum = nums[0]\nfor i in range(len(nums)):\n sub_sum = 0\n for j in range(len(nums) - i):\n sub_sum += nums[i ... | <|body_start_0|>
max_sum = nums[0]
max_sub_sum = nums[0]
for i in range(1, len(nums)):
max_sub_sum = max(nums[i], max_sub_sum + nums[i])
max_sum = max(max_sub_sum, max_sum)
return max_sum
<|end_body_0|>
<|body_start_1|>
max_sum = nums[0]
for i in ... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums):
"""dynamical programming, O(n)"""
<|body_0|>
def maxSubArray2(self, nums):
"""brutal solution, bad"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_sum = nums[0]
max_sub_sum = nums[0]
for i ... | stack_v2_sparse_classes_36k_train_009024 | 1,076 | permissive | [
{
"docstring": "dynamical programming, O(n)",
"name": "maxSubArray1",
"signature": "def maxSubArray1(self, nums)"
},
{
"docstring": "brutal solution, bad",
"name": "maxSubArray2",
"signature": "def maxSubArray2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014750 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums): dynamical programming, O(n)
- def maxSubArray2(self, nums): brutal solution, bad | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums): dynamical programming, O(n)
- def maxSubArray2(self, nums): brutal solution, bad
<|skeleton|>
class Solution:
def maxSubArray1(self, nums):
... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def maxSubArray1(self, nums):
"""dynamical programming, O(n)"""
<|body_0|>
def maxSubArray2(self, nums):
"""brutal solution, bad"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray1(self, nums):
"""dynamical programming, O(n)"""
max_sum = nums[0]
max_sub_sum = nums[0]
for i in range(1, len(nums)):
max_sub_sum = max(nums[i], max_sub_sum + nums[i])
max_sum = max(max_sub_sum, max_sum)
return max_sum
... | the_stack_v2_python_sparse | leetcode/0053_maximum_subarray.py | chaosWsF/Python-Practice | train | 1 | |
31dfcf427f787e3515a0463d7bcb65ce26fe0022 | [
"intervals = [[intervals[e].start, intervals[e].end] for e in range(len(intervals))]\nintervals.sort()\ni = 1\nwhile i < len(intervals):\n if intervals[i][0] <= intervals[i - 1][1] <= intervals[i][1]:\n intervals[i - 1][1] = intervals[i][1]\n del intervals[i]\n elif intervals[i - 1][1] > interva... | <|body_start_0|>
intervals = [[intervals[e].start, intervals[e].end] for e in range(len(intervals))]
intervals.sort()
i = 1
while i < len(intervals):
if intervals[i][0] <= intervals[i - 1][1] <= intervals[i][1]:
intervals[i - 1][1] = intervals[i][1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
inte... | stack_v2_sparse_classes_36k_train_009025 | 1,727 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge",
"signature": "def merge(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge1",
"signature": "def merge1(self, intervals)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
<|skelet... | f234bd7b62cb7bc2150faa764bf05a9095e19192 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
intervals = [[intervals[e].start, intervals[e].end] for e in range(len(intervals))]
intervals.sort()
i = 1
while i < len(intervals):
if intervals[i][0] <= inte... | the_stack_v2_python_sparse | alg/merge_intervals.py | nyannko/leetcode-python | train | 0 | |
be47df01d2c723aaa4185ab7e41c1edc2f3d06e5 | [
"self._logger = logging.getLogger(__name__)\nif platform.system() == 'Darwin':\n context: mp.context.BaseContext = mp.get_context('spawn')\nelse:\n context = mp.get_context()\nself.data_channel = context.Queue()\ninitial_data = state._get_napari_data()\nviewer_args = {'axis_labels': state.grid.axes, 'ndisplay... | <|body_start_0|>
self._logger = logging.getLogger(__name__)
if platform.system() == 'Darwin':
context: mp.context.BaseContext = mp.get_context('spawn')
else:
context = mp.get_context()
self.data_channel = context.Queue()
initial_data = state._get_napari_da... | allows viewing and updating data in a separate napari process | NapariViewer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NapariViewer:
"""allows viewing and updating data in a separate napari process"""
def __init__(self, state: FieldBase, t_initial: Optional[float]=None):
"""Args: state (:class:`pde.fields.base.FieldBase`): The initial state to be shown t_initial (float): The initial time. If `None`, ... | stack_v2_sparse_classes_36k_train_009026 | 10,485 | permissive | [
{
"docstring": "Args: state (:class:`pde.fields.base.FieldBase`): The initial state to be shown t_initial (float): The initial time. If `None`, no time will be shown.",
"name": "__init__",
"signature": "def __init__(self, state: FieldBase, t_initial: Optional[float]=None)"
},
{
"docstring": "upd... | 3 | stack_v2_sparse_classes_30k_train_006146 | Implement the Python class `NapariViewer` described below.
Class description:
allows viewing and updating data in a separate napari process
Method signatures and docstrings:
- def __init__(self, state: FieldBase, t_initial: Optional[float]=None): Args: state (:class:`pde.fields.base.FieldBase`): The initial state to ... | Implement the Python class `NapariViewer` described below.
Class description:
allows viewing and updating data in a separate napari process
Method signatures and docstrings:
- def __init__(self, state: FieldBase, t_initial: Optional[float]=None): Args: state (:class:`pde.fields.base.FieldBase`): The initial state to ... | d9c931a8361eaf27bc3766daba26edc11756b5f5 | <|skeleton|>
class NapariViewer:
"""allows viewing and updating data in a separate napari process"""
def __init__(self, state: FieldBase, t_initial: Optional[float]=None):
"""Args: state (:class:`pde.fields.base.FieldBase`): The initial state to be shown t_initial (float): The initial time. If `None`, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NapariViewer:
"""allows viewing and updating data in a separate napari process"""
def __init__(self, state: FieldBase, t_initial: Optional[float]=None):
"""Args: state (:class:`pde.fields.base.FieldBase`): The initial state to be shown t_initial (float): The initial time. If `None`, no time will ... | the_stack_v2_python_sparse | pde/trackers/interactive.py | zwicker-group/py-pde | train | 327 |
e24f77a7ec4c63a0c1ac7d553b9bc43a5beba174 | [
"weight = np.random.normal(0, 0.0001, (in_features, out_features))\ngrad_weight = np.zeros((in_features, out_features))\nbias = np.zeros(out_features)\nself.params = {'weight': weight, 'bias': bias}\nself.grads = {'weight': grad_weight, 'bias': bias}",
"self.x = x\nself.out = np.dot(x, self.params['weight']) + se... | <|body_start_0|>
weight = np.random.normal(0, 0.0001, (in_features, out_features))
grad_weight = np.zeros((in_features, out_features))
bias = np.zeros(out_features)
self.params = {'weight': weight, 'bias': bias}
self.grads = {'weight': grad_weight, 'bias': bias}
<|end_body_0|>
<... | Linear module. Applies a linear transformation to the input data. | LinearModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize wei... | stack_v2_sparse_classes_36k_train_009027 | 3,644 | no_license | [
{
"docstring": "Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. Initialize biases self.params['bias'] with 0. Also, initialize ... | 3 | stack_v2_sparse_classes_30k_val_001036 | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | Implement the Python class `LinearModule` described below.
Class description:
Linear module. Applies a linear transformation to the input data.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Initializes the parameters of the module. Args: in_features: size of each input sample out_... | 19e8ac762cedda82410a0dda676edaf659c55d6a | <|skeleton|>
class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize wei... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearModule:
"""Linear module. Applies a linear transformation to the input data."""
def __init__(self, in_features, out_features):
"""Initializes the parameters of the module. Args: in_features: size of each input sample out_features: size of each output sample TODO: Initialize weights self.par... | the_stack_v2_python_sparse | assignment_1/code/modules.py | RancyChepchirchir/dl-assignments | train | 0 |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.spherical_cheb_bn_pool = SphericalChebBNPool(in_channels, middle_channels, lap, pooling, kernel_size)\nself.spherical_cheb = SphericalChebConv(middle_channels, out_channels, lap, kernel_size)",
"x = self.spherical_cheb_bn_pool(x)\nx = self.spherical_cheb(x)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.spherical_cheb_bn_pool = SphericalChebBNPool(in_channels, middle_channels, lap, pooling, kernel_size)
self.spherical_cheb = SphericalChebConv(middle_channels, out_channels, lap, kernel_size)
<|end_body_0|>
<|body_start_1|>
x = self.spherical_cheb... | Building Block calling a SphericalChebBNPool block then a SphericalCheb. | SphericalChebBNPoolCheb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalChebBNPoolCheb:
"""Building Block calling a SphericalChebBNPool block then a SphericalCheb."""
def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. middle_channels (... | stack_v2_sparse_classes_36k_train_009028 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: in_channels (int): initial number of channels. middle_channels (int): middle number of channels. out_channels (int): output number of channels. lap (:obj:`torch.sparse.FloatTensor`): laplacian. pooling (:obj:`torch.nn.Module`): pooling/unpooling module. kernel_size (int, op... | 2 | stack_v2_sparse_classes_30k_train_000839 | Implement the Python class `SphericalChebBNPoolCheb` described below.
Class description:
Building Block calling a SphericalChebBNPool block then a SphericalCheb.
Method signatures and docstrings:
- def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_chan... | Implement the Python class `SphericalChebBNPoolCheb` described below.
Class description:
Building Block calling a SphericalChebBNPool block then a SphericalCheb.
Method signatures and docstrings:
- def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_chan... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalChebBNPoolCheb:
"""Building Block calling a SphericalChebBNPool block then a SphericalCheb."""
def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. middle_channels (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphericalChebBNPoolCheb:
"""Building Block calling a SphericalChebBNPool block then a SphericalCheb."""
def __init__(self, in_channels, middle_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. middle_channels (int): middle ... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
a73fba01c2da0f3d27a47fbd2591e312b3063919 | [
"super(Test_relax_fit, self).__init__(methodName)\nself.interpreter = Interpreter(show_script=False, raise_relax_error=True)\nself.interpreter.populate_self()\nself.interpreter.on(verbose=False)\nself.relax_fit_fns = self.interpreter.relax_fit",
"for data in DATA_TYPES:\n if data[0] == 'float' or data[0] == 'b... | <|body_start_0|>
super(Test_relax_fit, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise_relax_error=True)
self.interpreter.populate_self()
self.interpreter.on(verbose=False)
self.relax_fit_fns = self.interpreter.relax_fit
<|end_body_0|>
<|body_s... | Unit tests for the functions of the 'prompt.relax_fit' module. | Test_relax_fit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_relax_fit:
"""Unit tests for the functions of the 'prompt.relax_fit' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_relax_time_argfail_time(self):
"""The time arg test of the relax_f... | stack_v2_sparse_classes_36k_train_009029 | 3,846 | no_license | [
{
"docstring": "Set up the test case class for the system tests.",
"name": "__init__",
"signature": "def __init__(self, methodName=None)"
},
{
"docstring": "The time arg test of the relax_fit.relax_time() user function.",
"name": "test_relax_time_argfail_time",
"signature": "def test_rel... | 4 | stack_v2_sparse_classes_30k_train_014581 | Implement the Python class `Test_relax_fit` described below.
Class description:
Unit tests for the functions of the 'prompt.relax_fit' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_relax_time_argfail_time(self): The time ar... | Implement the Python class `Test_relax_fit` described below.
Class description:
Unit tests for the functions of the 'prompt.relax_fit' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_relax_time_argfail_time(self): The time ar... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Test_relax_fit:
"""Unit tests for the functions of the 'prompt.relax_fit' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_relax_time_argfail_time(self):
"""The time arg test of the relax_f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_relax_fit:
"""Unit tests for the functions of the 'prompt.relax_fit' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
super(Test_relax_fit, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise... | the_stack_v2_python_sparse | test_suite/unit_tests/_prompt/test_relax_fit.py | jlec/relax | train | 4 |
2424724d56efb683d4a31cd6ebfe9f7dc969d100 | [
"self._x = {0}\nself._y = {1}\nself._u = {3}\nsuper().__init__(dist, [rv_x, rv_y], [], rv_mode=rv_mode)\ntheoretical_bound = self._full_shape[self._proxy_vars[0]] + 1\nbound = min(bound, theoretical_bound) if bound else theoretical_bound\nself._construct_auxvars([({0}, bound)])",
"mi_a = self._mutual_information(... | <|body_start_0|>
self._x = {0}
self._y = {1}
self._u = {3}
super().__init__(dist, [rv_x, rv_y], [], rv_mode=rv_mode)
theoretical_bound = self._full_shape[self._proxy_vars[0]] + 1
bound = min(bound, theoretical_bound) if bound else theoretical_bound
self._construct... | Computes the hypercontractivity coefficient: .. math:: max_{U - X - Y} I[U:Y] / I[U:X] | HypercontractivityCoefficient | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypercontractivityCoefficient:
"""Computes the hypercontractivity coefficient: .. math:: max_{U - X - Y} I[U:Y] / I[U:X]"""
def __init__(self, dist, rv_x=None, rv_y=None, bound=None, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : Distribution The distributio... | stack_v2_sparse_classes_36k_train_009030 | 4,583 | permissive | [
{
"docstring": "Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute the intrinsic mutual information of. rv_x : iterable The variables to consider `X`. rv_y : iterable The variables to consider `Y`. bound : int, None Specifies a bound on the size of the auxiliary rand... | 2 | null | Implement the Python class `HypercontractivityCoefficient` described below.
Class description:
Computes the hypercontractivity coefficient: .. math:: max_{U - X - Y} I[U:Y] / I[U:X]
Method signatures and docstrings:
- def __init__(self, dist, rv_x=None, rv_y=None, bound=None, rv_mode=None): Initialize the optimizer. ... | Implement the Python class `HypercontractivityCoefficient` described below.
Class description:
Computes the hypercontractivity coefficient: .. math:: max_{U - X - Y} I[U:Y] / I[U:X]
Method signatures and docstrings:
- def __init__(self, dist, rv_x=None, rv_y=None, bound=None, rv_mode=None): Initialize the optimizer. ... | b13c5020a2b8524527a4a0db5a81d8549142228c | <|skeleton|>
class HypercontractivityCoefficient:
"""Computes the hypercontractivity coefficient: .. math:: max_{U - X - Y} I[U:Y] / I[U:X]"""
def __init__(self, dist, rv_x=None, rv_y=None, bound=None, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : Distribution The distributio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HypercontractivityCoefficient:
"""Computes the hypercontractivity coefficient: .. math:: max_{U - X - Y} I[U:Y] / I[U:X]"""
def __init__(self, dist, rv_x=None, rv_y=None, bound=None, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute ... | the_stack_v2_python_sparse | dit/divergences/hypercontractivity_coefficient.py | dit/dit | train | 468 |
e08042ef94570adc4bf1f6d2b5cec5cc2763094a | [
"res = {'logged_in': False}\nif api.user.is_logged_in():\n res['logged_in'] = True\n res['score'] = api.stats.get_score(tid=api.user.get_user()['tid'], time_weighted=False)\n userdata = {k: v for k, v in api.user.get_user().items() if k in USERDATA_FILTER}\n res.update(userdata)\nreturn jsonify(res)",
... | <|body_start_0|>
res = {'logged_in': False}
if api.user.is_logged_in():
res['logged_in'] = True
res['score'] = api.stats.get_score(tid=api.user.get_user()['tid'], time_weighted=False)
userdata = {k: v for k, v in api.user.get_user().items() if k in USERDATA_FILTER}
... | Get the current user or update their extdata. | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Get the current user or update their extdata."""
def get(self):
"""Get information about the current user."""
<|body_0|>
def patch(self):
"""Update the current user's extdata (other fields not supported)."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_009031 | 8,307 | permissive | [
{
"docstring": "Get information about the current user.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update the current user's extdata (other fields not supported).",
"name": "patch",
"signature": "def patch(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011624 | Implement the Python class `User` described below.
Class description:
Get the current user or update their extdata.
Method signatures and docstrings:
- def get(self): Get information about the current user.
- def patch(self): Update the current user's extdata (other fields not supported). | Implement the Python class `User` described below.
Class description:
Get the current user or update their extdata.
Method signatures and docstrings:
- def get(self): Get information about the current user.
- def patch(self): Update the current user's extdata (other fields not supported).
<|skeleton|>
class User:
... | 468035038afe00c6e7842b7e68ec45355ee1a224 | <|skeleton|>
class User:
"""Get the current user or update their extdata."""
def get(self):
"""Get information about the current user."""
<|body_0|>
def patch(self):
"""Update the current user's extdata (other fields not supported)."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""Get the current user or update their extdata."""
def get(self):
"""Get information about the current user."""
res = {'logged_in': False}
if api.user.is_logged_in():
res['logged_in'] = True
res['score'] = api.stats.get_score(tid=api.user.get_user()[... | the_stack_v2_python_sparse | picoCTF-web/api/apps/v1/user.py | zxc135781/picoCTF | train | 1 |
9a1f579f155b09cff21d97024df76b1e45eff390 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | CurrierInvokeServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrierInvokeServicer:
"""Missing associated documentation comment in .proto file."""
def Invoke(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetWorkStatus(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_36k_train_009032 | 9,240 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Invoke",
"signature": "def Invoke(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetWorkStatus",
"signature": "def GetWorkStatus(self, requ... | 2 | null | Implement the Python class `CurrierInvokeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Invoke(self, request, context): Missing associated documentation comment in .proto file.
- def GetWorkStatus(self, request, context): ... | Implement the Python class `CurrierInvokeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Invoke(self, request, context): Missing associated documentation comment in .proto file.
- def GetWorkStatus(self, request, context): ... | 039e4a679b554e085f935f8d725f560bdce6b688 | <|skeleton|>
class CurrierInvokeServicer:
"""Missing associated documentation comment in .proto file."""
def Invoke(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetWorkStatus(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrierInvokeServicer:
"""Missing associated documentation comment in .proto file."""
def Invoke(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | descarteslabs/common/proto/currier/currier_pb2_grpc.py | stjordanis/descarteslabs-python | train | 0 |
a04d4396b07335fe111676038a678e77fd84d160 | [
"if nbTasks < 0:\n cpu = cpu_count() + nbTasks + 1\n if cpu <= 0:\n cpu = 1\n nbTasks = min(cpu, dataSize)\nelse:\n if nbTasks == 0:\n nbTasks = 1\n nbTasks = min(nbTasks, dataSize)\ncounts = [dataSize / nbTasks] * nbTasks\nfor i in xrange(dataSize % nbTasks):\n counts[i] += 1\nstart... | <|body_start_0|>
if nbTasks < 0:
cpu = cpu_count() + nbTasks + 1
if cpu <= 0:
cpu = 1
nbTasks = min(cpu, dataSize)
else:
if nbTasks == 0:
nbTasks = 1
nbTasks = min(nbTasks, dataSize)
counts = [dataSize / ... | =========== TaskSplitter =========== A toolkit for preprocessing parallel computation | TaskSplitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskSplitter:
"""=========== TaskSplitter =========== A toolkit for preprocessing parallel computation"""
def computePartition(self, nbTasks, dataSize):
"""Compute data partitioning for parallel computation : min(nbTasks, dataSize) Parameters ---------- nbTasks : int (!=0) If >0 : th... | stack_v2_sparse_classes_36k_train_009033 | 13,126 | no_license | [
{
"docstring": "Compute data partitioning for parallel computation : min(nbTasks, dataSize) Parameters ---------- nbTasks : int (!=0) If >0 : the parallelization factor. If <0 : nbTasks = #cpu+nbTasks+1 (-1 -> nbTasks = #cpu) dataSize : int > 0 The size of the data to process Return ------ triplet = (nbTasks, c... | 2 | stack_v2_sparse_classes_30k_train_017431 | Implement the Python class `TaskSplitter` described below.
Class description:
=========== TaskSplitter =========== A toolkit for preprocessing parallel computation
Method signatures and docstrings:
- def computePartition(self, nbTasks, dataSize): Compute data partitioning for parallel computation : min(nbTasks, dataS... | Implement the Python class `TaskSplitter` described below.
Class description:
=========== TaskSplitter =========== A toolkit for preprocessing parallel computation
Method signatures and docstrings:
- def computePartition(self, nbTasks, dataSize): Compute data partitioning for parallel computation : min(nbTasks, dataS... | 192d03a368ef79b45ed154838a494db85c83f76a | <|skeleton|>
class TaskSplitter:
"""=========== TaskSplitter =========== A toolkit for preprocessing parallel computation"""
def computePartition(self, nbTasks, dataSize):
"""Compute data partitioning for parallel computation : min(nbTasks, dataSize) Parameters ---------- nbTasks : int (!=0) If >0 : th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskSplitter:
"""=========== TaskSplitter =========== A toolkit for preprocessing parallel computation"""
def computePartition(self, nbTasks, dataSize):
"""Compute data partitioning for parallel computation : min(nbTasks, dataSize) Parameters ---------- nbTasks : int (!=0) If >0 : the paralleliza... | the_stack_v2_python_sparse | code/lib/TaskManager.py | jm-begon/masterthesis | train | 0 |
42e73af0a8a0595994a59e3400f84348ec0959e1 | [
"try:\n allergy: models.Allergy = models.Allergy.create_from_json(data=request.data, patient_profile=request.user.patient_profile)\nexcept custom_exceptions.DataNotProvided as e:\n return response.Response(data=e.get_response_format(), status=status.HTTP_400_BAD_REQUEST)\nserialized_allergy = serializers.Alle... | <|body_start_0|>
try:
allergy: models.Allergy = models.Allergy.create_from_json(data=request.data, patient_profile=request.user.patient_profile)
except custom_exceptions.DataNotProvided as e:
return response.Response(data=e.get_response_format(), status=status.HTTP_400_BAD_REQUES... | Endpoints for Allergy objects. | AllergiesEndpoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllergiesEndpoint:
"""Endpoints for Allergy objects."""
def post(self, request: Request) -> response.Response:
"""Adds a new allergy for the user."""
<|body_0|>
def put(self, request: Request) -> response.Response:
"""Updates an existing allergy."""
<|bod... | stack_v2_sparse_classes_36k_train_009034 | 14,860 | no_license | [
{
"docstring": "Adds a new allergy for the user.",
"name": "post",
"signature": "def post(self, request: Request) -> response.Response"
},
{
"docstring": "Updates an existing allergy.",
"name": "put",
"signature": "def put(self, request: Request) -> response.Response"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_010071 | Implement the Python class `AllergiesEndpoint` described below.
Class description:
Endpoints for Allergy objects.
Method signatures and docstrings:
- def post(self, request: Request) -> response.Response: Adds a new allergy for the user.
- def put(self, request: Request) -> response.Response: Updates an existing alle... | Implement the Python class `AllergiesEndpoint` described below.
Class description:
Endpoints for Allergy objects.
Method signatures and docstrings:
- def post(self, request: Request) -> response.Response: Adds a new allergy for the user.
- def put(self, request: Request) -> response.Response: Updates an existing alle... | b6d757895132b9b3c8c6682c11efadf993d5905b | <|skeleton|>
class AllergiesEndpoint:
"""Endpoints for Allergy objects."""
def post(self, request: Request) -> response.Response:
"""Adds a new allergy for the user."""
<|body_0|>
def put(self, request: Request) -> response.Response:
"""Updates an existing allergy."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllergiesEndpoint:
"""Endpoints for Allergy objects."""
def post(self, request: Request) -> response.Response:
"""Adds a new allergy for the user."""
try:
allergy: models.Allergy = models.Allergy.create_from_json(data=request.data, patient_profile=request.user.patient_profile)... | the_stack_v2_python_sparse | main/model_api.py | kalolad1/cosmos | train | 0 |
830b634409d806bb3bca6de828a57ae82e6476d2 | [
"self.consumer_group = consumer_group\nself.consumer_group_generation_id = consumer_group_generation_id\nself.consumer_id = consumer_id\nself._reqs = defaultdict(dict)\nfor t in partition_requests:\n self._reqs[t.topic_name][t.partition_id] = (t.offset, t.timestamp, t.metadata)",
"size = self.HEADER_LEN + 2 + ... | <|body_start_0|>
self.consumer_group = consumer_group
self.consumer_group_generation_id = consumer_group_generation_id
self.consumer_id = consumer_id
self._reqs = defaultdict(dict)
for t in partition_requests:
self._reqs[t.topic_name][t.partition_id] = (t.offset, t.ti... | An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Partition => int32 Offset => int64 TimeStamp => int... | OffsetCommitRequest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OffsetCommitRequest:
"""An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Part... | stack_v2_sparse_classes_36k_train_009035 | 12,832 | permissive | [
{
"docstring": "Create a new offset commit request :param partition_requests: Iterable of :class:`kafka.pykafka.protocol.PartitionOffsetCommitRequest` for this request",
"name": "__init__",
"signature": "def __init__(self, consumer_group, consumer_group_generation_id, consumer_id, partition_requests=[])... | 3 | stack_v2_sparse_classes_30k_train_007464 | Implement the Python class `OffsetCommitRequest` described below.
Class description:
An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 Consum... | Implement the Python class `OffsetCommitRequest` described below.
Class description:
An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 Consum... | c7054bd05b127385b8c6f56a4e2241d92ff42ab4 | <|skeleton|>
class OffsetCommitRequest:
"""An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Part... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OffsetCommitRequest:
"""An offset commit request Specification:: OffsetCommitRequest => ConsumerGroupId ConsumerGroupGenerationId ConsumerId [TopicName [Partition Offset TimeStamp Metadata]] ConsumerGroupId => string ConsumerGroupGenerationId => int32 ConsumerId => string TopicName => string Partition => int3... | the_stack_v2_python_sparse | py_kafk/tar/pykafka-2.8.1-dev.1/pykafka/protocol/offset_commit.py | liuansen/python-utils-class | train | 3 |
ae4e3880ffa17975430fea490f616daefa904fd9 | [
"self.client = mock.Mock(Client)\nself.shipper = Shipper(client_builder=lambda *args, **kwargs: self.client)\n\ndef _fake_blocking_call_from_thread(reactor, call, *args, **kwargs):\n d = maybeDeferred(call, *args, **kwargs)\n return self.successResultOf(d)\nself.blocking_call = mock.patch('shipper.shipper.thr... | <|body_start_0|>
self.client = mock.Mock(Client)
self.shipper = Shipper(client_builder=lambda *args, **kwargs: self.client)
def _fake_blocking_call_from_thread(reactor, call, *args, **kwargs):
d = maybeDeferred(call, *args, **kwargs)
return self.successResultOf(d)
... | Tests commands (methods on Shipper) | ShipperCommands | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShipperCommands:
"""Tests commands (methods on Shipper)"""
def setUp(self):
"""Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out"""
<|body_0|>
def test_wait(self):
"""Client.wait is called for every for every container p... | stack_v2_sparse_classes_36k_train_009036 | 49,482 | no_license | [
{
"docstring": "Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Client.wait is called for every for every container passed to Shipper.wait. The result is a list tuples of container: ... | 2 | stack_v2_sparse_classes_30k_train_009901 | Implement the Python class `ShipperCommands` described below.
Class description:
Tests commands (methods on Shipper)
Method signatures and docstrings:
- def setUp(self): Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out
- def test_wait(self): Client.wait is called for every ... | Implement the Python class `ShipperCommands` described below.
Class description:
Tests commands (methods on Shipper)
Method signatures and docstrings:
- def setUp(self): Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out
- def test_wait(self): Client.wait is called for every ... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class ShipperCommands:
"""Tests commands (methods on Shipper)"""
def setUp(self):
"""Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out"""
<|body_0|>
def test_wait(self):
"""Client.wait is called for every for every container p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShipperCommands:
"""Tests commands (methods on Shipper)"""
def setUp(self):
"""Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out"""
self.client = mock.Mock(Client)
self.shipper = Shipper(client_builder=lambda *args, **kwargs: self.client)... | the_stack_v2_python_sparse | repoData/mailgun-shipper/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
3d25be333ea08e52683afa2859fc9cf419e79531 | [
"if start_date == None:\n self.start_date = pd.to_datetime('2015275', format='%Y%j')\nelse:\n self.start_date = convert_date(start_date)\nif end_date == None:\n self.end_date = pd.to_datetime('2015307', format='%Y%j')\nelse:\n self.end_date = convert_date(end_date)\nself.date_range = pd.date_range(self.... | <|body_start_0|>
if start_date == None:
self.start_date = pd.to_datetime('2015275', format='%Y%j')
else:
self.start_date = convert_date(start_date)
if end_date == None:
self.end_date = pd.to_datetime('2015307', format='%Y%j')
else:
self.end... | Data Fetcher for Mahali Data | DataFetcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFetcher:
"""Data Fetcher for Mahali Data"""
def __init__(self, ap_paramList=[], start_date=None, end_date=None):
"""Initialize Mahali Data Fetcher @param ap_paramList[stations]: Autolist of stations (Defaults to all stations) @param start_date: Starting date for seelcting data (D... | stack_v2_sparse_classes_36k_train_009037 | 5,601 | permissive | [
{
"docstring": "Initialize Mahali Data Fetcher @param ap_paramList[stations]: Autolist of stations (Defaults to all stations) @param start_date: Starting date for seelcting data (Defaults to beginning of available data) @param end_date: Ending date for selecting data (Defaults to end of available data)",
"n... | 2 | stack_v2_sparse_classes_30k_train_017950 | Implement the Python class `DataFetcher` described below.
Class description:
Data Fetcher for Mahali Data
Method signatures and docstrings:
- def __init__(self, ap_paramList=[], start_date=None, end_date=None): Initialize Mahali Data Fetcher @param ap_paramList[stations]: Autolist of stations (Defaults to all station... | Implement the Python class `DataFetcher` described below.
Class description:
Data Fetcher for Mahali Data
Method signatures and docstrings:
- def __init__(self, ap_paramList=[], start_date=None, end_date=None): Initialize Mahali Data Fetcher @param ap_paramList[stations]: Autolist of stations (Defaults to all station... | 935bfd54149abd9542fe38e77b7eabab48b1c3a1 | <|skeleton|>
class DataFetcher:
"""Data Fetcher for Mahali Data"""
def __init__(self, ap_paramList=[], start_date=None, end_date=None):
"""Initialize Mahali Data Fetcher @param ap_paramList[stations]: Autolist of stations (Defaults to all stations) @param start_date: Starting date for seelcting data (D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataFetcher:
"""Data Fetcher for Mahali Data"""
def __init__(self, ap_paramList=[], start_date=None, end_date=None):
"""Initialize Mahali Data Fetcher @param ap_paramList[stations]: Autolist of stations (Defaults to all stations) @param start_date: Starting date for seelcting data (Defaults to be... | the_stack_v2_python_sparse | skdaccess/geo/mahali/tec/data_fetcher.py | MITHaystack/scikit-dataaccess | train | 41 |
84496be901ffdd5ef773bad38c74f853c6598034 | [
"i = 0\nwhile i <= len(nums) - 1:\n if nums[i] == val:\n nums[i] = nums[-1]\n nums.pop()\n else:\n i += 1\nreturn i",
"i = 0\nj = len(nums) - 1\nwhile i < j and i <= len(nums) - 1 and (j >= 0):\n while i < j and i <= len(nums) - 1 and (nums[i] != val):\n i += 1\n while i < ... | <|body_start_0|>
i = 0
while i <= len(nums) - 1:
if nums[i] == val:
nums[i] = nums[-1]
nums.pop()
else:
i += 1
return i
<|end_body_0|>
<|body_start_1|>
i = 0
j = len(nums) - 1
while i < j and i <= le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_0|>
def removeElementV0(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009038 | 1,332 | no_license | [
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElement",
"signature": "def removeElement(self, nums, val)"
},
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElementV0",
"signature": "def removeElementV0(self, nums, val... | 2 | stack_v2_sparse_classes_30k_train_001537 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int
- def removeElementV0(self, nums, val): :type nums: List[int] :type val: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int
- def removeElementV0(self, nums, val): :type nums: List[int] :type val: int :rtype: int
<|s... | 76fdcec59b48c69120ebcf13a5374e6fc480c257 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_0|>
def removeElementV0(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
i = 0
while i <= len(nums) - 1:
if nums[i] == val:
nums[i] = nums[-1]
nums.pop()
else:
i += 1
return i
... | the_stack_v2_python_sparse | lulu/removeElement.py | luluxing3/LeetCode | train | 1 | |
fa385683de2692f7c8961f6e339e3ad60e42af85 | [
"logger.debug('Parsing input in KServe v2 format %s', data)\ninputs = self._batch_from_json(data)\nlogger.debug('KServev2 parsed inputs %s', inputs)\nreturn inputs",
"logger.debug('Parse input data %s', rows)\nbody_list = [body_list.get('data') or body_list.get('body') for body_list in rows]\ndata_list = self._fr... | <|body_start_0|>
logger.debug('Parsing input in KServe v2 format %s', data)
inputs = self._batch_from_json(data)
logger.debug('KServev2 parsed inputs %s', inputs)
return inputs
<|end_body_0|>
<|body_start_1|>
logger.debug('Parse input data %s', rows)
body_list = [body_li... | Implementation. Captures batches in KServe v2 protocol format, returns also in FServing v2 protocol format. | KServev2Envelope | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KServev2Envelope:
"""Implementation. Captures batches in KServe v2 protocol format, returns also in FServing v2 protocol format."""
def parse_input(self, data):
"""Translates KServe request input to list of data expected by Torchserve. Parameters: data (json): KServe v2 request input... | stack_v2_sparse_classes_36k_train_009039 | 5,882 | permissive | [
{
"docstring": "Translates KServe request input to list of data expected by Torchserve. Parameters: data (json): KServe v2 request input json. { \"inputs\": [{ \"name\": \"input-0\", \"shape\": [37], \"datatype\": \"INT64\", \"data\": [66, 108, 111, 111, 109] }] } Returns: list of data objects. [{ 'name': 'inpu... | 6 | null | Implement the Python class `KServev2Envelope` described below.
Class description:
Implementation. Captures batches in KServe v2 protocol format, returns also in FServing v2 protocol format.
Method signatures and docstrings:
- def parse_input(self, data): Translates KServe request input to list of data expected by Tor... | Implement the Python class `KServev2Envelope` described below.
Class description:
Implementation. Captures batches in KServe v2 protocol format, returns also in FServing v2 protocol format.
Method signatures and docstrings:
- def parse_input(self, data): Translates KServe request input to list of data expected by Tor... | 242895c6b4596c4119ec09d6139e627c5dd696b6 | <|skeleton|>
class KServev2Envelope:
"""Implementation. Captures batches in KServe v2 protocol format, returns also in FServing v2 protocol format."""
def parse_input(self, data):
"""Translates KServe request input to list of data expected by Torchserve. Parameters: data (json): KServe v2 request input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KServev2Envelope:
"""Implementation. Captures batches in KServe v2 protocol format, returns also in FServing v2 protocol format."""
def parse_input(self, data):
"""Translates KServe request input to list of data expected by Torchserve. Parameters: data (json): KServe v2 request input json. { "inp... | the_stack_v2_python_sparse | ts/torch_handler/request_envelope/kservev2.py | pytorch/serve | train | 3,689 |
d375ee42b072dee1c7446ccd874f1cd213413b6c | [
"super().__init__()\nself.model = model\nself.coil_to_batch = coil_to_batch\nself.coil_dim = coil_dim",
"output = []\nfor idx in range(data.size(self.coil_dim)):\n subselected_data = data.select(self.coil_dim, idx)\n if subselected_data.shape[-1] == 2 and subselected_data.dim() == 4:\n output.append(... | <|body_start_0|>
super().__init__()
self.model = model
self.coil_to_batch = coil_to_batch
self.coil_dim = coil_dim
<|end_body_0|>
<|body_start_1|>
output = []
for idx in range(data.size(self.coil_dim)):
subselected_data = data.select(self.coil_dim, idx)
... | This makes the forward pass of multi-coil data of shape (N, N_coils, H, W, C) to a model. If coil_to_batch is set to True, coil dimension is moved to the batch dimension. Otherwise, it passes to the model each coil-data individually. | MultiCoil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiCoil:
"""This makes the forward pass of multi-coil data of shape (N, N_coils, H, W, C) to a model. If coil_to_batch is set to True, coil dimension is moved to the batch dimension. Otherwise, it passes to the model each coil-data individually."""
def __init__(self, model: nn.Module, coil... | stack_v2_sparse_classes_36k_train_009040 | 2,652 | permissive | [
{
"docstring": "Inits MultiCoil. Parameters ---------- model: Any nn.Module that takes as input with 4D data (N, H, W, C). Typically, a convolutional-like model. torch.nn.Module coil_dim: Coil dimension. int, Default: 1. coil_to_batch: If True batch and coil dimensions are merged when forwarded by the model and... | 3 | stack_v2_sparse_classes_30k_test_000737 | Implement the Python class `MultiCoil` described below.
Class description:
This makes the forward pass of multi-coil data of shape (N, N_coils, H, W, C) to a model. If coil_to_batch is set to True, coil dimension is moved to the batch dimension. Otherwise, it passes to the model each coil-data individually.
Method si... | Implement the Python class `MultiCoil` described below.
Class description:
This makes the forward pass of multi-coil data of shape (N, N_coils, H, W, C) to a model. If coil_to_batch is set to True, coil dimension is moved to the batch dimension. Otherwise, it passes to the model each coil-data individually.
Method si... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class MultiCoil:
"""This makes the forward pass of multi-coil data of shape (N, N_coils, H, W, C) to a model. If coil_to_batch is set to True, coil dimension is moved to the batch dimension. Otherwise, it passes to the model each coil-data individually."""
def __init__(self, model: nn.Module, coil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiCoil:
"""This makes the forward pass of multi-coil data of shape (N, N_coils, H, W, C) to a model. If coil_to_batch is set to True, coil dimension is moved to the batch dimension. Otherwise, it passes to the model each coil-data individually."""
def __init__(self, model: nn.Module, coil_dim: int=1, ... | the_stack_v2_python_sparse | mridc/collections/reconstruction/models/crossdomain/multicoil.py | wdika/mridc | train | 40 |
f7394bc423b95808b226662f471dffcefac07c26 | [
"super(Mnist, self).__init__()\nif data_format == 'channels_first':\n self._input_shape = [-1, 1, 28, 28]\nelse:\n assert data_format == 'channels_last'\n self._input_shape = [-1, 28, 28, 1]\nself.conv1 = tf_layers.Conv2D(32, 5, padding='same', data_format=data_format, activation=nn.relu)\nself.conv2 = tf_... | <|body_start_0|>
super(Mnist, self).__init__()
if data_format == 'channels_first':
self._input_shape = [-1, 1, 28, 28]
else:
assert data_format == 'channels_last'
self._input_shape = [-1, 28, 28, 1]
self.conv1 = tf_layers.Conv2D(32, 5, padding='same', ... | Mnist | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mnist:
def __init__(self, data_format):
"""Creates a model for classifying a hand-written digit. Args: data_format: Either 'channels_first' or 'channels_last'."""
<|body_0|>
def __call__(self, inputs, training):
"""Add operations to classify a batch of input images. ... | stack_v2_sparse_classes_36k_train_009041 | 27,689 | permissive | [
{
"docstring": "Creates a model for classifying a hand-written digit. Args: data_format: Either 'channels_first' or 'channels_last'.",
"name": "__init__",
"signature": "def __init__(self, data_format)"
},
{
"docstring": "Add operations to classify a batch of input images. Args: inputs: A Tensor ... | 2 | null | Implement the Python class `Mnist` described below.
Class description:
Implement the Mnist class.
Method signatures and docstrings:
- def __init__(self, data_format): Creates a model for classifying a hand-written digit. Args: data_format: Either 'channels_first' or 'channels_last'.
- def __call__(self, inputs, train... | Implement the Python class `Mnist` described below.
Class description:
Implement the Mnist class.
Method signatures and docstrings:
- def __init__(self, data_format): Creates a model for classifying a hand-written digit. Args: data_format: Either 'channels_first' or 'channels_last'.
- def __call__(self, inputs, train... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class Mnist:
def __init__(self, data_format):
"""Creates a model for classifying a hand-written digit. Args: data_format: Either 'channels_first' or 'channels_last'."""
<|body_0|>
def __call__(self, inputs, training):
"""Add operations to classify a batch of input images. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mnist:
def __init__(self, data_format):
"""Creates a model for classifying a hand-written digit. Args: data_format: Either 'channels_first' or 'channels_last'."""
super(Mnist, self).__init__()
if data_format == 'channels_first':
self._input_shape = [-1, 1, 28, 28]
e... | the_stack_v2_python_sparse | tensorflow/python/ops/parallel_for/gradients_test.py | tensorflow/tensorflow | train | 208,740 | |
562704ad5d0c06b5aab0faffaded4d842ad66986 | [
"if not parent:\n raise ValueError('Missing parent value.')\nsuper(CSPathSpec, self).__init__(parent=parent, **kwargs)\nself.encrypted_root_plist = encrypted_root_plist\nself.location = location\nself.password = password\nself.recovery_password = recovery_password\nself.volume_index = volume_index",
"string_pa... | <|body_start_0|>
if not parent:
raise ValueError('Missing parent value.')
super(CSPathSpec, self).__init__(parent=parent, **kwargs)
self.encrypted_root_plist = encrypted_root_plist
self.location = location
self.password = password
self.recovery_password = reco... | CS path specification. Attributes: encrypted_root_plist (str): path to the EncryptedRoot.plist.wipekey file. location (str): location. password (str): password. recovery_password (str): recovery password. volume_index (int): logical volume index. | CSPathSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSPathSpec:
"""CS path specification. Attributes: encrypted_root_plist (str): path to the EncryptedRoot.plist.wipekey file. location (str): location. password (str): password. recovery_password (str): recovery password. volume_index (int): logical volume index."""
def __init__(self, encrypte... | stack_v2_sparse_classes_36k_train_009042 | 2,397 | permissive | [
{
"docstring": "Initializes a path specification. Note that the CS path specification must have a parent. Args: encrypted_root_plist (Optional[str]): path to the EncryptedRoot.plist.wipekey file. location (Optional[str]): location. password (Optional[str]): password. parent (Optional[PathSpec]): parent path spe... | 2 | null | Implement the Python class `CSPathSpec` described below.
Class description:
CS path specification. Attributes: encrypted_root_plist (str): path to the EncryptedRoot.plist.wipekey file. location (str): location. password (str): password. recovery_password (str): recovery password. volume_index (int): logical volume ind... | Implement the Python class `CSPathSpec` described below.
Class description:
CS path specification. Attributes: encrypted_root_plist (str): path to the EncryptedRoot.plist.wipekey file. location (str): location. password (str): password. recovery_password (str): recovery password. volume_index (int): logical volume ind... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class CSPathSpec:
"""CS path specification. Attributes: encrypted_root_plist (str): path to the EncryptedRoot.plist.wipekey file. location (str): location. password (str): password. recovery_password (str): recovery password. volume_index (int): logical volume index."""
def __init__(self, encrypte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSPathSpec:
"""CS path specification. Attributes: encrypted_root_plist (str): path to the EncryptedRoot.plist.wipekey file. location (str): location. password (str): password. recovery_password (str): recovery password. volume_index (int): logical volume index."""
def __init__(self, encrypted_root_plist=... | the_stack_v2_python_sparse | dfvfs/path/cs_path_spec.py | log2timeline/dfvfs | train | 197 |
33723ce8855306b035c8552bdd6d5c906bfb1899 | [
"if self.action == 'create':\n return ResponseWriteableSerializer\nreturn super().get_serializer_class()",
"children_ids = Child.objects.filter(user__id=self.request.user.id).values_list('id', flat=True)\nif 'study_uuid' in self.kwargs:\n study_uuid = self.kwargs['study_uuid']\n queryset = Response.objec... | <|body_start_0|>
if self.action == 'create':
return ResponseWriteableSerializer
return super().get_serializer_class()
<|end_body_0|>
<|body_start_1|>
children_ids = Child.objects.filter(user__id=self.request.user.id).values_list('id', flat=True)
if 'study_uuid' in self.kwarg... | Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children. | ResponseViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different ... | stack_v2_sparse_classes_36k_train_009043 | 10,514 | permissive | [
{
"docstring": "Return a different serializer for create views",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Overrides queryset. Shows responses that you either have permission to view, or responses by your own children",
"name": "get_quer... | 2 | stack_v2_sparse_classes_30k_train_007001 | Implement the Python class `ResponseViewSet` described below.
Class description:
Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children.
Method signatures and docstrin... | Implement the Python class `ResponseViewSet` described below.
Class description:
Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children.
Method signatures and docstrin... | 621fbb8b25100a21fd94721d39003b5d4f651dc5 | <|skeleton|>
class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different serializer fo... | the_stack_v2_python_sparse | api/views.py | enrobyn/lookit-api | train | 0 |
1000e9e0fa0f2ee82e0decf81625afbbd627d0d0 | [
"new_column_data = []\nfor citem in validated_data:\n if not (cname := citem.get('name')):\n raise Exception(_('Incorrect column name.'))\n if not (col := self.context['workflow'].columns.filter(name=cname).first()):\n if citem['is_key']:\n raise Exception(_('Action contains non-exist... | <|body_start_0|>
new_column_data = []
for citem in validated_data:
if not (cname := citem.get('name')):
raise Exception(_('Incorrect column name.'))
if not (col := self.context['workflow'].columns.filter(name=cname).first()):
if citem['is_key']:
... | Full Action serializer traversing conditions AND columns. | ActionSelfcontainedSerializer | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionSelfcontainedSerializer:
"""Full Action serializer traversing conditions AND columns."""
def _process_columns(self, validated_data: List) -> List:
"""Process the used_columns field of a serializer. Verifies if the column is new or not. If not new, it verifies that is compatible... | stack_v2_sparse_classes_36k_train_009044 | 11,560 | permissive | [
{
"docstring": "Process the used_columns field of a serializer. Verifies if the column is new or not. If not new, it verifies that is compatible with the columns already existing in the workflow :param validated_data: Object with the parsed column items :return: List of new columns",
"name": "_process_colum... | 3 | null | Implement the Python class `ActionSelfcontainedSerializer` described below.
Class description:
Full Action serializer traversing conditions AND columns.
Method signatures and docstrings:
- def _process_columns(self, validated_data: List) -> List: Process the used_columns field of a serializer. Verifies if the column ... | Implement the Python class `ActionSelfcontainedSerializer` described below.
Class description:
Full Action serializer traversing conditions AND columns.
Method signatures and docstrings:
- def _process_columns(self, validated_data: List) -> List: Process the used_columns field of a serializer. Verifies if the column ... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class ActionSelfcontainedSerializer:
"""Full Action serializer traversing conditions AND columns."""
def _process_columns(self, validated_data: List) -> List:
"""Process the used_columns field of a serializer. Verifies if the column is new or not. If not new, it verifies that is compatible... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionSelfcontainedSerializer:
"""Full Action serializer traversing conditions AND columns."""
def _process_columns(self, validated_data: List) -> List:
"""Process the used_columns field of a serializer. Verifies if the column is new or not. If not new, it verifies that is compatible with the col... | the_stack_v2_python_sparse | ontask/action/serializers/basic.py | abelardopardo/ontask_b | train | 43 |
5bace45a65dd5ee972f2f2e16334338be5c6bb18 | [
"if pk is None or pk == '':\n return None\ntable_name = self.model._meta.db_table\ncache = FireHydrantCacheFactory(('model_cache', table_name))\nobj = cache.get_cache(pk)\nif obj is None:\n try:\n obj = super().get_queryset().get(pk=pk)\n cache.set_cache(pk, obj)\n except:\n return Non... | <|body_start_0|>
if pk is None or pk == '':
return None
table_name = self.model._meta.db_table
cache = FireHydrantCacheFactory(('model_cache', table_name))
obj = cache.get_cache(pk)
if obj is None:
try:
obj = super().get_queryset().get(pk=p... | FireHydrantModelManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FireHydrantModelManager:
def get_once(self, pk):
"""缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:"""
<|body_0|>
def all_cache(self):
"""全部缓存 :return:"""
<|body_1|>
def filter_cache(self, **kwargs):
"""过滤缓存 :param kwargs: :return:"""
... | stack_v2_sparse_classes_36k_train_009045 | 1,776 | no_license | [
{
"docstring": "缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:",
"name": "get_once",
"signature": "def get_once(self, pk)"
},
{
"docstring": "全部缓存 :return:",
"name": "all_cache",
"signature": "def all_cache(self)"
},
{
"docstring": "过滤缓存 :param kwargs: :return:",
"name... | 4 | null | Implement the Python class `FireHydrantModelManager` described below.
Class description:
Implement the FireHydrantModelManager class.
Method signatures and docstrings:
- def get_once(self, pk): 缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:
- def all_cache(self): 全部缓存 :return:
- def filter_cache(self, **kwargs... | Implement the Python class `FireHydrantModelManager` described below.
Class description:
Implement the FireHydrantModelManager class.
Method signatures and docstrings:
- def get_once(self, pk): 缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:
- def all_cache(self): 全部缓存 :return:
- def filter_cache(self, **kwargs... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class FireHydrantModelManager:
def get_once(self, pk):
"""缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:"""
<|body_0|>
def all_cache(self):
"""全部缓存 :return:"""
<|body_1|>
def filter_cache(self, **kwargs):
"""过滤缓存 :param kwargs: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FireHydrantModelManager:
def get_once(self, pk):
"""缓存中获取一条记录 若无则从数据库获取 替代model中get方法 :param pk: :return:"""
if pk is None or pk == '':
return None
table_name = self.model._meta.db_table
cache = FireHydrantCacheFactory(('model_cache', table_name))
obj = cach... | the_stack_v2_python_sparse | FireHydrant/common/core/dao/cache/model_manager.py | shoogoome/FireHydrant | train | 4 | |
b42c07f88503ce66125b1ef19ecd24906a5ab3ae | [
"df = pd.DataFrame()\nfor each in snp_lines:\n line = each.strip().split('\\t')\n col_name = line[0] + ':' + line[1]\n line = line[9:]\n col = np.zeros(53)\n for i in range(53):\n if line[i][0] == '.':\n col[i] = np.nan\n else:\n col[i] = int(line[i][0]) + int(line... | <|body_start_0|>
df = pd.DataFrame()
for each in snp_lines:
line = each.strip().split('\t')
col_name = line[0] + ':' + line[1]
line = line[9:]
col = np.zeros(53)
for i in range(53):
if line[i][0] == '.':
col[... | Lab3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lab3:
def create_data(self, snp_lines):
"""Input - the snp_lines parsed at the beginning of the notebook Output - You should return the 53 x 3902 dataframe"""
<|body_0|>
def create_target(self, header_line):
"""Input - the header_line parsed at the beginning of the n... | stack_v2_sparse_classes_36k_train_009046 | 2,413 | no_license | [
{
"docstring": "Input - the snp_lines parsed at the beginning of the notebook Output - You should return the 53 x 3902 dataframe",
"name": "create_data",
"signature": "def create_data(self, snp_lines)"
},
{
"docstring": "Input - the header_line parsed at the beginning of the notebook Output - a ... | 4 | null | Implement the Python class `Lab3` described below.
Class description:
Implement the Lab3 class.
Method signatures and docstrings:
- def create_data(self, snp_lines): Input - the snp_lines parsed at the beginning of the notebook Output - You should return the 53 x 3902 dataframe
- def create_target(self, header_line):... | Implement the Python class `Lab3` described below.
Class description:
Implement the Lab3 class.
Method signatures and docstrings:
- def create_data(self, snp_lines): Input - the snp_lines parsed at the beginning of the notebook Output - You should return the 53 x 3902 dataframe
- def create_target(self, header_line):... | adcb6b47164a909fe8b3cd3969c8bc3f3696893a | <|skeleton|>
class Lab3:
def create_data(self, snp_lines):
"""Input - the snp_lines parsed at the beginning of the notebook Output - You should return the 53 x 3902 dataframe"""
<|body_0|>
def create_target(self, header_line):
"""Input - the header_line parsed at the beginning of the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lab3:
def create_data(self, snp_lines):
"""Input - the snp_lines parsed at the beginning of the notebook Output - You should return the 53 x 3902 dataframe"""
df = pd.DataFrame()
for each in snp_lines:
line = each.strip().split('\t')
col_name = line[0] + ':' + l... | the_stack_v2_python_sparse | ECE365/Genomics/lab3/main.py | RickyL-2000/ZJUI-lib | train | 1 | |
981cbbdd08c7f298503e93945bdaf3778d094af7 | [
"dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]\nfor i in range(len(text1)):\n for j in range(len(text2)):\n if text1[i] == text2[j]:\n dp[i + 1][j + 1] = dp[i][j] + 1\n else:\n dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])\nreturn dp[-1][-1]",
... | <|body_start_0|>
dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]
for i in range(len(text1)):
for j in range(len(text2)):
if text1[i] == text2[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonSubsequence2(self, text1: str, text2: str) -> int:
"""CREATED AT: 2022/1/21 Runtime: 436 ms, faster than 66.06% Memory Usage: 22.7 MB, less than 55.90% 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters. :param ... | stack_v2_sparse_classes_36k_train_009047 | 2,788 | permissive | [
{
"docstring": "CREATED AT: 2022/1/21 Runtime: 436 ms, faster than 66.06% Memory Usage: 22.7 MB, less than 55.90% 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters. :param text1: :param text2: :return:",
"name": "longestCommonSubsequence2",
"signature":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence2(self, text1: str, text2: str) -> int: CREATED AT: 2022/1/21 Runtime: 436 ms, faster than 66.06% Memory Usage: 22.7 MB, less than 55.90% 1 <= text1.l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence2(self, text1: str, text2: str) -> int: CREATED AT: 2022/1/21 Runtime: 436 ms, faster than 66.06% Memory Usage: 22.7 MB, less than 55.90% 1 <= text1.l... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def longestCommonSubsequence2(self, text1: str, text2: str) -> int:
"""CREATED AT: 2022/1/21 Runtime: 436 ms, faster than 66.06% Memory Usage: 22.7 MB, less than 55.90% 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters. :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonSubsequence2(self, text1: str, text2: str) -> int:
"""CREATED AT: 2022/1/21 Runtime: 436 ms, faster than 66.06% Memory Usage: 22.7 MB, less than 55.90% 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters. :param text1: :param ... | the_stack_v2_python_sparse | src/1143-LongestCommonSubsequence.py | Jiezhi/myleetcode | train | 1 | |
a5e8ec4c0be24f38045ace7e8e0b7ec77282b4aa | [
"self.rulesDisplay = rulesDisplay\nself.new_rule_root = Toplevel()\nself.new_rule_root.title(\"Création d'une nouvelle règle\")\nLabel(self.new_rule_root, text='Conditions :').grid(row=0, padx='0.3c')\nLabel(self.new_rule_root, text='Conclusions :').grid(row=0, column=2, padx='0.3c', sticky=E)\nself.condition_vars ... | <|body_start_0|>
self.rulesDisplay = rulesDisplay
self.new_rule_root = Toplevel()
self.new_rule_root.title("Création d'une nouvelle règle")
Label(self.new_rule_root, text='Conditions :').grid(row=0, padx='0.3c')
Label(self.new_rule_root, text='Conclusions :').grid(row=0, column=2... | RuleCreation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuleCreation:
def __init__(self, rulesDisplay):
"""Allows the user to create a new rule. The user has to select the condition and the conclusions among the facts, and to write a description before validating the creation of the rule."""
<|body_0|>
def validate(self):
... | stack_v2_sparse_classes_36k_train_009048 | 7,078 | no_license | [
{
"docstring": "Allows the user to create a new rule. The user has to select the condition and the conclusions among the facts, and to write a description before validating the creation of the rule.",
"name": "__init__",
"signature": "def __init__(self, rulesDisplay)"
},
{
"docstring": "This fun... | 2 | stack_v2_sparse_classes_30k_train_013651 | Implement the Python class `RuleCreation` described below.
Class description:
Implement the RuleCreation class.
Method signatures and docstrings:
- def __init__(self, rulesDisplay): Allows the user to create a new rule. The user has to select the condition and the conclusions among the facts, and to write a descripti... | Implement the Python class `RuleCreation` described below.
Class description:
Implement the RuleCreation class.
Method signatures and docstrings:
- def __init__(self, rulesDisplay): Allows the user to create a new rule. The user has to select the condition and the conclusions among the facts, and to write a descripti... | 989f4050816d1241e41e36e4e6d95784ff4dff1c | <|skeleton|>
class RuleCreation:
def __init__(self, rulesDisplay):
"""Allows the user to create a new rule. The user has to select the condition and the conclusions among the facts, and to write a description before validating the creation of the rule."""
<|body_0|>
def validate(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuleCreation:
def __init__(self, rulesDisplay):
"""Allows the user to create a new rule. The user has to select the condition and the conclusions among the facts, and to write a description before validating the creation of the rule."""
self.rulesDisplay = rulesDisplay
self.new_rule_ro... | the_stack_v2_python_sparse | User_interface/UI_Rules.py | brieglhostis/ExpertSystems | train | 0 | |
f11fad5d26a3d7de11b0c8786cb45d46bbf3a547 | [
"self.hostname = ip\nself.username = username\nself.password = password\nself.port = port\nself.conn_timeout = conn_timeout\nself.key_filename = key_filename",
"_ssh = my_pxssh(ip=self.hostname, username=self.username, timeout=self.conn_timeout, maxread=5000, options={'StrictHostKeyChecking': 'no', 'UserKnownHost... | <|body_start_0|>
self.hostname = ip
self.username = username
self.password = password
self.port = port
self.conn_timeout = conn_timeout
self.key_filename = key_filename
<|end_body_0|>
<|body_start_1|>
_ssh = my_pxssh(ip=self.hostname, username=self.username, time... | PXSSH_Factory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PXSSH_Factory:
def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None):
""":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径"""
<|body_0|>
def create(self, retry=... | stack_v2_sparse_classes_36k_train_009049 | 8,958 | no_license | [
{
"docstring": ":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径",
"name": "__init__",
"signature": "def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None)"
},
{
"docstring": "创建pxs... | 2 | stack_v2_sparse_classes_30k_train_009566 | Implement the Python class `PXSSH_Factory` described below.
Class description:
Implement the PXSSH_Factory class.
Method signatures and docstrings:
- def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None): :param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时... | Implement the Python class `PXSSH_Factory` described below.
Class description:
Implement the PXSSH_Factory class.
Method signatures and docstrings:
- def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None): :param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时... | 9e66f5e62214e566528003d434ef2b74877419fd | <|skeleton|>
class PXSSH_Factory:
def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None):
""":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径"""
<|body_0|>
def create(self, retry=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PXSSH_Factory:
def __init__(self, ip, username, port, conn_timeout, password=None, key_filename=None):
""":param ip: 主机ip :param username: 登录用户名 :param port: 端口号 :param conn_timeout: 超时时间 :param password: 登录密码 :param key_filename: 登录密钥路径"""
self.hostname = ip
self.username = username
... | the_stack_v2_python_sparse | utils/deploy.py | seekplum/seekplum | train | 2 | |
08edbbd780a3bb748e04bd7ad35b5e161c726fb0 | [
"super(StatModOnStatusAbility, self).__init__(name)\nself.stat = stat\nself.mod = mod",
"messages = []\nstatus.statMods[self.stat] = self.mod\nmessages = [pkmn.getHeader() + \" raised it's \" + self.stat + '.']\nreturn messages"
] | <|body_start_0|>
super(StatModOnStatusAbility, self).__init__(name)
self.stat = stat
self.mod = mod
<|end_body_0|>
<|body_start_1|>
messages = []
status.statMods[self.stat] = self.mod
messages = [pkmn.getHeader() + " raised it's " + self.stat + '.']
return messag... | An ability that modifies a stat when the parent receives a status | StatModOnStatusAbility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatModOnStatusAbility:
"""An ability that modifies a stat when the parent receives a status"""
def __init__(self, name, stat, mod):
"""Builds the Ability"""
<|body_0|>
def onStatus(self, pkmn, status):
"""Alter the statMods of the Status to reflect the abilities... | stack_v2_sparse_classes_36k_train_009050 | 649 | no_license | [
{
"docstring": "Builds the Ability",
"name": "__init__",
"signature": "def __init__(self, name, stat, mod)"
},
{
"docstring": "Alter the statMods of the Status to reflect the abilities effect",
"name": "onStatus",
"signature": "def onStatus(self, pkmn, status)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014645 | Implement the Python class `StatModOnStatusAbility` described below.
Class description:
An ability that modifies a stat when the parent receives a status
Method signatures and docstrings:
- def __init__(self, name, stat, mod): Builds the Ability
- def onStatus(self, pkmn, status): Alter the statMods of the Status to ... | Implement the Python class `StatModOnStatusAbility` described below.
Class description:
An ability that modifies a stat when the parent receives a status
Method signatures and docstrings:
- def __init__(self, name, stat, mod): Builds the Ability
- def onStatus(self, pkmn, status): Alter the statMods of the Status to ... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class StatModOnStatusAbility:
"""An ability that modifies a stat when the parent receives a status"""
def __init__(self, name, stat, mod):
"""Builds the Ability"""
<|body_0|>
def onStatus(self, pkmn, status):
"""Alter the statMods of the Status to reflect the abilities... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatModOnStatusAbility:
"""An ability that modifies a stat when the parent receives a status"""
def __init__(self, name, stat, mod):
"""Builds the Ability"""
super(StatModOnStatusAbility, self).__init__(name)
self.stat = stat
self.mod = mod
def onStatus(self, pkmn, st... | the_stack_v2_python_sparse | src/Pokemon/Abilities/statmodonstatus_ability.py | sgtnourry/Pokemon-Project | train | 0 |
58fbd41101fb1067638c898c0f5a0402d3443e63 | [
"test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))]\nfor test_case in test_cases:\n multiples = multiples_of_x_below_y(test_case[1][0], test_case[1][1])\n self.assertEqual(multiples, test_case[0])",
"test_case = (23, [3, 5], 10)\nsum_solution = solution(test_case[1], test_case[2])\nself.assertEqual(sum_sol... | <|body_start_0|>
test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))]
for test_case in test_cases:
multiples = multiples_of_x_below_y(test_case[1][0], test_case[1][1])
self.assertEqual(multiples, test_case[0])
<|end_body_0|>
<|body_start_1|>
test_case = (23, [3, 5], 10)
... | Test0001 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test0001:
def test_multiples_of_x_below_y_examples(self):
"""it should get the example correct"""
<|body_0|>
def test_solution_example(self):
"""it should get the example correct"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_cases = [([3, 6, ... | stack_v2_sparse_classes_36k_train_009051 | 691 | no_license | [
{
"docstring": "it should get the example correct",
"name": "test_multiples_of_x_below_y_examples",
"signature": "def test_multiples_of_x_below_y_examples(self)"
},
{
"docstring": "it should get the example correct",
"name": "test_solution_example",
"signature": "def test_solution_exampl... | 2 | stack_v2_sparse_classes_30k_test_000699 | Implement the Python class `Test0001` described below.
Class description:
Implement the Test0001 class.
Method signatures and docstrings:
- def test_multiples_of_x_below_y_examples(self): it should get the example correct
- def test_solution_example(self): it should get the example correct | Implement the Python class `Test0001` described below.
Class description:
Implement the Test0001 class.
Method signatures and docstrings:
- def test_multiples_of_x_below_y_examples(self): it should get the example correct
- def test_solution_example(self): it should get the example correct
<|skeleton|>
class Test000... | 9687b709385a23d36bd8a24af16aaf7f375f4818 | <|skeleton|>
class Test0001:
def test_multiples_of_x_below_y_examples(self):
"""it should get the example correct"""
<|body_0|>
def test_solution_example(self):
"""it should get the example correct"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test0001:
def test_multiples_of_x_below_y_examples(self):
"""it should get the example correct"""
test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))]
for test_case in test_cases:
multiples = multiples_of_x_below_y(test_case[1][0], test_case[1][1])
self.assertEqu... | the_stack_v2_python_sparse | problem_0001/python/test.py | mleue/project_euler | train | 0 | |
f3745ef442ea5f46ba2e7c56a3eb78963cd2a3f5 | [
"n = len(s)\nif n < 2:\n return 0\nminCuts = [l - 1 for l in range(n + 1)]\nfor i in range(n):\n j = 0\n while j <= i and i + j < n and (s[i - j] == s[i + j]):\n minCuts[i + j + 1] = min(minCuts[i + j + 1], 1 + minCuts[i - j])\n j += 1\n j = 1\n while j <= i + 1 and i + j < n and (s[i -... | <|body_start_0|>
n = len(s)
if n < 2:
return 0
minCuts = [l - 1 for l in range(n + 1)]
for i in range(n):
j = 0
while j <= i and i + j < n and (s[i - j] == s[i + j]):
minCuts[i + j + 1] = min(minCuts[i + j + 1], 1 + minCuts[i - j])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCut(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def minCut2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def minCut4(self, s):
""":type s: str :rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009052 | 3,902 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "minCut",
"signature": "def minCut(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "minCut2",
"signature": "def minCut2(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "minCut4",
"signature... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int
- def minCut2(self, s): :type s: str :rtype: int
- def minCut4(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int
- def minCut2(self, s): :type s: str :rtype: int
- def minCut4(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def minCut(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def minCut2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def minCut4(self, s):
""":type s: str :rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCut(self, s):
""":type s: str :rtype: int"""
n = len(s)
if n < 2:
return 0
minCuts = [l - 1 for l in range(n + 1)]
for i in range(n):
j = 0
while j <= i and i + j < n and (s[i - j] == s[i + j]):
minCut... | the_stack_v2_python_sparse | code132PalindromePartitioningII.py | cybelewang/leetcode-python | train | 0 | |
bec6830c1157023a9cb882f277b89814383e8598 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | InstanceServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Get(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def List(self, request, context):
"""Missing associated documentatio... | stack_v2_sparse_classes_36k_train_009053 | 5,203 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "List",
"signature": "def List(self, request, context)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000700 | Implement the Python class `InstanceServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Get(self, request, context): Missing associated documentation comment in .proto file.
- def List(self, request, context): Missing as... | Implement the Python class `InstanceServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Get(self, request, context): Missing associated documentation comment in .proto file.
- def List(self, request, context): Missing as... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class InstanceServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Get(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def List(self, request, context):
"""Missing associated documentatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Get(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | yandex/cloud/marketplace/licensemanager/v1/instance_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
eb483c5b0ac940b8f4f7bee78cf8476a8757352b | [
"contribution = self.get_contribution(request.user, project_id, contribution_id)\ncomment = self.get_comment(contribution, comment_id)\nreturn self.update_and_respond(request, contribution, comment)",
"contribution = self.get_contribution(request.user, project_id, contribution_id)\ncomment = self.get_comment(cont... | <|body_start_0|>
contribution = self.get_contribution(request.user, project_id, contribution_id)
comment = self.get_comment(contribution, comment_id)
return self.update_and_respond(request, contribution, comment)
<|end_body_0|>
<|body_start_1|>
contribution = self.get_contribution(reque... | Public API for a single comment. | SingleCommentAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleCommentAPIView:
"""Public API for a single comment."""
def patch(self, request, project_id, contribution_id, comment_id):
"""Handle PATCH request. Update the comment. Parameters ---------- request : rest_framework.request.Request Object representing the request. project_id : in... | stack_v2_sparse_classes_36k_train_009054 | 11,610 | permissive | [
{
"docstring": "Handle PATCH request. Update the comment. Parameters ---------- request : rest_framework.request.Request Object representing the request. project_id : int Identifies the project in the database. contribution_id : int Identifies the contribution in the database. comment_id : int Identifies the co... | 2 | stack_v2_sparse_classes_30k_train_012950 | Implement the Python class `SingleCommentAPIView` described below.
Class description:
Public API for a single comment.
Method signatures and docstrings:
- def patch(self, request, project_id, contribution_id, comment_id): Handle PATCH request. Update the comment. Parameters ---------- request : rest_framework.request... | Implement the Python class `SingleCommentAPIView` described below.
Class description:
Public API for a single comment.
Method signatures and docstrings:
- def patch(self, request, project_id, contribution_id, comment_id): Handle PATCH request. Update the comment. Parameters ---------- request : rest_framework.request... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class SingleCommentAPIView:
"""Public API for a single comment."""
def patch(self, request, project_id, contribution_id, comment_id):
"""Handle PATCH request. Update the comment. Parameters ---------- request : rest_framework.request.Request Object representing the request. project_id : in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleCommentAPIView:
"""Public API for a single comment."""
def patch(self, request, project_id, contribution_id, comment_id):
"""Handle PATCH request. Update the comment. Parameters ---------- request : rest_framework.request.Request Object representing the request. project_id : int Identifies ... | the_stack_v2_python_sparse | geokey/contributions/views/comments.py | NeolithEra/geokey | train | 0 |
e3d62106c02d59548f1d722e512d7b05d001b844 | [
"values = self.do_version_changes_for_db()\nvalues['initial_version'] = values['current_version']\ndb_fwcmp = self.dbapi.create_firmware_component(values)\nself._from_db_object(self._context, self, db_fwcmp)",
"updates = self.do_version_changes_for_db()\nup_fwcmp = self.dbapi.update_firmware_component(self.node_i... | <|body_start_0|>
values = self.do_version_changes_for_db()
values['initial_version'] = values['current_version']
db_fwcmp = self.dbapi.create_firmware_component(values)
self._from_db_object(self._context, self, db_fwcmp)
<|end_body_0|>
<|body_start_1|>
updates = self.do_version_... | FirmwareComponent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirmwareComponent:
def create(self, context=None):
"""Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists."""
<|body_0|>
def save(self, cont... | stack_v2_sparse_classes_36k_train_009055 | 6,237 | permissive | [
{
"docstring": "Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists.",
"name": "create",
"signature": "def create(self, context=None)"
},
{
"docstring": "Save up... | 3 | null | Implement the Python class `FirmwareComponent` described below.
Class description:
Implement the FirmwareComponent class.
Method signatures and docstrings:
- def create(self, context=None): Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: F... | Implement the Python class `FirmwareComponent` described below.
Class description:
Implement the FirmwareComponent class.
Method signatures and docstrings:
- def create(self, context=None): Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: F... | ab76ff12e1c3c2208455e917f1a40d4000b4e990 | <|skeleton|>
class FirmwareComponent:
def create(self, context=None):
"""Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists."""
<|body_0|>
def save(self, cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirmwareComponent:
def create(self, context=None):
"""Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists."""
values = self.do_version_changes_for_db()
... | the_stack_v2_python_sparse | ironic/objects/firmware.py | openstack/ironic | train | 411 | |
ca60386c219f28e2a6cc022b98731172f1ae6bc0 | [
"self.sum_matrix = [[0] * len(matrix[0]) for j in range(len(matrix))]\nself.matrix = matrix\nfor i in range(len(matrix)):\n summ = 0\n for j in range(len(matrix[0])):\n summ += matrix[i][j]\n self.sum_matrix[i][j] = summ",
"diff = val - self.matrix[row][col]\nself.matrix[row][col] = val\nfor i... | <|body_start_0|>
self.sum_matrix = [[0] * len(matrix[0]) for j in range(len(matrix))]
self.matrix = matrix
for i in range(len(matrix)):
summ = 0
for j in range(len(matrix[0])):
summ += matrix[i][j]
self.sum_matrix[i][j] = summ
<|end_body_0|... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k_train_009056 | 2,415 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | stack_v2_sparse_classes_30k_train_002857 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | 6e4894c2d80413b13dc247d1783afd709ad984c8 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.sum_matrix = [[0] * len(matrix[0]) for j in range(len(matrix))]
self.matrix = matrix
for i in range(len(matrix)):
summ = 0
for j in range(len(matrix[0])):
sum... | the_stack_v2_python_sparse | leet_code308.py | tejamupparaju/LeetCode_Python | train | 2 | |
e058866aab8b0d075db8236bb6da253417dfcecc | [
"with self.assertRaisesRegex(TypeError, 'cirq.Sampler is required for sampled expectation.'):\n cirq_ops._get_cirq_sampled_expectation('junk')\ncirq_ops._get_cirq_sampled_expectation()\ncirq_ops._get_cirq_sampled_expectation(cirq.Simulator())\ncirq_ops._get_cirq_sampled_expectation(cirq.DensityMatrixSimulator())... | <|body_start_0|>
with self.assertRaisesRegex(TypeError, 'cirq.Sampler is required for sampled expectation.'):
cirq_ops._get_cirq_sampled_expectation('junk')
cirq_ops._get_cirq_sampled_expectation()
cirq_ops._get_cirq_sampled_expectation(cirq.Simulator())
cirq_ops._get_cirq_sa... | Tests get_cirq_sampled_expectation. | CirqSampledExpectationTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CirqSampledExpectationTest:
"""Tests get_cirq_sampled_expectation."""
def test_get_cirq_sampled_expectation_op(self):
"""Input check the wrapper for the cirq analytical expectation op."""
<|body_0|>
def test_cirq_sampled_expectation_op_inputs(self):
"""test input... | stack_v2_sparse_classes_36k_train_009057 | 23,553 | permissive | [
{
"docstring": "Input check the wrapper for the cirq analytical expectation op.",
"name": "test_get_cirq_sampled_expectation_op",
"signature": "def test_get_cirq_sampled_expectation_op(self)"
},
{
"docstring": "test input checking in the state sim op.",
"name": "test_cirq_sampled_expectation... | 4 | stack_v2_sparse_classes_30k_train_004389 | Implement the Python class `CirqSampledExpectationTest` described below.
Class description:
Tests get_cirq_sampled_expectation.
Method signatures and docstrings:
- def test_get_cirq_sampled_expectation_op(self): Input check the wrapper for the cirq analytical expectation op.
- def test_cirq_sampled_expectation_op_inp... | Implement the Python class `CirqSampledExpectationTest` described below.
Class description:
Tests get_cirq_sampled_expectation.
Method signatures and docstrings:
- def test_get_cirq_sampled_expectation_op(self): Input check the wrapper for the cirq analytical expectation op.
- def test_cirq_sampled_expectation_op_inp... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class CirqSampledExpectationTest:
"""Tests get_cirq_sampled_expectation."""
def test_get_cirq_sampled_expectation_op(self):
"""Input check the wrapper for the cirq analytical expectation op."""
<|body_0|>
def test_cirq_sampled_expectation_op_inputs(self):
"""test input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CirqSampledExpectationTest:
"""Tests get_cirq_sampled_expectation."""
def test_get_cirq_sampled_expectation_op(self):
"""Input check the wrapper for the cirq analytical expectation op."""
with self.assertRaisesRegex(TypeError, 'cirq.Sampler is required for sampled expectation.'):
... | the_stack_v2_python_sparse | tensorflow_quantum/core/ops/cirq_ops_test.py | tensorflow/quantum | train | 1,799 |
bb843bb6bef400bc30e7719b07aebbff6ded8cb2 | [
"def is_prims(n):\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n < 2:\n return False\n for i in range(3, int(n ** 0.5) + 1, 2):\n if n % i == 0:\n return False\n return True\nans = 0\nfor i in range(2, n):\n if is_prims(i) == True:\n ans += 1\nprint(a... | <|body_start_0|>
def is_prims(n):
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
ans... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes_TLE(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def is_prims(n):
if n == 2 or n == 3:
... | stack_v2_sparse_classes_36k_train_009058 | 1,762 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes_TLE",
"signature": "def countPrimes_TLE(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes_TLE(self, n): :type n: int :rtype: int
- def countPrimes(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes_TLE(self, n): :type n: int :rtype: int
- def countPrimes(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def countPrimes_TLE(self, n):
... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def countPrimes_TLE(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimes_TLE(self, n):
""":type n: int :rtype: int"""
def is_prims(n):
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i ==... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00204.Count Primes.py | roger6blog/LeetCode | train | 0 | |
abba8f84e256d582a94f4ecf3ecd451f8bdadc25 | [
"out_x = u_x * scale_x - u_y * scale_y + shift_x\nout_y = u_x * scale_y + u_y * scale_x + shift_y\nreturn (out_x, out_y)",
"norm2 = self.get_square_norm(u)\neps = 1e-07\nout = ops.sqrt(norm2 + eps)\nreturn out",
"u_r, u_i = get_real_and_imag(u)\nout = u_r ** 2 + u_i ** 2\nreturn out"
] | <|body_start_0|>
out_x = u_x * scale_x - u_y * scale_y + shift_x
out_y = u_x * scale_y + u_y * scale_x + shift_y
return (out_x, out_y)
<|end_body_0|>
<|body_start_1|>
norm2 = self.get_square_norm(u)
eps = 1e-07
out = ops.sqrt(norm2 + eps)
return out
<|end_body_1|... | The implementor class of the Batch Normalization layer for complex numbers. Implements the functionality specific to complex numbers and needed by the 'BatchNorm' class. This includes: getting the norm of complex number, applying scaling and shift to a complex tensor, and updating the running mean and variance, which a... | _BatchNormImpl | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BatchNormImpl:
"""The implementor class of the Batch Normalization layer for complex numbers. Implements the functionality specific to complex numbers and needed by the 'BatchNorm' class. This includes: getting the norm of complex number, applying scaling and shift to a complex tensor, and updat... | stack_v2_sparse_classes_36k_train_009059 | 7,025 | permissive | [
{
"docstring": "Applies complex scaling and shift to an input tensor. This function implements the operation as: .. math:: \\\\begin{align} \\\\text{Re(out)} = \\\\text{Re(inp)} * \\\\text{Re(scale)} - \\\\text{Im(inp)} * \\\\text{Im(scale)} + \\\\text{Re(shift)}\\\\\\\\ \\\\text{Im(out)} = \\\\text{Re(inp)} * ... | 3 | stack_v2_sparse_classes_30k_train_013984 | Implement the Python class `_BatchNormImpl` described below.
Class description:
The implementor class of the Batch Normalization layer for complex numbers. Implements the functionality specific to complex numbers and needed by the 'BatchNorm' class. This includes: getting the norm of complex number, applying scaling a... | Implement the Python class `_BatchNormImpl` described below.
Class description:
The implementor class of the Batch Normalization layer for complex numbers. Implements the functionality specific to complex numbers and needed by the 'BatchNorm' class. This includes: getting the norm of complex number, applying scaling a... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class _BatchNormImpl:
"""The implementor class of the Batch Normalization layer for complex numbers. Implements the functionality specific to complex numbers and needed by the 'BatchNorm' class. This includes: getting the norm of complex number, applying scaling and shift to a complex tensor, and updat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _BatchNormImpl:
"""The implementor class of the Batch Normalization layer for complex numbers. Implements the functionality specific to complex numbers and needed by the 'BatchNorm' class. This includes: getting the norm of complex number, applying scaling and shift to a complex tensor, and updating the runni... | the_stack_v2_python_sparse | mindspore/python/mindspore/hypercomplex/complex/_complex_bn_impl.py | mindspore-ai/mindspore | train | 4,178 |
9cd0135cb6904e5f4cf3a98c28e5434a5d4ed692 | [
"super(SmallNetworkEmbedder, self).__init__(*args, **kwargs)\nself._params = params\nif len(self._params.conv_sizes) != len(self._params.conv_strides):\n raise ValueError('Conv sizes and strides should have the same length: {} != {}'.format(len(self._params.conv_sizes), len(self._params.conv_strides)))\nif len(s... | <|body_start_0|>
super(SmallNetworkEmbedder, self).__init__(*args, **kwargs)
self._params = params
if len(self._params.conv_sizes) != len(self._params.conv_strides):
raise ValueError('Conv sizes and strides should have the same length: {} != {}'.format(len(self._params.conv_sizes), l... | Embedder for image like observations. The network is comprised of multiple conv layers and a fully connected layer at the end. The number of conv layers and the parameters are configured from params. | SmallNetworkEmbedder | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmallNetworkEmbedder:
"""Embedder for image like observations. The network is comprised of multiple conv layers and a fully connected layer at the end. The number of conv layers and the parameters are configured from params."""
def __init__(self, params, *args, **kwargs):
"""Construc... | stack_v2_sparse_classes_36k_train_009060 | 19,820 | permissive | [
{
"docstring": "Constructs the small network. Args: params: params should be tf.hparams type. params need to have a list of conv_sizes, conv_strides, conv_channels. The length of these lists should be equal to each other and to the number of conv layers in the network. Plus, it also needs to have boolean variab... | 2 | stack_v2_sparse_classes_30k_train_005524 | Implement the Python class `SmallNetworkEmbedder` described below.
Class description:
Embedder for image like observations. The network is comprised of multiple conv layers and a fully connected layer at the end. The number of conv layers and the parameters are configured from params.
Method signatures and docstrings... | Implement the Python class `SmallNetworkEmbedder` described below.
Class description:
Embedder for image like observations. The network is comprised of multiple conv layers and a fully connected layer at the end. The number of conv layers and the parameters are configured from params.
Method signatures and docstrings... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class SmallNetworkEmbedder:
"""Embedder for image like observations. The network is comprised of multiple conv layers and a fully connected layer at the end. The number of conv layers and the parameters are configured from params."""
def __init__(self, params, *args, **kwargs):
"""Construc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmallNetworkEmbedder:
"""Embedder for image like observations. The network is comprised of multiple conv layers and a fully connected layer at the end. The number of conv layers and the parameters are configured from params."""
def __init__(self, params, *args, **kwargs):
"""Constructs the small ... | the_stack_v2_python_sparse | models/research/cognitive_planning/embedders.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
7ebda500248d54f5add0d09827042319d06ae3ac | [
"items = S3File.objects.all()\nfor item in items.all():\n item.delete()",
"try:\n return S3File.objects.get(pk=pk)\nexcept S3File.DoesNotExist:\n return None",
"pk_string = django_unsign(signed_pk)\npk = int_or_none(pk_string)\ntry:\n return self.get(pk=pk)\nexcept S3File.DoesNotExist:\n return N... | <|body_start_0|>
items = S3File.objects.all()
for item in items.all():
item.delete()
<|end_body_0|>
<|body_start_1|>
try:
return S3File.objects.get(pk=pk)
except S3File.DoesNotExist:
return None
<|end_body_1|>
<|body_start_2|>
pk_string = dja... | S3FileManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3FileManager:
def delete_all(self):
"""Utility function will delete all the S3 files in our system."""
<|body_0|>
def get_by_pk_or_none(self, pk):
"""Helper function which gets the S3File object by PK parameter or returns None result."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_009061 | 4,649 | permissive | [
{
"docstring": "Utility function will delete all the S3 files in our system.",
"name": "delete_all",
"signature": "def delete_all(self)"
},
{
"docstring": "Helper function which gets the S3File object by PK parameter or returns None result.",
"name": "get_by_pk_or_none",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_008206 | Implement the Python class `S3FileManager` described below.
Class description:
Implement the S3FileManager class.
Method signatures and docstrings:
- def delete_all(self): Utility function will delete all the S3 files in our system.
- def get_by_pk_or_none(self, pk): Helper function which gets the S3File object by PK... | Implement the Python class `S3FileManager` described below.
Class description:
Implement the S3FileManager class.
Method signatures and docstrings:
- def delete_all(self): Utility function will delete all the S3 files in our system.
- def get_by_pk_or_none(self, pk): Helper function which gets the S3File object by PK... | 053973b5ff0b997c52bfaca8daf8e07db64a877c | <|skeleton|>
class S3FileManager:
def delete_all(self):
"""Utility function will delete all the S3 files in our system."""
<|body_0|>
def get_by_pk_or_none(self, pk):
"""Helper function which gets the S3File object by PK parameter or returns None result."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3FileManager:
def delete_all(self):
"""Utility function will delete all the S3 files in our system."""
items = S3File.objects.all()
for item in items.all():
item.delete()
def get_by_pk_or_none(self, pk):
"""Helper function which gets the S3File object by PK pa... | the_stack_v2_python_sparse | foundation_tenant/models/base/s3file.py | smegurus/smegurus-django | train | 1 | |
1c1b82100347c7d5685323da29ec708632fbd7b6 | [
"job = get_object_or_404(models.ImportJob, id=job_id)\nif job.user != request.user:\n raise PermissionDenied()\nitems = job.items.order_by('index').filter(fail_reason__isnull=False, book_guess__isnull=True)\npaginated = Paginator(items, PAGE_LENGTH)\npage = paginated.get_page(request.GET.get('page'))\ndata = {'j... | <|body_start_0|>
job = get_object_or_404(models.ImportJob, id=job_id)
if job.user != request.user:
raise PermissionDenied()
items = job.items.order_by('index').filter(fail_reason__isnull=False, book_guess__isnull=True)
paginated = Paginator(items, PAGE_LENGTH)
page = ... | problems items in an existing import | ImportTroubleshoot | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportTroubleshoot:
"""problems items in an existing import"""
def get(self, request, job_id):
"""status of an import job"""
<|body_0|>
def post(self, request, job_id):
"""retry lines from an import"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009062 | 1,935 | no_license | [
{
"docstring": "status of an import job",
"name": "get",
"signature": "def get(self, request, job_id)"
},
{
"docstring": "retry lines from an import",
"name": "post",
"signature": "def post(self, request, job_id)"
}
] | 2 | null | Implement the Python class `ImportTroubleshoot` described below.
Class description:
problems items in an existing import
Method signatures and docstrings:
- def get(self, request, job_id): status of an import job
- def post(self, request, job_id): retry lines from an import | Implement the Python class `ImportTroubleshoot` described below.
Class description:
problems items in an existing import
Method signatures and docstrings:
- def get(self, request, job_id): status of an import job
- def post(self, request, job_id): retry lines from an import
<|skeleton|>
class ImportTroubleshoot:
... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class ImportTroubleshoot:
"""problems items in an existing import"""
def get(self, request, job_id):
"""status of an import job"""
<|body_0|>
def post(self, request, job_id):
"""retry lines from an import"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImportTroubleshoot:
"""problems items in an existing import"""
def get(self, request, job_id):
"""status of an import job"""
job = get_object_or_404(models.ImportJob, id=job_id)
if job.user != request.user:
raise PermissionDenied()
items = job.items.order_by('i... | the_stack_v2_python_sparse | bookwyrm/views/imports/troubleshoot.py | bookwyrm-social/bookwyrm | train | 1,398 |
94bb9db79a1b08a4cb848edc1687c736264a0b84 | [
"if not hasattr(settings, self.settings_attr):\n raise ImproperlyConfigured(\"Settings doesn't define {}. This is required when using a FileSystemFinder.\".format(self.settings_attr))\nself.paths = getattr(settings, self.settings_attr)",
"if getattr(self, 'settings_attr', None):\n self.paths = getattr(setti... | <|body_start_0|>
if not hasattr(settings, self.settings_attr):
raise ImproperlyConfigured("Settings doesn't define {}. This is required when using a FileSystemFinder.".format(self.settings_attr))
self.paths = getattr(settings, self.settings_attr)
<|end_body_0|>
<|body_start_1|>
if g... | Base class for searching filesystem directories | BaseFilesystemFinder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFilesystemFinder:
"""Base class for searching filesystem directories"""
def __init__(self):
"""Initialize finder class by looking up the paths referenced in ``settings_attr``."""
<|body_0|>
def find(self, path: Path) -> Path:
"""Finds a file in the configured... | stack_v2_sparse_classes_36k_train_009063 | 3,204 | permissive | [
{
"docstring": "Initialize finder class by looking up the paths referenced in ``settings_attr``.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Finds a file in the configured paths returning its absolute path. Args: path (pathlib.Path): The path to find Returns: The a... | 2 | null | Implement the Python class `BaseFilesystemFinder` described below.
Class description:
Base class for searching filesystem directories
Method signatures and docstrings:
- def __init__(self): Initialize finder class by looking up the paths referenced in ``settings_attr``.
- def find(self, path: Path) -> Path: Finds a f... | Implement the Python class `BaseFilesystemFinder` described below.
Class description:
Base class for searching filesystem directories
Method signatures and docstrings:
- def __init__(self): Initialize finder class by looking up the paths referenced in ``settings_attr``.
- def find(self, path: Path) -> Path: Finds a f... | 200f2b9ea8b350b0ac9bb6a2d24310c0d8227794 | <|skeleton|>
class BaseFilesystemFinder:
"""Base class for searching filesystem directories"""
def __init__(self):
"""Initialize finder class by looking up the paths referenced in ``settings_attr``."""
<|body_0|>
def find(self, path: Path) -> Path:
"""Finds a file in the configured... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFilesystemFinder:
"""Base class for searching filesystem directories"""
def __init__(self):
"""Initialize finder class by looking up the paths referenced in ``settings_attr``."""
if not hasattr(settings, self.settings_attr):
raise ImproperlyConfigured("Settings doesn't def... | the_stack_v2_python_sparse | moderngl_window/finders/base.py | moderngl/moderngl-window | train | 205 |
a24cd45a4efa46e6ba01bfdbd50b532d64011c01 | [
"allow_speech_tags = [as_text(item) for item in allow_speech_tags]\nself.default_speech_tag_filter = allow_speech_tags\nself.stop_words = set()\nself.stop_words_file = stopwords_path\nif type(stop_words_file) is str:\n self.stop_words_file = stop_words_file\nfor word in codecs.open(self.stop_words_file, 'r', 'ut... | <|body_start_0|>
allow_speech_tags = [as_text(item) for item in allow_speech_tags]
self.default_speech_tag_filter = allow_speech_tags
self.stop_words = set()
self.stop_words_file = stopwords_path
if type(stop_words_file) is str:
self.stop_words_file = stop_words_file
... | WordSegmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordSegmentation:
def __init__(self, stop_words_file=None, allow_speech_tags=allow_speech_tags):
"""Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤"""
<|body_0|>
def segment(self, text, lower=True, use_stop_wo... | stack_v2_sparse_classes_36k_train_009064 | 27,442 | no_license | [
{
"docstring": "Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤",
"name": "__init__",
"signature": "def __init__(self, stop_words_file=None, allow_speech_tags=allow_speech_tags)"
},
{
"docstring": "对一段文本进行分词,返回list类型的分词结果 Keyword ... | 3 | stack_v2_sparse_classes_30k_val_000074 | Implement the Python class `WordSegmentation` described below.
Class description:
Implement the WordSegmentation class.
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, allow_speech_tags=allow_speech_tags): Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 ... | Implement the Python class `WordSegmentation` described below.
Class description:
Implement the WordSegmentation class.
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, allow_speech_tags=allow_speech_tags): Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 ... | 815a5706183063522d5a26c321b047ee1ab812cf | <|skeleton|>
class WordSegmentation:
def __init__(self, stop_words_file=None, allow_speech_tags=allow_speech_tags):
"""Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤"""
<|body_0|>
def segment(self, text, lower=True, use_stop_wo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordSegmentation:
def __init__(self, stop_words_file=None, allow_speech_tags=allow_speech_tags):
"""Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤"""
allow_speech_tags = [as_text(item) for item in allow_speech_tags]
sel... | the_stack_v2_python_sparse | knowledge_graph/information/keywords_extraction.py | wagaman/deep_learning | train | 0 | |
fa5b7766357529edb257d7ef81ba1179733bccb4 | [
"def _anchor_span(op):\n return \"<span id='anchor_%s'>%s</span>\" % (op.id, op.id)\noperations = self.to_steps_list()\n\ndef sorting_key(op):\n location = op.get('final_location', None)\n if location is None:\n location = (-1, 1)\n return (location[0], -location[1])\noperations = sorted(operatio... | <|body_start_0|>
def _anchor_span(op):
return "<span id='anchor_%s'>%s</span>" % (op.id, op.id)
operations = self.to_steps_list()
def sorting_key(op):
location = op.get('final_location', None)
if location is None:
location = (-1, 1)
... | PdfReportMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PdfReportMixin:
def make_html_report(self):
"""Return a HTML version of the assembly report (later converted to PDF)."""
<|body_0|>
def write_pdf_report(self, target):
"""Return a PDF version of the report with general infos and details of each intermediary construct... | stack_v2_sparse_classes_36k_train_009065 | 6,358 | permissive | [
{
"docstring": "Return a HTML version of the assembly report (later converted to PDF).",
"name": "make_html_report",
"signature": "def make_html_report(self)"
},
{
"docstring": "Return a PDF version of the report with general infos and details of each intermediary constructs.",
"name": "writ... | 2 | null | Implement the Python class `PdfReportMixin` described below.
Class description:
Implement the PdfReportMixin class.
Method signatures and docstrings:
- def make_html_report(self): Return a HTML version of the assembly report (later converted to PDF).
- def write_pdf_report(self, target): Return a PDF version of the r... | Implement the Python class `PdfReportMixin` described below.
Class description:
Implement the PdfReportMixin class.
Method signatures and docstrings:
- def make_html_report(self): Return a HTML version of the assembly report (later converted to PDF).
- def write_pdf_report(self, target): Return a PDF version of the r... | f72d79f13c3e17501616944ca636aa530a1a6ed9 | <|skeleton|>
class PdfReportMixin:
def make_html_report(self):
"""Return a HTML version of the assembly report (later converted to PDF)."""
<|body_0|>
def write_pdf_report(self, target):
"""Return a PDF version of the report with general infos and details of each intermediary construct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PdfReportMixin:
def make_html_report(self):
"""Return a HTML version of the assembly report (later converted to PDF)."""
def _anchor_span(op):
return "<span id='anchor_%s'>%s</span>" % (op.id, op.id)
operations = self.to_steps_list()
def sorting_key(op):
... | the_stack_v2_python_sparse | dnaweaver/AssemblyPlanReport/mixins/PdfReportMixin.py | Edinburgh-Genome-Foundry/DnaWeaver | train | 25 | |
74e1196e322b18981339e8a17f085eeba04e6ebf | [
"argument_group.add_argument(u'--case_name', dest=u'case_name', type=str, action=u'store', default=cls._DEFAULT_CASE, help=u'Add a case name. This will be the name of the index in ElasticSearch.')\nargument_group.add_argument(u'--document_type', dest=u'document_type', type=str, action=u'store', default=cls._DEFAULT... | <|body_start_0|>
argument_group.add_argument(u'--case_name', dest=u'case_name', type=str, action=u'store', default=cls._DEFAULT_CASE, help=u'Add a case name. This will be the name of the index in ElasticSearch.')
argument_group.add_argument(u'--document_type', dest=u'document_type', type=str, action=u's... | CLI arguments helper class for an Elastic Search output module. | ElasticOutputHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it ... | stack_v2_sparse_classes_36k_train_009066 | 2,989 | permissive | [
{
"docstring": "Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group: the argparse group (instance of argparse._ArgumentGroup or or argparse... | 2 | stack_v2_sparse_classes_30k_train_019105 | Implement the Python class `ElasticOutputHelper` described below.
Class description:
CLI arguments helper class for an Elastic Search output module.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Add command line arguments the helper supports to an argument group. This function takes an ar... | Implement the Python class `ElasticOutputHelper` described below.
Class description:
CLI arguments helper class for an Elastic Search output module.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Add command line arguments the helper supports to an argument group. This function takes an ar... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the comma... | the_stack_v2_python_sparse | plaso/cli/helpers/elastic_output.py | CNR-ITTIG/plasodfaxp | train | 1 |
117b9fda56880c7ec73b134c27dd5c42a0c60162 | [
"self.ID = ID\nself.data = dataframe[ID]\nmetadata = import_pickle('E://Summer research/pythonProject/data/metadata.pickle')[0]\nself.urbanization = metadata['Urbanization'][metadata['NAPS ID'] == ID].iloc[0]",
"df = self.data\nstart_yr = pd.to_datetime('{}-01-01'.format(start), infer_datetime_format=True)\nend_y... | <|body_start_0|>
self.ID = ID
self.data = dataframe[ID]
metadata = import_pickle('E://Summer research/pythonProject/data/metadata.pickle')[0]
self.urbanization = metadata['Urbanization'][metadata['NAPS ID'] == ID].iloc[0]
<|end_body_0|>
<|body_start_1|>
df = self.data
st... | Station | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Station:
def __init__(self, ID, dataframe):
"""Initializes the Station class. input: ID (str) --> ID of station. Eg. "S010102" dataframe (dict) --> A dictionary containing collapsed Dataframes for each station. Must be collapsed and have repeated columns merged using merge_repeated(). Eg... | stack_v2_sparse_classes_36k_train_009067 | 2,574 | no_license | [
{
"docstring": "Initializes the Station class. input: ID (str) --> ID of station. Eg. \"S010102\" dataframe (dict) --> A dictionary containing collapsed Dataframes for each station. Must be collapsed and have repeated columns merged using merge_repeated(). Eg. {station1:df1, station2:df2, ..., station(i):df(i)}... | 2 | stack_v2_sparse_classes_30k_train_016705 | Implement the Python class `Station` described below.
Class description:
Implement the Station class.
Method signatures and docstrings:
- def __init__(self, ID, dataframe): Initializes the Station class. input: ID (str) --> ID of station. Eg. "S010102" dataframe (dict) --> A dictionary containing collapsed Dataframes... | Implement the Python class `Station` described below.
Class description:
Implement the Station class.
Method signatures and docstrings:
- def __init__(self, ID, dataframe): Initializes the Station class. input: ID (str) --> ID of station. Eg. "S010102" dataframe (dict) --> A dictionary containing collapsed Dataframes... | 309c7d72c6fa580c5f3e45c48824097ddd17685c | <|skeleton|>
class Station:
def __init__(self, ID, dataframe):
"""Initializes the Station class. input: ID (str) --> ID of station. Eg. "S010102" dataframe (dict) --> A dictionary containing collapsed Dataframes for each station. Must be collapsed and have repeated columns merged using merge_repeated(). Eg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Station:
def __init__(self, ID, dataframe):
"""Initializes the Station class. input: ID (str) --> ID of station. Eg. "S010102" dataframe (dict) --> A dictionary containing collapsed Dataframes for each station. Must be collapsed and have repeated columns merged using merge_repeated(). Eg. {station1:df... | the_stack_v2_python_sparse | Classes.py | Ulvvo/NAPS-2021 | train | 0 | |
cbb07959a07111fd9ce8e3da1b30504cfc95f76a | [
"super().__init__()\nself.forward_func = forward_func\nself.fgsm = FGSM(forward_func, loss_func)\nself.bound = lambda x: torch.clamp(x, min=lower_bound, max=upper_bound)",
"def _clip(inputs: Tensor, outputs: Tensor) -> Tensor:\n diff = outputs - inputs\n if norm == 'Linf':\n return inputs + torch.cla... | <|body_start_0|>
super().__init__()
self.forward_func = forward_func
self.fgsm = FGSM(forward_func, loss_func)
self.bound = lambda x: torch.clamp(x, min=lower_bound, max=upper_bound)
<|end_body_0|>
<|body_start_1|>
def _clip(inputs: Tensor, outputs: Tensor) -> Tensor:
... | Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the formulation is:: x_0 = x x_(t+1) = ... | PGD | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PGD:
"""Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the form... | stack_v2_sparse_classes_36k_train_009068 | 10,165 | permissive | [
{
"docstring": "Args: forward_func (Callable): The pytorch model for which the attack is computed. loss_func (Callable, optional): Loss function of which the gradient computed. The loss function should take in outputs of the model and labels, and return the loss for each input tensor. The default loss function ... | 3 | stack_v2_sparse_classes_30k_train_014959 | Implement the Python class `PGD` described below.
Class description:
Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inp... | Implement the Python class `PGD` described below.
Class description:
Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inp... | 945c582cc0b08885c4e2bfecb020abdfac0122f3 | <|skeleton|>
class PGD:
"""Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the form... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PGD:
"""Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the formulation is:: ... | the_stack_v2_python_sparse | captum/robust/_core/pgd.py | pytorch/captum | train | 4,230 |
1d19c7463fe0694832b6530477cefc8a7e56f905 | [
"self.reqpaser = reqparse.RequestParser()\nself.reqpaser.add_argument('attribute_id', type=str, required=True, help='attribute id required')\nself.reqpaser.add_argument('user_id', type=int, required=True, help='user id required')\nself.reqpaser.add_argument('name', type=str, required=False, store_missing=False, def... | <|body_start_0|>
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('attribute_id', type=str, required=True, help='attribute id required')
self.reqpaser.add_argument('user_id', type=int, required=True, help='user id required')
self.reqpaser.add_argument('name', type=str,... | Create, Update or Fetch Attribute Alias | AttributeAlias | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeAlias:
"""Create, Update or Fetch Attribute Alias"""
def __init__(self):
"""Set reqpase arguments"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Update AttrAlias (Attribute Alias) if it exists otherwise create an AttrAlias :param attribute_... | stack_v2_sparse_classes_36k_train_009069 | 4,352 | permissive | [
{
"docstring": "Set reqpase arguments",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update AttrAlias (Attribute Alias) if it exists otherwise create an AttrAlias :param attribute_id: Parent Attribute id to alias :param user_id: Owner user id :param name: Alias for At... | 3 | null | Implement the Python class `AttributeAlias` described below.
Class description:
Create, Update or Fetch Attribute Alias
Method signatures and docstrings:
- def __init__(self): Set reqpase arguments
- def post(self) -> ({str: str}, HTTPStatus): Update AttrAlias (Attribute Alias) if it exists otherwise create an AttrAl... | Implement the Python class `AttributeAlias` described below.
Class description:
Create, Update or Fetch Attribute Alias
Method signatures and docstrings:
- def __init__(self): Set reqpase arguments
- def post(self) -> ({str: str}, HTTPStatus): Update AttrAlias (Attribute Alias) if it exists otherwise create an AttrAl... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class AttributeAlias:
"""Create, Update or Fetch Attribute Alias"""
def __init__(self):
"""Set reqpase arguments"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Update AttrAlias (Attribute Alias) if it exists otherwise create an AttrAlias :param attribute_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeAlias:
"""Create, Update or Fetch Attribute Alias"""
def __init__(self):
"""Set reqpase arguments"""
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('attribute_id', type=str, required=True, help='attribute id required')
self.reqpaser.add_argume... | the_stack_v2_python_sparse | Analytics/resources/attributes/attribute_alias.py | thanosbnt/SharingCitiesDashboard | train | 0 |
3039ce654c1ac14948b3e3ac6a169790dcc4c8e1 | [
"if not l1:\n return l2\nelif not l2:\n return l1\nelif l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2",
"prehead = ListNode(-1)\nprev = prehead\nwhile l1 and l2:\n if l1.val < l2.val:\n prev.next,... | <|body_start_0|>
if not l1:
return l2
elif not l2:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
<|end_body_0|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists2(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009070 | 1,701 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists1",
"signature": "def mergeTwoLists1(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists2",
"signature": "def mergeTwoLists2(self, ... | 2 | stack_v2_sparse_classes_30k_train_003241 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists1(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists2(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists1(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists2(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNod... | 5f94a60d01dca431025d461d2e50dcf9612dee70 | <|skeleton|>
class Solution:
def mergeTwoLists1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists2(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
if not l1:
return l2
elif not l2:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
... | the_stack_v2_python_sparse | 1.链表/21.合并两个有序链表.py | WJ-Lai/LeetCode-Python-Solution | train | 0 | |
7fe47ef7ae3b9c61aa70a4bf850469c91b3ce7fa | [
"n = len(A)\nres = [False] * n\nsum = 0\nfor i in range(n):\n sum = (sum << 1) + A[i]\n res[i] = sum % 5 == 0\nreturn res",
"A = ''.join([str(x) for x in A])\nn = len(A)\nres = [False] * n\nfor i in range(n):\n res[i] = int(''.join(A[:i + 1]), 2) % 5 == 0\nreturn res"
] | <|body_start_0|>
n = len(A)
res = [False] * n
sum = 0
for i in range(n):
sum = (sum << 1) + A[i]
res[i] = sum % 5 == 0
return res
<|end_body_0|>
<|body_start_1|>
A = ''.join([str(x) for x in A])
n = len(A)
res = [False] * n
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def prefixesDivBy5(self, A):
""":type A: List[int] :rtype: List[bool]"""
<|body_0|>
def prefixesDivBy5_2(self, A):
"""超时 待优化 :type A: List[int] :rtype: List[bool]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(A)
res = [Fa... | stack_v2_sparse_classes_36k_train_009071 | 1,383 | no_license | [
{
"docstring": ":type A: List[int] :rtype: List[bool]",
"name": "prefixesDivBy5",
"signature": "def prefixesDivBy5(self, A)"
},
{
"docstring": "超时 待优化 :type A: List[int] :rtype: List[bool]",
"name": "prefixesDivBy5_2",
"signature": "def prefixesDivBy5_2(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prefixesDivBy5(self, A): :type A: List[int] :rtype: List[bool]
- def prefixesDivBy5_2(self, A): 超时 待优化 :type A: List[int] :rtype: List[bool] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prefixesDivBy5(self, A): :type A: List[int] :rtype: List[bool]
- def prefixesDivBy5_2(self, A): 超时 待优化 :type A: List[int] :rtype: List[bool]
<|skeleton|>
class Solution:
... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def prefixesDivBy5(self, A):
""":type A: List[int] :rtype: List[bool]"""
<|body_0|>
def prefixesDivBy5_2(self, A):
"""超时 待优化 :type A: List[int] :rtype: List[bool]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def prefixesDivBy5(self, A):
""":type A: List[int] :rtype: List[bool]"""
n = len(A)
res = [False] * n
sum = 0
for i in range(n):
sum = (sum << 1) + A[i]
res[i] = sum % 5 == 0
return res
def prefixesDivBy5_2(self, A):
... | the_stack_v2_python_sparse | 1018_被 5 整除的二进制前缀.py | lovehhf/LeetCode | train | 0 | |
f37fa391497a701dacb21446267b537718222ecc | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\ntensor ... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_bod... | class that instantiates a RNN Encoder | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""class that instantiates a RNN Encoder"""
def __init__(self, vocab, embedding, units, batch):
"""constructor"""
<|body_0|>
def initialize_hidden_state(self):
"""function that initializes the hidden state to a tensor of zeros"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_009072 | 1,553 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "function that initializes the hidden state to a tensor of zeros",
"name": "initialize_hidden_state",
"signature": "def initialize_hidden_state(self)"
}... | 3 | stack_v2_sparse_classes_30k_train_007661 | Implement the Python class `RNNEncoder` described below.
Class description:
class that instantiates a RNN Encoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): constructor
- def initialize_hidden_state(self): function that initializes the hidden state to a tensor of zeros
- d... | Implement the Python class `RNNEncoder` described below.
Class description:
class that instantiates a RNN Encoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): constructor
- def initialize_hidden_state(self): function that initializes the hidden state to a tensor of zeros
- d... | 7d3b348aec3b20da25b162b71f150c87c7c28d71 | <|skeleton|>
class RNNEncoder:
"""class that instantiates a RNN Encoder"""
def __init__(self, vocab, embedding, units, batch):
"""constructor"""
<|body_0|>
def initialize_hidden_state(self):
"""function that initializes the hidden state to a tensor of zeros"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""class that instantiates a RNN Encoder"""
def __init__(self, vocab, embedding, units, batch):
"""constructor"""
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | dacastanogo/holbertonschool-machine_learning | train | 0 |
13bafd0c54bd7a08652274f745d963da6e484805 | [
"super().__init__(attacker, defender, enemy=enemy)\nself._move_file_name = join('moves', 'body_slam.png')\nself._fps = 30\nself._drop = VerticalDropAndRecovery(attacker, 4)\nself._lunge = HorizontalLunge(attacker, 10 if not enemy else -10)\nself._reverse_lunge = HorizontalLunge(attacker, -10 if not enemy else 10)\n... | <|body_start_0|>
super().__init__(attacker, defender, enemy=enemy)
self._move_file_name = join('moves', 'body_slam.png')
self._fps = 30
self._drop = VerticalDropAndRecovery(attacker, 4)
self._lunge = HorizontalLunge(attacker, 10 if not enemy else -10)
self._reverse_lunge ... | BodySlam | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BodySlam:
def __init__(self, attacker, defender, enemy=False):
"""This is the animation for the move body slam. It first performs a vertical drop and recover, then a horizontal lunge, then displays the impact png, the the enemy performs a horizontal lunge, then the enemy jiggles, then it... | stack_v2_sparse_classes_36k_train_009073 | 4,195 | no_license | [
{
"docstring": "This is the animation for the move body slam. It first performs a vertical drop and recover, then a horizontal lunge, then displays the impact png, the the enemy performs a horizontal lunge, then the enemy jiggles, then it lunges back to its start point and the animation ends. Extends MoveBase",... | 2 | stack_v2_sparse_classes_30k_train_013192 | Implement the Python class `BodySlam` described below.
Class description:
Implement the BodySlam class.
Method signatures and docstrings:
- def __init__(self, attacker, defender, enemy=False): This is the animation for the move body slam. It first performs a vertical drop and recover, then a horizontal lunge, then di... | Implement the Python class `BodySlam` described below.
Class description:
Implement the BodySlam class.
Method signatures and docstrings:
- def __init__(self, attacker, defender, enemy=False): This is the animation for the move body slam. It first performs a vertical drop and recover, then a horizontal lunge, then di... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class BodySlam:
def __init__(self, attacker, defender, enemy=False):
"""This is the animation for the move body slam. It first performs a vertical drop and recover, then a horizontal lunge, then displays the impact png, the the enemy performs a horizontal lunge, then the enemy jiggles, then it... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BodySlam:
def __init__(self, attacker, defender, enemy=False):
"""This is the animation for the move body slam. It first performs a vertical drop and recover, then a horizontal lunge, then displays the impact png, the the enemy performs a horizontal lunge, then the enemy jiggles, then it lunges back t... | the_stack_v2_python_sparse | pokered/modules/animations/moves/body_slam.py | surranc20/pokered | train | 44 | |
b78d0923b8486f19528620bd9a647c84590d3ab4 | [
"self.controller = controller\nself.sock_l = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.sock_l.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nself.sock_l.bind(('localhost', 9999))\nself.sock_l.listen(0)\nself.sock = None",
"self.sock, addr = self.sock_l.accept()\nself.sock_l.close()\nself.soc... | <|body_start_0|>
self.controller = controller
self.sock_l = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock_l.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock_l.bind(('localhost', 9999))
self.sock_l.listen(0)
self.sock = None
<|end_body_0|>
<|b... | Simulation server exposing PandA simulation controller to TCP server | SimulationServer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationServer:
"""Simulation server exposing PandA simulation controller to TCP server"""
def __init__(self, controller):
"""Start simulation server and create controller Args: controller(Controller): Zebra2 controller object"""
<|body_0|>
def run(self):
"""Ac... | stack_v2_sparse_classes_36k_train_009074 | 23,000 | permissive | [
{
"docstring": "Start simulation server and create controller Args: controller(Controller): Zebra2 controller object",
"name": "__init__",
"signature": "def __init__(self, controller)"
},
{
"docstring": "Accept the first connection to server, then start simulation",
"name": "run",
"signa... | 4 | stack_v2_sparse_classes_30k_val_000813 | Implement the Python class `SimulationServer` described below.
Class description:
Simulation server exposing PandA simulation controller to TCP server
Method signatures and docstrings:
- def __init__(self, controller): Start simulation server and create controller Args: controller(Controller): Zebra2 controller objec... | Implement the Python class `SimulationServer` described below.
Class description:
Simulation server exposing PandA simulation controller to TCP server
Method signatures and docstrings:
- def __init__(self, controller): Start simulation server and create controller Args: controller(Controller): Zebra2 controller objec... | 9ad5512556c94d38f817b0c02a38d660c8777f43 | <|skeleton|>
class SimulationServer:
"""Simulation server exposing PandA simulation controller to TCP server"""
def __init__(self, controller):
"""Start simulation server and create controller Args: controller(Controller): Zebra2 controller object"""
<|body_0|>
def run(self):
"""Ac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulationServer:
"""Simulation server exposing PandA simulation controller to TCP server"""
def __init__(self, controller):
"""Start simulation server and create controller Args: controller(Controller): Zebra2 controller object"""
self.controller = controller
self.sock_l = socket... | the_stack_v2_python_sparse | common/python/simulations.py | PandABlocks/PandABlocks-FPGA | train | 17 |
f5ea304ad1602160cf832cf52fcc9ad701f3fc09 | [
"super(EmBLeafMerge, self).__init__()\nsuper(EmBLeafScenario, self).__init__()\nself.service = GlobalModule.SERVICE_B_LEAF\nself._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.service]\nself._scenario_name = 'B-LeafMerge'\nself.device_type = 'device'",
"xml_elm = etree.fromstring(device_message)\nGlobalModul... | <|body_start_0|>
super(EmBLeafMerge, self).__init__()
super(EmBLeafScenario, self).__init__()
self.service = GlobalModule.SERVICE_B_LEAF
self._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.service]
self._scenario_name = 'B-LeafMerge'
self.device_type = 'device'
<|end... | B-Leaf expansion class (take-over from Leaf expansion scenario) | EmBLeafMerge | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmBLeafMerge:
"""B-Leaf expansion class (take-over from Leaf expansion scenario)"""
def __init__(self):
"""Constructor"""
<|body_0|>
def _creating_json(self, device_message):
"""Convert EC message (XML) divided for each device into JSON. Explanation about paramet... | stack_v2_sparse_classes_36k_train_009075 | 2,172 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Convert EC message (XML) divided for each device into JSON. Explanation about parameter: device_message: Message for each device Explanation about return value device_json_message: JSON message... | 2 | stack_v2_sparse_classes_30k_train_009182 | Implement the Python class `EmBLeafMerge` described below.
Class description:
B-Leaf expansion class (take-over from Leaf expansion scenario)
Method signatures and docstrings:
- def __init__(self): Constructor
- def _creating_json(self, device_message): Convert EC message (XML) divided for each device into JSON. Expl... | Implement the Python class `EmBLeafMerge` described below.
Class description:
B-Leaf expansion class (take-over from Leaf expansion scenario)
Method signatures and docstrings:
- def __init__(self): Constructor
- def _creating_json(self, device_message): Convert EC message (XML) divided for each device into JSON. Expl... | e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f | <|skeleton|>
class EmBLeafMerge:
"""B-Leaf expansion class (take-over from Leaf expansion scenario)"""
def __init__(self):
"""Constructor"""
<|body_0|>
def _creating_json(self, device_message):
"""Convert EC message (XML) divided for each device into JSON. Explanation about paramet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmBLeafMerge:
"""B-Leaf expansion class (take-over from Leaf expansion scenario)"""
def __init__(self):
"""Constructor"""
super(EmBLeafMerge, self).__init__()
super(EmBLeafScenario, self).__init__()
self.service = GlobalModule.SERVICE_B_LEAF
self._xml_ns = '{%s}' %... | the_stack_v2_python_sparse | lib/Scenario/EmBLeafMerge.py | lixiaochun/element-manager | train | 0 |
02333b7934193dd945067c39642bcb9409d93c3f | [
"try:\n with BytesIO() as stream:\n with GzipFile(fileobj=stream, mode='wb') as file_handle:\n file_handle.write(jsonify(value, pretty=False).encode('utf-8'))\n output = stream.getvalue()\n return output\nexcept TypeError as error:\n log_json_incompatible_types(value)\n raise_wi... | <|body_start_0|>
try:
with BytesIO() as stream:
with GzipFile(fileobj=stream, mode='wb') as file_handle:
file_handle.write(jsonify(value, pretty=False).encode('utf-8'))
output = stream.getvalue()
return output
except TypeError a... | Implement a binary compressed JSON column type. | BJSON | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BJSON:
"""Implement a binary compressed JSON column type."""
def process_bind_param(self, value, dialect):
"""Convert the value to a JSON encoded string before storing it."""
<|body_0|>
def process_result_value(self, value, dialect):
"""Convert a JSON encoded str... | stack_v2_sparse_classes_36k_train_009076 | 3,473 | permissive | [
{
"docstring": "Convert the value to a JSON encoded string before storing it.",
"name": "process_bind_param",
"signature": "def process_bind_param(self, value, dialect)"
},
{
"docstring": "Convert a JSON encoded string to a dictionary structure.",
"name": "process_result_value",
"signatu... | 2 | stack_v2_sparse_classes_30k_val_000029 | Implement the Python class `BJSON` described below.
Class description:
Implement a binary compressed JSON column type.
Method signatures and docstrings:
- def process_bind_param(self, value, dialect): Convert the value to a JSON encoded string before storing it.
- def process_result_value(self, value, dialect): Conve... | Implement the Python class `BJSON` described below.
Class description:
Implement a binary compressed JSON column type.
Method signatures and docstrings:
- def process_bind_param(self, value, dialect): Convert the value to a JSON encoded string before storing it.
- def process_result_value(self, value, dialect): Conve... | 81a55a163262a0e06bfcb036d98e8e551edc3873 | <|skeleton|>
class BJSON:
"""Implement a binary compressed JSON column type."""
def process_bind_param(self, value, dialect):
"""Convert the value to a JSON encoded string before storing it."""
<|body_0|>
def process_result_value(self, value, dialect):
"""Convert a JSON encoded str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BJSON:
"""Implement a binary compressed JSON column type."""
def process_bind_param(self, value, dialect):
"""Convert the value to a JSON encoded string before storing it."""
try:
with BytesIO() as stream:
with GzipFile(fileobj=stream, mode='wb') as file_handle... | the_stack_v2_python_sparse | src/memote/suite/results/models.py | opencobra/memote | train | 109 |
d7308318fedd81c1965f4266798b13219f3bd865 | [
"if len(nums) == 0 or nums is None:\n return 0\nif len(nums) <= 2:\n return max(nums[:])\nreturn max(self.robHelper(nums[1:]), self.robHelper(nums[:len(nums) - 1]))",
"pp = nums[0]\np = max(pp, nums[1])\nfor i in range(2, len(nums)):\n tmp = p\n p = max(pp + nums[i], p)\n pp = tmp\nreturn p"
] | <|body_start_0|>
if len(nums) == 0 or nums is None:
return 0
if len(nums) <= 2:
return max(nums[:])
return max(self.robHelper(nums[1:]), self.robHelper(nums[:len(nums) - 1]))
<|end_body_0|>
<|body_start_1|>
pp = nums[0]
p = max(pp, nums[1])
for i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def robHelper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0 or nums is None:
return 0... | stack_v2_sparse_classes_36k_train_009077 | 707 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "robHelper",
"signature": "def robHelper(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006201 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def robHelper(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 rob(self, nums): :type nums: List[int] :rtype: int
- def robHelper(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def robHelper(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 rob(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0 or nums is None:
return 0
if len(nums) <= 2:
return max(nums[:])
return max(self.robHelper(nums[1:]), self.robHelper(nums[:len(nums) - 1]))
def robHelper(self, ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/lc-all-solutions/213.house-robber-ii/house-robber-ii.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
b7862cff3acf7f167240ce999417ead2d257e66e | [
"if not grid:\n return 0\nrows, cols = (len(grid), len(grid[0]))\ntotal_islands = 0\nq = deque()\n\ndef bfs(grid: List[List[int]], q: 'deque'):\n while q:\n row, col = q.popleft()\n for dr, dc in ((row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)):\n if 0 <= dr < rows and... | <|body_start_0|>
if not grid:
return 0
rows, cols = (len(grid), len(grid[0]))
total_islands = 0
q = deque()
def bfs(grid: List[List[int]], q: 'deque'):
while q:
row, col = q.popleft()
for dr, dc in ((row + 1, col), (row - 1... | Islands | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Islands:
def total_number_bfs(self, grid: List[List[int]]) -> int:
"""Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:"""
<|body_0|>
def total_number_dfs(self, grid: List[List[int]]) -> int:
"""Approach: DFS Time Complexity:... | stack_v2_sparse_classes_36k_train_009078 | 2,849 | no_license | [
{
"docstring": "Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:",
"name": "total_number_bfs",
"signature": "def total_number_bfs(self, grid: List[List[int]]) -> int"
},
{
"docstring": "Approach: DFS Time Complexity: O(M * N) Space Complexity: O(M * N) ... | 2 | null | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def total_number_bfs(self, grid: List[List[int]]) -> int: Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:
- def total_number_dfs(self, g... | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def total_number_bfs(self, grid: List[List[int]]) -> int: Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:
- def total_number_dfs(self, g... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Islands:
def total_number_bfs(self, grid: List[List[int]]) -> int:
"""Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:"""
<|body_0|>
def total_number_dfs(self, grid: List[List[int]]) -> int:
"""Approach: DFS Time Complexity:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Islands:
def total_number_bfs(self, grid: List[List[int]]) -> int:
"""Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:"""
if not grid:
return 0
rows, cols = (len(grid), len(grid[0]))
total_islands = 0
q = deque()
... | the_stack_v2_python_sparse | goldman_sachs/number_of_islands.py | Shiv2157k/leet_code | train | 1 | |
2581e3f1f1ce245d49f3a1b454bb6de26a5e8946 | [
"self.sums = list()\nself.lens = len(nums)\nif self.lens > 0:\n self.sums.append(nums[0])\nfor index, val in enumerate(nums[1:], 1):\n self.sums.append(val + self.sums[index - 1])",
"if self.lens == 0 or i > j:\n return 0\nj = min(j, self.lens - 1)\ni = max(i, 0)\nreturn self.sums[j] if i == 0 else self.... | <|body_start_0|>
self.sums = list()
self.lens = len(nums)
if self.lens > 0:
self.sums.append(nums[0])
for index, val in enumerate(nums[1:], 1):
self.sums.append(val + self.sums[index - 1])
<|end_body_0|>
<|body_start_1|>
if self.lens == 0 or i > j:
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sums = list()
self.lens = len(nums)
if... | stack_v2_sparse_classes_36k_train_009079 | 831 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006057 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 3f9bd744b35b0adb727677f390bf2b35f0201e3c | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.sums = list()
self.lens = len(nums)
if self.lens > 0:
self.sums.append(nums[0])
for index, val in enumerate(nums[1:], 1):
self.sums.append(val + self.sums[index - 1])
def s... | the_stack_v2_python_sparse | leecode/303_Range_Sum_Query-Immutable.py | lishuchen/Algorithms | train | 0 | |
f50413552e5f447dea656e6d9d8366198a51bb7a | [
"for amc_key, amc_value in lnt_dict.items():\n url = self.start_url[0] + amc_value + '/' + str(YEAR)\n yield scrapy.Request(url=url, callback=self.parser, meta={'amc_key': amc_key})",
"link = {}\nlink.update({response.meta.get('amc_key'): response.css(lnt_path[0]).getall()[0]})\nfor amc, url_value in link.i... | <|body_start_0|>
for amc_key, amc_value in lnt_dict.items():
url = self.start_url[0] + amc_value + '/' + str(YEAR)
yield scrapy.Request(url=url, callback=self.parser, meta={'amc_key': amc_key})
<|end_body_0|>
<|body_start_1|>
link = {}
link.update({response.meta.get('amc... | LTAdvisorKhoj | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LTAdvisorKhoj:
def start_requests(self):
"""This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent."""
<|body_0|>
def parser(self, response):
"""This function ... | stack_v2_sparse_classes_36k_train_009080 | 1,757 | no_license | [
{
"docstring": "This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent.",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "This function gets the Respon... | 2 | null | Implement the Python class `LTAdvisorKhoj` described below.
Class description:
Implement the LTAdvisorKhoj class.
Method signatures and docstrings:
- def start_requests(self): This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy ... | Implement the Python class `LTAdvisorKhoj` described below.
Class description:
Implement the LTAdvisorKhoj class.
Method signatures and docstrings:
- def start_requests(self): This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy ... | 946e1c35b785bfc3ea31d5903e021d4bc99fe302 | <|skeleton|>
class LTAdvisorKhoj:
def start_requests(self):
"""This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent."""
<|body_0|>
def parser(self, response):
"""This function ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LTAdvisorKhoj:
def start_requests(self):
"""This function will loop through all the AMC's in the given dictionary with the Query parameters of the URL. With the built up URL, the Scrapy Request will be sent."""
for amc_key, amc_value in lnt_dict.items():
url = self.start_url[0] + a... | the_stack_v2_python_sparse | FundRatingAMCFiles/fund_rating_file_extraction/fund_rating_file_extraction/spiders/l&t.py | pavithra-ft/ft-automation | train | 0 | |
5a3e44a5c89d3e7633a9f7526592ceadc6614cb3 | [
"debts = self.debts.all()\nborrowed_amount = sum([debt.amount for debt in debts], 0)\nreturn borrowed_amount",
"loans = self.loans.all()\nlent_amount = sum([loan.amount for loan in loans], 0)\nreturn lent_amount"
] | <|body_start_0|>
debts = self.debts.all()
borrowed_amount = sum([debt.amount for debt in debts], 0)
return borrowed_amount
<|end_body_0|>
<|body_start_1|>
loans = self.loans.all()
lent_amount = sum([loan.amount for loan in loans], 0)
return lent_amount
<|end_body_1|>
| Class to define a user, based on the specified requirements | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Class to define a user, based on the specified requirements"""
def borrowed_amount(self):
"""A property that computes automatically the amount of money borrowed from the user"""
<|body_0|>
def lent_amount(self):
"""A property that computes automatically ... | stack_v2_sparse_classes_36k_train_009081 | 2,336 | permissive | [
{
"docstring": "A property that computes automatically the amount of money borrowed from the user",
"name": "borrowed_amount",
"signature": "def borrowed_amount(self)"
},
{
"docstring": "A property that computes automatically the amount of money lent by the user",
"name": "lent_amount",
... | 2 | stack_v2_sparse_classes_30k_train_010183 | Implement the Python class `User` described below.
Class description:
Class to define a user, based on the specified requirements
Method signatures and docstrings:
- def borrowed_amount(self): A property that computes automatically the amount of money borrowed from the user
- def lent_amount(self): A property that co... | Implement the Python class `User` described below.
Class description:
Class to define a user, based on the specified requirements
Method signatures and docstrings:
- def borrowed_amount(self): A property that computes automatically the amount of money borrowed from the user
- def lent_amount(self): A property that co... | 4d17bb63fb2b9669216a0f60326d4a4b9055af7e | <|skeleton|>
class User:
"""Class to define a user, based on the specified requirements"""
def borrowed_amount(self):
"""A property that computes automatically the amount of money borrowed from the user"""
<|body_0|>
def lent_amount(self):
"""A property that computes automatically ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""Class to define a user, based on the specified requirements"""
def borrowed_amount(self):
"""A property that computes automatically the amount of money borrowed from the user"""
debts = self.debts.all()
borrowed_amount = sum([debt.amount for debt in debts], 0)
ret... | the_stack_v2_python_sparse | black_belt/online_lending/models.py | gfhuertac/coding_dojo_python | train | 0 |
3a853e31d9c343085a28a64cf7019df3b1142925 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing data of the Project resource. | ProjectDataServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectDataServiceServicer:
"""A set of methods for managing data of the Project resource."""
def UploadFile(self, request_iterator, context):
"""Uploads a file to the specified project."""
<|body_0|>
def DownloadFile(self, request, context):
"""Downloads the spe... | stack_v2_sparse_classes_36k_train_009082 | 5,007 | permissive | [
{
"docstring": "Uploads a file to the specified project.",
"name": "UploadFile",
"signature": "def UploadFile(self, request_iterator, context)"
},
{
"docstring": "Downloads the specified file from the specified project.",
"name": "DownloadFile",
"signature": "def DownloadFile(self, reque... | 2 | stack_v2_sparse_classes_30k_train_005880 | Implement the Python class `ProjectDataServiceServicer` described below.
Class description:
A set of methods for managing data of the Project resource.
Method signatures and docstrings:
- def UploadFile(self, request_iterator, context): Uploads a file to the specified project.
- def DownloadFile(self, request, contex... | Implement the Python class `ProjectDataServiceServicer` described below.
Class description:
A set of methods for managing data of the Project resource.
Method signatures and docstrings:
- def UploadFile(self, request_iterator, context): Uploads a file to the specified project.
- def DownloadFile(self, request, contex... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class ProjectDataServiceServicer:
"""A set of methods for managing data of the Project resource."""
def UploadFile(self, request_iterator, context):
"""Uploads a file to the specified project."""
<|body_0|>
def DownloadFile(self, request, context):
"""Downloads the spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectDataServiceServicer:
"""A set of methods for managing data of the Project resource."""
def UploadFile(self, request_iterator, context):
"""Uploads a file to the specified project."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented... | the_stack_v2_python_sparse | yandex/cloud/datasphere/v1/project_data_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
7d08dd6b973d8d04f2e355b3481285833e99f475 | [
"assert len(fxy) <= self.ndof\nf = numpy.zeros((self.ndof, 1))\nfor item in fxy:\n assert len(item) == 4\n x_ = item[0]\n y_ = item[1]\n fx_ = item[2] if item[2] else 0\n fy_ = item[3] if item[3] else 0\n f[xy_to_id(x_, y_, self.nelx, self.nely) * 2, 0] = fx_\n f[xy_to_id(x_, y_, self.nelx, sel... | <|body_start_0|>
assert len(fxy) <= self.ndof
f = numpy.zeros((self.ndof, 1))
for item in fxy:
assert len(item) == 4
x_ = item[0]
y_ = item[1]
fx_ = item[2] if item[2] else 0
fy_ = item[3] if item[3] else 0
f[xy_to_id(x_, y_... | A class used to extend BoundaryConditions class originally builtin within topopt.boundary_conditions. It adds 2 public methods to convert forces and fized dofs. ... Attributes ---------- inherited from topopt.boundary_conditions.BoundaryConditions Methods ------- fxy2f(fxy) Forces at coordinates to forces at dof ids fi... | MyExtendedBoundaryConditions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyExtendedBoundaryConditions:
"""A class used to extend BoundaryConditions class originally builtin within topopt.boundary_conditions. It adds 2 public methods to convert forces and fized dofs. ... Attributes ---------- inherited from topopt.boundary_conditions.BoundaryConditions Methods ------- ... | stack_v2_sparse_classes_36k_train_009083 | 6,408 | no_license | [
{
"docstring": "Forces at coordinates to forces at dof ids Converts a list of tuples as [(x1, y1, fx1, fy1), (x2, y2, fx2, fy2), ...] to a numpy.ndarray suitable to specify forces. Parameters ---------- fxy : list list of 4-tuples as [(x1, y1, fx1, fy1), (x2, y2, fx2, fy2), ...] Returns ------- numpy.ndarray nu... | 2 | stack_v2_sparse_classes_30k_train_002711 | Implement the Python class `MyExtendedBoundaryConditions` described below.
Class description:
A class used to extend BoundaryConditions class originally builtin within topopt.boundary_conditions. It adds 2 public methods to convert forces and fized dofs. ... Attributes ---------- inherited from topopt.boundary_conditi... | Implement the Python class `MyExtendedBoundaryConditions` described below.
Class description:
A class used to extend BoundaryConditions class originally builtin within topopt.boundary_conditions. It adds 2 public methods to convert forces and fized dofs. ... Attributes ---------- inherited from topopt.boundary_conditi... | 067bf9b768e020b3de15fc1dee06c2ca36875619 | <|skeleton|>
class MyExtendedBoundaryConditions:
"""A class used to extend BoundaryConditions class originally builtin within topopt.boundary_conditions. It adds 2 public methods to convert forces and fized dofs. ... Attributes ---------- inherited from topopt.boundary_conditions.BoundaryConditions Methods ------- ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyExtendedBoundaryConditions:
"""A class used to extend BoundaryConditions class originally builtin within topopt.boundary_conditions. It adds 2 public methods to convert forces and fized dofs. ... Attributes ---------- inherited from topopt.boundary_conditions.BoundaryConditions Methods ------- fxy2f(fxy) Fo... | the_stack_v2_python_sparse | myutils/my_boundary_conditions.py | carloshernangarrido/topopt1 | train | 0 |
dddf4ec494a60e48e9a8c6c5ddb45ab08cc6d272 | [
"flags.AddNamePositionalArg(parser)\nflags.AddServiceUpdateArgs(parser)\nflags.AddParametersArg(parser)",
"add_service = args.add_service\nremove_service = args.remove_service\nintegration_name = args.name\nparameters = flags.GetParameters(args)\nrelease_track = self.ReleaseTrack()\nconn_context = connection_cont... | <|body_start_0|>
flags.AddNamePositionalArg(parser)
flags.AddServiceUpdateArgs(parser)
flags.AddParametersArg(parser)
<|end_body_0|>
<|body_start_1|>
add_service = args.add_service
remove_service = args.remove_service
integration_name = args.name
parameters = fla... | Update a Cloud Run Integration. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update a Cloud Run Integration."""
def Args(cls, parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
<|body_0|>
def Run(self, args):
"""Update a Cloud Run Integration."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_009084 | 3,654 | permissive | [
{
"docstring": "Set up arguments for this command. Args: parser: An argparse.ArgumentParser.",
"name": "Args",
"signature": "def Args(cls, parser)"
},
{
"docstring": "Update a Cloud Run Integration.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | null | Implement the Python class `Update` described below.
Class description:
Update a Cloud Run Integration.
Method signatures and docstrings:
- def Args(cls, parser): Set up arguments for this command. Args: parser: An argparse.ArgumentParser.
- def Run(self, args): Update a Cloud Run Integration. | Implement the Python class `Update` described below.
Class description:
Update a Cloud Run Integration.
Method signatures and docstrings:
- def Args(cls, parser): Set up arguments for this command. Args: parser: An argparse.ArgumentParser.
- def Run(self, args): Update a Cloud Run Integration.
<|skeleton|>
class Upd... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Update:
"""Update a Cloud Run Integration."""
def Args(cls, parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
<|body_0|>
def Run(self, args):
"""Update a Cloud Run Integration."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Update:
"""Update a Cloud Run Integration."""
def Args(cls, parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentParser."""
flags.AddNamePositionalArg(parser)
flags.AddServiceUpdateArgs(parser)
flags.AddParametersArg(parser)
def Run(self, a... | the_stack_v2_python_sparse | lib/surface/run/integrations/update.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
9dddb428b3b9b3c8170da030d63a9601ea0402da | [
"self.ui = viewStockUI.Ui_viewStockWindow()\napp = viewStockUI.QtGui.QApplication(sys.argv)\nMainWindow = viewStockUI.QtGui.QMainWindow()\nself.ui.setupUi(MainWindow)\nself.ui.loadButton.clicked.connect(self.onclick)\nMainWindow.show()\nsys.exit(app.exec_())",
"QTableWidget.clearContents(self.ui.tableWidget)\nsel... | <|body_start_0|>
self.ui = viewStockUI.Ui_viewStockWindow()
app = viewStockUI.QtGui.QApplication(sys.argv)
MainWindow = viewStockUI.QtGui.QMainWindow()
self.ui.setupUi(MainWindow)
self.ui.loadButton.clicked.connect(self.onclick)
MainWindow.show()
sys.exit(app.exec... | viewStocks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class viewStocks:
def __init__(self):
"""Initialises all the graphical user interfaces necessary to display the data in the table appropriately but also adds functionality to the button, meaning that after the button gets pressed, it will perform a function."""
<|body_0|>
def oncl... | stack_v2_sparse_classes_36k_train_009085 | 13,931 | no_license | [
{
"docstring": "Initialises all the graphical user interfaces necessary to display the data in the table appropriately but also adds functionality to the button, meaning that after the button gets pressed, it will perform a function.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_010703 | Implement the Python class `viewStocks` described below.
Class description:
Implement the viewStocks class.
Method signatures and docstrings:
- def __init__(self): Initialises all the graphical user interfaces necessary to display the data in the table appropriately but also adds functionality to the button, meaning ... | Implement the Python class `viewStocks` described below.
Class description:
Implement the viewStocks class.
Method signatures and docstrings:
- def __init__(self): Initialises all the graphical user interfaces necessary to display the data in the table appropriately but also adds functionality to the button, meaning ... | 5ad535689dfaa6023c3c0fb15bf823c8c46c4cb2 | <|skeleton|>
class viewStocks:
def __init__(self):
"""Initialises all the graphical user interfaces necessary to display the data in the table appropriately but also adds functionality to the button, meaning that after the button gets pressed, it will perform a function."""
<|body_0|>
def oncl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class viewStocks:
def __init__(self):
"""Initialises all the graphical user interfaces necessary to display the data in the table appropriately but also adds functionality to the button, meaning that after the button gets pressed, it will perform a function."""
self.ui = viewStockUI.Ui_viewStockWind... | the_stack_v2_python_sparse | itemBroker.py | DaveLominski/340CT | train | 0 | |
61bd15d80fdffc0e1ecba2bd63d7c69b1501e199 | [
"self.api = api_client\nself.sketch_from_flag = sketch_from_flag\nself.output_format_from_flag = output_format_from_flag\nif not api_client:\n try:\n self.api = timesketch_config.get_client(load_cli_config=True)\n if not self.api:\n raise RequestConnectionError\n except RequestConnect... | <|body_start_0|>
self.api = api_client
self.sketch_from_flag = sketch_from_flag
self.output_format_from_flag = output_format_from_flag
if not api_client:
try:
self.api = timesketch_config.get_client(load_cli_config=True)
if not self.api:
... | Timesketch CLI state object. Attributes: sketch_from_flag: Sketch ID if provided by flag config_assistant: Instance of ConfigAssistant output_format_from_flag: Output format to use | TimesketchCli | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimesketchCli:
"""Timesketch CLI state object. Attributes: sketch_from_flag: Sketch ID if provided by flag config_assistant: Instance of ConfigAssistant output_format_from_flag: Output format to use"""
def __init__(self, api_client=None, sketch_from_flag=None, conf_file='', output_format_fro... | stack_v2_sparse_classes_36k_train_009086 | 6,088 | permissive | [
{
"docstring": "Initialize the state object. Args: sketch_from_flag: Sketch ID if provided by flag. conf_file: Path to the config file. output_format_from_flag: Output format to use.",
"name": "__init__",
"signature": "def __init__(self, api_client=None, sketch_from_flag=None, conf_file='', output_forma... | 3 | null | Implement the Python class `TimesketchCli` described below.
Class description:
Timesketch CLI state object. Attributes: sketch_from_flag: Sketch ID if provided by flag config_assistant: Instance of ConfigAssistant output_format_from_flag: Output format to use
Method signatures and docstrings:
- def __init__(self, api... | Implement the Python class `TimesketchCli` described below.
Class description:
Timesketch CLI state object. Attributes: sketch_from_flag: Sketch ID if provided by flag config_assistant: Instance of ConfigAssistant output_format_from_flag: Output format to use
Method signatures and docstrings:
- def __init__(self, api... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class TimesketchCli:
"""Timesketch CLI state object. Attributes: sketch_from_flag: Sketch ID if provided by flag config_assistant: Instance of ConfigAssistant output_format_from_flag: Output format to use"""
def __init__(self, api_client=None, sketch_from_flag=None, conf_file='', output_format_fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimesketchCli:
"""Timesketch CLI state object. Attributes: sketch_from_flag: Sketch ID if provided by flag config_assistant: Instance of ConfigAssistant output_format_from_flag: Output format to use"""
def __init__(self, api_client=None, sketch_from_flag=None, conf_file='', output_format_from_flag=None):... | the_stack_v2_python_sparse | cli_client/python/timesketch_cli_client/cli.py | google/timesketch | train | 2,263 |
b98c08bad0de239c2ee925087d650a56d44d5243 | [
"super().__init__(document, params.label_map, params.zero_output, NER)\nself.windows = params.windows\nself.embs = [get_loc_embeddings(document), get_embeddings(params.word_vsm, document)]\nif params.name_vsm:\n self.embs.append(get_embeddings(params.name_vsm, document))\nself.embs.append((self.output, self.zero... | <|body_start_0|>
super().__init__(document, params.label_map, params.zero_output, NER)
self.windows = params.windows
self.embs = [get_loc_embeddings(document), get_embeddings(params.word_vsm, document)]
if params.name_vsm:
self.embs.append(get_embeddings(params.name_vsm, docu... | NERState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NERState:
def __init__(self, document, params):
"""NERState inherits the one-pass, left-to-right tagging strategy from ForwardState. :param document: the input document. :type document: elit.nlp.structure.Document :param params: parameters created by NERecognizer.create_params() :type pa... | stack_v2_sparse_classes_36k_train_009087 | 11,455 | permissive | [
{
"docstring": "NERState inherits the one-pass, left-to-right tagging strategy from ForwardState. :param document: the input document. :type document: elit.nlp.structure.Document :param params: parameters created by NERecognizer.create_params() :type params: SimpleNamespace",
"name": "__init__",
"signat... | 3 | stack_v2_sparse_classes_30k_train_019955 | Implement the Python class `NERState` described below.
Class description:
Implement the NERState class.
Method signatures and docstrings:
- def __init__(self, document, params): NERState inherits the one-pass, left-to-right tagging strategy from ForwardState. :param document: the input document. :type document: elit.... | Implement the Python class `NERState` described below.
Class description:
Implement the NERState class.
Method signatures and docstrings:
- def __init__(self, document, params): NERState inherits the one-pass, left-to-right tagging strategy from ForwardState. :param document: the input document. :type document: elit.... | 622b4438ea73c0f235fd1a79b13ee9e6850bfdc9 | <|skeleton|>
class NERState:
def __init__(self, document, params):
"""NERState inherits the one-pass, left-to-right tagging strategy from ForwardState. :param document: the input document. :type document: elit.nlp.structure.Document :param params: parameters created by NERecognizer.create_params() :type pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NERState:
def __init__(self, document, params):
"""NERState inherits the one-pass, left-to-right tagging strategy from ForwardState. :param document: the input document. :type document: elit.nlp.structure.Document :param params: parameters created by NERecognizer.create_params() :type params: SimpleNa... | the_stack_v2_python_sparse | elit/nlp/task/ner.py | hankcs/elit | train | 0 | |
8a963962e46daf24ac38b44877af67fc98fbc557 | [
"if self._coords is None:\n assert self._species is not None\n self._coords = CartesianCoordinates(self._species.coordinates)\nself._update_gradient_and_energy()\nself._solve_subproblem()\nreturn None",
"assert self._coords is not None\nself._coords.h = np.eye(len(self._coords))\nreturn None",
"assert sel... | <|body_start_0|>
if self._coords is None:
assert self._species is not None
self._coords = CartesianCoordinates(self._species.coordinates)
self._update_gradient_and_energy()
self._solve_subproblem()
return None
<|end_body_0|>
<|body_start_1|>
assert self._... | Most simple trust-radius optimiser, solving the subproblem with a cauchy point calculation | CauchyTROptimiser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CauchyTROptimiser:
"""Most simple trust-radius optimiser, solving the subproblem with a cauchy point calculation"""
def _initialise_run(self) -> None:
"""Initialise a TR optimiser, so it can take the first step"""
<|body_0|>
def _update_hessian(self) -> None:
"""... | stack_v2_sparse_classes_36k_train_009088 | 13,234 | permissive | [
{
"docstring": "Initialise a TR optimiser, so it can take the first step",
"name": "_initialise_run",
"signature": "def _initialise_run(self) -> None"
},
{
"docstring": "Hessian is always the identity matrix",
"name": "_update_hessian",
"signature": "def _update_hessian(self) -> None"
... | 4 | stack_v2_sparse_classes_30k_test_000028 | Implement the Python class `CauchyTROptimiser` described below.
Class description:
Most simple trust-radius optimiser, solving the subproblem with a cauchy point calculation
Method signatures and docstrings:
- def _initialise_run(self) -> None: Initialise a TR optimiser, so it can take the first step
- def _update_he... | Implement the Python class `CauchyTROptimiser` described below.
Class description:
Most simple trust-radius optimiser, solving the subproblem with a cauchy point calculation
Method signatures and docstrings:
- def _initialise_run(self) -> None: Initialise a TR optimiser, so it can take the first step
- def _update_he... | 4d6667592f083dfcf38de6b75c4222c0a0e7b60b | <|skeleton|>
class CauchyTROptimiser:
"""Most simple trust-radius optimiser, solving the subproblem with a cauchy point calculation"""
def _initialise_run(self) -> None:
"""Initialise a TR optimiser, so it can take the first step"""
<|body_0|>
def _update_hessian(self) -> None:
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CauchyTROptimiser:
"""Most simple trust-radius optimiser, solving the subproblem with a cauchy point calculation"""
def _initialise_run(self) -> None:
"""Initialise a TR optimiser, so it can take the first step"""
if self._coords is None:
assert self._species is not None
... | the_stack_v2_python_sparse | autode/opt/optimisers/trust_region.py | duartegroup/autodE | train | 132 |
8e2828d8b44921476b5ac8f523d1ca777d70a368 | [
"DE = 0.001\nCHI = 10\nN = 108\nLAM = 306.3\nBETA = 16\nTHC_DIM = 350\noutput = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)\nstps1 = output[0]\noutput = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps1)\nassert output == (10912, 5250145120, 2142)",
"DE = 0.001\nCHI = 10\nN = 152\nLAM = 1201... | <|body_start_0|>
DE = 0.001
CHI = 10
N = 108
LAM = 306.3
BETA = 16
THC_DIM = 350
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)
stps1 = output[0]
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps1)
assert... | THCCostTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
<|body_0|>
def test_li_thc(self):
"""Reproduce Li et al orbital THC FT costs from paper"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
DE = 0.001
... | stack_v2_sparse_classes_36k_train_009089 | 1,527 | permissive | [
{
"docstring": "Reproduce Reiher et al orbital THC FT costs from paper",
"name": "test_reiher_thc",
"signature": "def test_reiher_thc(self)"
},
{
"docstring": "Reproduce Li et al orbital THC FT costs from paper",
"name": "test_li_thc",
"signature": "def test_li_thc(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003217 | Implement the Python class `THCCostTest` described below.
Class description:
Implement the THCCostTest class.
Method signatures and docstrings:
- def test_reiher_thc(self): Reproduce Reiher et al orbital THC FT costs from paper
- def test_li_thc(self): Reproduce Li et al orbital THC FT costs from paper | Implement the Python class `THCCostTest` described below.
Class description:
Implement the THCCostTest class.
Method signatures and docstrings:
- def test_reiher_thc(self): Reproduce Reiher et al orbital THC FT costs from paper
- def test_li_thc(self): Reproduce Li et al orbital THC FT costs from paper
<|skeleton|>
... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
<|body_0|>
def test_li_thc(self):
"""Reproduce Li et al orbital THC FT costs from paper"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
DE = 0.001
CHI = 10
N = 108
LAM = 306.3
BETA = 16
THC_DIM = 350
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)
stp... | the_stack_v2_python_sparse | src/openfermion/resource_estimates/thc/compute_cost_thc_test.py | quantumlib/OpenFermion | train | 1,481 | |
99d8591cafeeb792c35a31ff82efadb80b94246e | [
"if prices == []:\n return 0\nmin_ = prices[0]\nmax_ = prices[0]\nacc = 0\nfor i in prices:\n if i < max_:\n acc += max_ - min_\n min_ = i\n max_ = i\n max_ = i\nacc += max_ - min_\nreturn acc",
"acc = 0\nif len(prices) <= 1:\n return acc\nfor i in range(1, len(prices)):\n if p... | <|body_start_0|>
if prices == []:
return 0
min_ = prices[0]
max_ = prices[0]
acc = 0
for i in prices:
if i < max_:
acc += max_ - min_
min_ = i
max_ = i
max_ = i
acc += max_ - min_
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit_myself(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if prices == []:
retur... | stack_v2_sparse_classes_36k_train_009090 | 912 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_myself",
"signature": "def maxProfit_myself(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit_myself(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit_myself(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 93266095329e2e8e949a72371b88b07382a60e0d | <|skeleton|>
class Solution:
def maxProfit_myself(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit_myself(self, prices):
""":type prices: List[int] :rtype: int"""
if prices == []:
return 0
min_ = prices[0]
max_ = prices[0]
acc = 0
for i in prices:
if i < max_:
acc += max_ - min_
m... | the_stack_v2_python_sparse | maxProfit_2.py | shivangi-prog/leetcode | train | 0 | |
1eb51e9244f0eca75e53700094fcf2ede58ef8ea | [
"end = self.length - 2\ni = 0\nwhile i <= end:\n c1, c2 = self.coordinates[i:i + 2]\n if i < end:\n self.coordinates.insert(i + 2, c2[:])\n end += 1\n if self.premultiplied:\n a, b = (c1[-1], c2[-1])\n a_nan, b_nan = (math.isnan(a), math.isnan(b))\n if not a_nan:\n ... | <|body_start_0|>
end = self.length - 2
i = 0
while i <= end:
c1, c2 = self.coordinates[i:i + 2]
if i < end:
self.coordinates.insert(i + 2, c2[:])
end += 1
if self.premultiplied:
a, b = (c1[-1], c2[-1])
... | Interpolate multiple ranges of colors using linear, Piecewise interpolation. | InterpolatorLinear | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolatorLinear:
"""Interpolate multiple ranges of colors using linear, Piecewise interpolation."""
def setup(self) -> None:
"""Setup for linear interpolation."""
<|body_0|>
def interpolate(self, point: float, index: int) -> Vector:
"""Interpolate."""
... | stack_v2_sparse_classes_36k_train_009091 | 3,867 | permissive | [
{
"docstring": "Setup for linear interpolation.",
"name": "setup",
"signature": "def setup(self) -> None"
},
{
"docstring": "Interpolate.",
"name": "interpolate",
"signature": "def interpolate(self, point: float, index: int) -> Vector"
}
] | 2 | null | Implement the Python class `InterpolatorLinear` described below.
Class description:
Interpolate multiple ranges of colors using linear, Piecewise interpolation.
Method signatures and docstrings:
- def setup(self) -> None: Setup for linear interpolation.
- def interpolate(self, point: float, index: int) -> Vector: Int... | Implement the Python class `InterpolatorLinear` described below.
Class description:
Interpolate multiple ranges of colors using linear, Piecewise interpolation.
Method signatures and docstrings:
- def setup(self) -> None: Setup for linear interpolation.
- def interpolate(self, point: float, index: int) -> Vector: Int... | ad4d779bff57a65b7c77cda0b79c10cf904eb817 | <|skeleton|>
class InterpolatorLinear:
"""Interpolate multiple ranges of colors using linear, Piecewise interpolation."""
def setup(self) -> None:
"""Setup for linear interpolation."""
<|body_0|>
def interpolate(self, point: float, index: int) -> Vector:
"""Interpolate."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterpolatorLinear:
"""Interpolate multiple ranges of colors using linear, Piecewise interpolation."""
def setup(self) -> None:
"""Setup for linear interpolation."""
end = self.length - 2
i = 0
while i <= end:
c1, c2 = self.coordinates[i:i + 2]
if i... | the_stack_v2_python_sparse | lib/coloraide/interpolate/linear.py | facelessuser/ColorHelper | train | 279 |
c6e1b2e3f9b1b14f4881ee9baa0e1999835e5ac2 | [
"width = 3.0\ntriangular_weights_instance = ChooseDefaultWeightsTriangular(width, units='hours')\nresult = str(triangular_weights_instance)\nexpected = '<ChooseDefaultTriangularWeights width=3.0, parameters_units=hours>'\nself.assertEqual(result, expected)",
"width = 3.0\ntriangular_weights_instance = ChooseDefau... | <|body_start_0|>
width = 3.0
triangular_weights_instance = ChooseDefaultWeightsTriangular(width, units='hours')
result = str(triangular_weights_instance)
expected = '<ChooseDefaultTriangularWeights width=3.0, parameters_units=hours>'
self.assertEqual(result, expected)
<|end_body_... | Tests for the __repr__function | Test___repr__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test___repr__:
"""Tests for the __repr__function"""
def test_basic(self):
"""Test the repr function formats the arguments correctly"""
<|body_0|>
def test_basic_no_units(self):
"""Test the repr function formats the arguments correctly"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_009092 | 13,166 | permissive | [
{
"docstring": "Test the repr function formats the arguments correctly",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test the repr function formats the arguments correctly",
"name": "test_basic_no_units",
"signature": "def test_basic_no_units(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016774 | Implement the Python class `Test___repr__` described below.
Class description:
Tests for the __repr__function
Method signatures and docstrings:
- def test_basic(self): Test the repr function formats the arguments correctly
- def test_basic_no_units(self): Test the repr function formats the arguments correctly | Implement the Python class `Test___repr__` described below.
Class description:
Tests for the __repr__function
Method signatures and docstrings:
- def test_basic(self): Test the repr function formats the arguments correctly
- def test_basic_no_units(self): Test the repr function formats the arguments correctly
<|skel... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test___repr__:
"""Tests for the __repr__function"""
def test_basic(self):
"""Test the repr function formats the arguments correctly"""
<|body_0|>
def test_basic_no_units(self):
"""Test the repr function formats the arguments correctly"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test___repr__:
"""Tests for the __repr__function"""
def test_basic(self):
"""Test the repr function formats the arguments correctly"""
width = 3.0
triangular_weights_instance = ChooseDefaultWeightsTriangular(width, units='hours')
result = str(triangular_weights_instance)
... | the_stack_v2_python_sparse | improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py | metoppv/improver | train | 101 |
9e6da15f6e988c32dedd8dd3a2a049e321732176 | [
"self.definitions = definitions\nself.per_client_bandwidth_limits = per_client_bandwidth_limits\nself.dscp_tag_value = dscp_tag_value\nself.priority = priority",
"if dictionary is None:\n return None\ndefinitions = None\nif dictionary.get('definitions') != None:\n definitions = list()\n for structure in ... | <|body_start_0|>
self.definitions = definitions
self.per_client_bandwidth_limits = per_client_bandwidth_limits
self.dscp_tag_value = dscp_tag_value
self.priority = priority
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
definitions = None
... | Implementation of the 'Rule13' model. TODO: type model description here. Attributes: definitions (list of DefinitionModel): A list of objects describing the definitions of your traffic shaping rule. At least one definition is required. per_client_bandwidth_limits (PerClientBandwidthLimitsModel): An object describing th... | Rule13Model | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule13Model:
"""Implementation of the 'Rule13' model. TODO: type model description here. Attributes: definitions (list of DefinitionModel): A list of objects describing the definitions of your traffic shaping rule. At least one definition is required. per_client_bandwidth_limits (PerClientBandwid... | stack_v2_sparse_classes_36k_train_009093 | 3,283 | permissive | [
{
"docstring": "Constructor for the Rule13Model class",
"name": "__init__",
"signature": "def __init__(self, definitions=None, per_client_bandwidth_limits=None, dscp_tag_value=None, priority=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionar... | 2 | stack_v2_sparse_classes_30k_train_010836 | Implement the Python class `Rule13Model` described below.
Class description:
Implementation of the 'Rule13' model. TODO: type model description here. Attributes: definitions (list of DefinitionModel): A list of objects describing the definitions of your traffic shaping rule. At least one definition is required. per_cl... | Implement the Python class `Rule13Model` described below.
Class description:
Implementation of the 'Rule13' model. TODO: type model description here. Attributes: definitions (list of DefinitionModel): A list of objects describing the definitions of your traffic shaping rule. At least one definition is required. per_cl... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class Rule13Model:
"""Implementation of the 'Rule13' model. TODO: type model description here. Attributes: definitions (list of DefinitionModel): A list of objects describing the definitions of your traffic shaping rule. At least one definition is required. per_client_bandwidth_limits (PerClientBandwid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule13Model:
"""Implementation of the 'Rule13' model. TODO: type model description here. Attributes: definitions (list of DefinitionModel): A list of objects describing the definitions of your traffic shaping rule. At least one definition is required. per_client_bandwidth_limits (PerClientBandwidthLimitsModel... | the_stack_v2_python_sparse | meraki_sdk/models/rule_13_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
c64c5d982adfaf94c2561341d502ea5084ddc2f7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessReviewInactiveUsersQueryScope()",
"from .access_review_query_scope import AccessReviewQueryScope\nfrom .access_review_query_scope import AccessReviewQueryScope\nfields: Dict[str, Callable[[Any], None]] = {'inactiveDuration': lamb... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessReviewInactiveUsersQueryScope()
<|end_body_0|>
<|body_start_1|>
from .access_review_query_scope import AccessReviewQueryScope
from .access_review_query_scope import AccessReviewQue... | AccessReviewInactiveUsersQueryScope | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessReviewInactiveUsersQueryScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInactiveUsersQueryScope:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | stack_v2_sparse_classes_36k_train_009094 | 2,516 | 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: AccessReviewInactiveUsersQueryScope",
"name": "create_from_discriminator_value",
"signature": "def create_fr... | 3 | null | Implement the Python class `AccessReviewInactiveUsersQueryScope` described below.
Class description:
Implement the AccessReviewInactiveUsersQueryScope class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInactiveUsersQueryScope: Creates a ... | Implement the Python class `AccessReviewInactiveUsersQueryScope` described below.
Class description:
Implement the AccessReviewInactiveUsersQueryScope class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInactiveUsersQueryScope: Creates a ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessReviewInactiveUsersQueryScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInactiveUsersQueryScope:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessReviewInactiveUsersQueryScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInactiveUsersQueryScope:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/access_review_inactive_users_query_scope.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8341e2dd0837161ea34da559b0af7a3c3dd664da | [
"model = BasicModel()\ncmodel = CompiledModel(model, None, None, ['accuracy'])\nx_data = torch.tensor([[1.0, 2.0, 3.0], [3.0, 2.0, 1.0], [1.0, 2.0, 3.0], [2.0, 3.0, 1.0]])\ny_data = torch.tensor([[1, 0, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0]])\naccuracy = cmodel._calculate_metrics(x_data, y_data)[0]\nassert accuracy =... | <|body_start_0|>
model = BasicModel()
cmodel = CompiledModel(model, None, None, ['accuracy'])
x_data = torch.tensor([[1.0, 2.0, 3.0], [3.0, 2.0, 1.0], [1.0, 2.0, 3.0], [2.0, 3.0, 1.0]])
y_data = torch.tensor([[1, 0, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0]])
accuracy = cmodel._calcula... | TestAccuracyMetric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAccuracyMetric:
def test_accuracy_one_hot_encoded(self):
"""Test accuracy where target is one hot encoded"""
<|body_0|>
def test_accuracy_sparse_encoded(self):
"""Test accuracy where target is sparsely encoded"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_009095 | 22,306 | permissive | [
{
"docstring": "Test accuracy where target is one hot encoded",
"name": "test_accuracy_one_hot_encoded",
"signature": "def test_accuracy_one_hot_encoded(self)"
},
{
"docstring": "Test accuracy where target is sparsely encoded",
"name": "test_accuracy_sparse_encoded",
"signature": "def te... | 2 | stack_v2_sparse_classes_30k_train_013713 | Implement the Python class `TestAccuracyMetric` described below.
Class description:
Implement the TestAccuracyMetric class.
Method signatures and docstrings:
- def test_accuracy_one_hot_encoded(self): Test accuracy where target is one hot encoded
- def test_accuracy_sparse_encoded(self): Test accuracy where target is... | Implement the Python class `TestAccuracyMetric` described below.
Class description:
Implement the TestAccuracyMetric class.
Method signatures and docstrings:
- def test_accuracy_one_hot_encoded(self): Test accuracy where target is one hot encoded
- def test_accuracy_sparse_encoded(self): Test accuracy where target is... | d73b7cac2ca70363d73c5842f2c4b9c2342147c4 | <|skeleton|>
class TestAccuracyMetric:
def test_accuracy_one_hot_encoded(self):
"""Test accuracy where target is one hot encoded"""
<|body_0|>
def test_accuracy_sparse_encoded(self):
"""Test accuracy where target is sparsely encoded"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAccuracyMetric:
def test_accuracy_one_hot_encoded(self):
"""Test accuracy where target is one hot encoded"""
model = BasicModel()
cmodel = CompiledModel(model, None, None, ['accuracy'])
x_data = torch.tensor([[1.0, 2.0, 3.0], [3.0, 2.0, 1.0], [1.0, 2.0, 3.0], [2.0, 3.0, 1.0... | the_stack_v2_python_sparse | keraspytorch.py | mikek64/image_text_labeling | train | 1 | |
bfdb3d02836659d92e1dd30c1796092d9441c74b | [
"self.unity_env = unity_env\nself.unity_env.reset()\nengine_configuration_channel = EngineConfigurationChannel()\nengine_configuration_channel.set_configuration_parameters(time_scale=time_scale, width=width, height=height, target_frame_rate=target_frame_rate, quality_level=quality_level)\nself.unity_env.side_channe... | <|body_start_0|>
self.unity_env = unity_env
self.unity_env.reset()
engine_configuration_channel = EngineConfigurationChannel()
engine_configuration_channel.set_configuration_parameters(time_scale=time_scale, width=width, height=height, target_frame_rate=target_frame_rate, quality_level=q... | Game Class Game is a wrapper that takes a UnityEnvironment and makes a set of NeuralNetworks play in this environment. The game stops when all agents are done and returns their scores. An Agent does not play again when he's done. A Game might contain multiple simulations to make multiple neural networks play at the sam... | Game | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Game Class Game is a wrapper that takes a UnityEnvironment and makes a set of NeuralNetworks play in this environment. The game stops when all agents are done and returns their scores. An Agent does not play again when he's done. A Game might contain multiple simulations to make multiple... | stack_v2_sparse_classes_36k_train_009096 | 3,309 | permissive | [
{
"docstring": "Initializes the game :param unity_env: (UnityEnvironment) Environment where the game will be played :param time_scale:(float) Speed of the game :param width:(int) Window's width :param height:(int) Window's height :param target_frame_rate:(int) Frame rate :param quality_level:(int) Visual qualit... | 2 | stack_v2_sparse_classes_30k_train_011012 | Implement the Python class `Game` described below.
Class description:
Game Class Game is a wrapper that takes a UnityEnvironment and makes a set of NeuralNetworks play in this environment. The game stops when all agents are done and returns their scores. An Agent does not play again when he's done. A Game might contai... | Implement the Python class `Game` described below.
Class description:
Game Class Game is a wrapper that takes a UnityEnvironment and makes a set of NeuralNetworks play in this environment. The game stops when all agents are done and returns their scores. An Agent does not play again when he's done. A Game might contai... | 2083afb187b72e313c8423217bb3bef20a564d44 | <|skeleton|>
class Game:
"""Game Class Game is a wrapper that takes a UnityEnvironment and makes a set of NeuralNetworks play in this environment. The game stops when all agents are done and returns their scores. An Agent does not play again when he's done. A Game might contain multiple simulations to make multiple... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""Game Class Game is a wrapper that takes a UnityEnvironment and makes a set of NeuralNetworks play in this environment. The game stops when all agents are done and returns their scores. An Agent does not play again when he's done. A Game might contain multiple simulations to make multiple neural netwo... | the_stack_v2_python_sparse | game.py | dsapandora/genetic-unity | train | 0 |
a23cd4d90338cf67c3466c238547fd7b09d858c1 | [
"self.fig = Figure(figsize=(width / dpi, height / dpi), dpi=dpi)\nself.fcqt = FigureCanvasQT(self.fig)\nself.ax = self.fcqt.figure.subplots()\nFigureCanvasQTAgg.__init__(self, self.fcqt.figure)\nFigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)\nFigureCanvasQTAgg.updateGeometry(sel... | <|body_start_0|>
self.fig = Figure(figsize=(width / dpi, height / dpi), dpi=dpi)
self.fcqt = FigureCanvasQT(self.fig)
self.ax = self.fcqt.figure.subplots()
FigureCanvasQTAgg.__init__(self, self.fcqt.figure)
FigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.... | The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax (matplotlib.axes.Axes): Axes of th... | BCanvas | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCanvas:
"""The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax... | stack_v2_sparse_classes_36k_train_009097 | 22,292 | permissive | [
{
"docstring": "Initialization of the Bathymetry canvas. It makes a bridge between Matplotlib and the window, creates the figure to display and then show statically or dynamically the figure. Args: parent (QWidget): Parent of the canvas (default: None). width (int): Width of the canvas (default: 800). height (i... | 4 | stack_v2_sparse_classes_30k_train_001274 | Implement the Python class `BCanvas` described below.
Class description:
The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvas... | Implement the Python class `BCanvas` described below.
Class description:
The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvas... | 0b39cd5e499f6168f10906d29ef826ab9aaa45c4 | <|skeleton|>
class BCanvas:
"""The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BCanvas:
"""The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax (matplotlib.... | the_stack_v2_python_sparse | src/graphics/ApplicationWindow.py | GregoireThoumyre/Bathymetry-Inversion | train | 1 |
681261529b617333acfffba92e5d9b76facb2ff6 | [
"obj_action = self.pool.get('ir.actions.act_window')\nobj_model = self.pool.get('ir.model.data')\nfor thisrule in self.browse(cr, uid, ids):\n obj = self.pool.get(thisrule.object_id.model)\n if not obj:\n raise osv.except_osv(_('WARNING: audittrail is not part of the pool'), _('Change audittrail depend... | <|body_start_0|>
obj_action = self.pool.get('ir.actions.act_window')
obj_model = self.pool.get('ir.model.data')
for thisrule in self.browse(cr, uid, ids):
obj = self.pool.get(thisrule.object_id.model)
if not obj:
raise osv.except_osv(_('WARNING: audittrail... | For Auddittrail Rule | audittrail_rule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class audittrail_rule:
"""For Auddittrail Rule"""
def subscribe(self, cr, uid, ids, *args):
"""Subscribe Rule for auditing changes on object and apply shortcut for logs on that object. @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security chec... | stack_v2_sparse_classes_36k_train_009098 | 28,495 | no_license | [
{
"docstring": "Subscribe Rule for auditing changes on object and apply shortcut for logs on that object. @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of Auddittrail Rule’s IDs. @return: True",
"name": "subscribe",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_004379 | Implement the Python class `audittrail_rule` described below.
Class description:
For Auddittrail Rule
Method signatures and docstrings:
- def subscribe(self, cr, uid, ids, *args): Subscribe Rule for auditing changes on object and apply shortcut for logs on that object. @param cr: the current row, from the database cu... | Implement the Python class `audittrail_rule` described below.
Class description:
For Auddittrail Rule
Method signatures and docstrings:
- def subscribe(self, cr, uid, ids, *args): Subscribe Rule for auditing changes on object and apply shortcut for logs on that object. @param cr: the current row, from the database cu... | 3de4017d4df223a7596532394eda25e590081e94 | <|skeleton|>
class audittrail_rule:
"""For Auddittrail Rule"""
def subscribe(self, cr, uid, ids, *args):
"""Subscribe Rule for auditing changes on object and apply shortcut for logs on that object. @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security chec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class audittrail_rule:
"""For Auddittrail Rule"""
def subscribe(self, cr, uid, ids, *args):
"""Subscribe Rule for auditing changes on object and apply shortcut for logs on that object. @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param id... | the_stack_v2_python_sparse | audittrail/audittrail.py | iw3hxn/addons | train | 2 |
9fa97f824ebc8f8112cd789c4ca375073e721fb0 | [
"model = ZHtmlTableModel(None)\ndialog = ZInsertTableDialog(parentWindow, model)\ndialog.CentreOnParent()\nif dialog.ShowModal() == wx.ID_OK:\n attrs = model.getTableAttributes()\n tableContext.insertTable(attrs)\ndialog.Destroy()",
"model = ZHtmlTableModel(tableContext.getTableAttributes())\ndialog = ZInse... | <|body_start_0|>
model = ZHtmlTableModel(None)
dialog = ZInsertTableDialog(parentWindow, model)
dialog.CentreOnParent()
if dialog.ShowModal() == wx.ID_OK:
attrs = model.getTableAttributes()
tableContext.insertTable(attrs)
dialog.Destroy()
<|end_body_0|>
<... | ZTableUiUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZTableUiUtil:
def insertTable(self, parentWindow, tableContext):
"""insertTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the create and edit table dialog."""
<|body_0|>
def editTable(self, parentWindow, tableContext):
"""editTable(wxWindow, IZXHTMLEdit... | stack_v2_sparse_classes_36k_train_009099 | 9,326 | no_license | [
{
"docstring": "insertTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the create and edit table dialog.",
"name": "insertTable",
"signature": "def insertTable(self, parentWindow, tableContext)"
},
{
"docstring": "editTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the... | 2 | null | Implement the Python class `ZTableUiUtil` described below.
Class description:
Implement the ZTableUiUtil class.
Method signatures and docstrings:
- def insertTable(self, parentWindow, tableContext): insertTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the create and edit table dialog.
- def editTable(s... | Implement the Python class `ZTableUiUtil` described below.
Class description:
Implement the ZTableUiUtil class.
Method signatures and docstrings:
- def insertTable(self, parentWindow, tableContext): insertTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the create and edit table dialog.
- def editTable(s... | f1096a02a3dbb25a79d5c4e6a2f71a3d469631eb | <|skeleton|>
class ZTableUiUtil:
def insertTable(self, parentWindow, tableContext):
"""insertTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the create and edit table dialog."""
<|body_0|>
def editTable(self, parentWindow, tableContext):
"""editTable(wxWindow, IZXHTMLEdit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZTableUiUtil:
def insertTable(self, parentWindow, tableContext):
"""insertTable(wxWindow, IZXHTMLEditControlTableContext) -> void Shows the create and edit table dialog."""
model = ZHtmlTableModel(None)
dialog = ZInsertTableDialog(parentWindow, model)
dialog.CentreOnParent()
... | the_stack_v2_python_sparse | src/python/zoundry/blogapp/ui/util/editorutil.py | mpm2050/Raven | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.