blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6932b54e6f076c25a26099e948fd818f0ac8d8d5 | [
"self._inputs = inputs\nif self._inputs < 2:\n raise Exception(('spam', 'eggs'))\nself._dimensions = self.initDimensions(inputs)\nComponent.__init__(self, canvas, location, self._dimensions[0], self._dimensions[1], direction, width)\nself._inputList = []",
"widthx = inputs / sqrt(inputs * 2) * WIDTH\nheight = ... | <|body_start_0|>
self._inputs = inputs
if self._inputs < 2:
raise Exception(('spam', 'eggs'))
self._dimensions = self.initDimensions(inputs)
Component.__init__(self, canvas, location, self._dimensions[0], self._dimensions[1], direction, width)
self._inputList = []
<|e... | A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs. | MultiInSingleOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiInSingleOut:
"""A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs."""
def __init__(self, canvas, location, direction=E... | stack_v2_sparse_classes_10k_train_008800 | 8,062 | no_license | [
{
"docstring": "Initializes a Component instance with a certain number of inputs and dimensions which are dependent on the number of inputs.",
"name": "__init__",
"signature": "def __init__(self, canvas, location, direction=E, width=1, inputs=2, size=1)"
},
{
"docstring": "Initialize the dimensi... | 4 | stack_v2_sparse_classes_30k_train_007121 | Implement the Python class `MultiInSingleOut` described below.
Class description:
A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs.
Method signature... | Implement the Python class `MultiInSingleOut` described below.
Class description:
A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs.
Method signature... | 5b046f6ccacd397df7b319a9f96235dba4b653d7 | <|skeleton|>
class MultiInSingleOut:
"""A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs."""
def __init__(self, canvas, location, direction=E... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiInSingleOut:
"""A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs."""
def __init__(self, canvas, location, direction=E, width=1, in... | the_stack_v2_python_sparse | AntiochComponent.py | piannaf/Antioch | train | 0 |
41d8a75a3c85cdf5d2e1a1cf78f0a9adaf2eff45 | [
"self.n_sent = 1\nself.data = data\nself.empty = False\nagg_func = lambda s: [(w, t) for w, t in zip(s[word_column].values.tolist(), s[tag_column].values.tolist())]\nself.grouped = self.data.groupby(sentence_column).apply(agg_func)\nself.sentences = [s for s in self.grouped]",
"try:\n s = self.grouped['Sentenc... | <|body_start_0|>
self.n_sent = 1
self.data = data
self.empty = False
agg_func = lambda s: [(w, t) for w, t in zip(s[word_column].values.tolist(), s[tag_column].values.tolist())]
self.grouped = self.data.groupby(sentence_column).apply(agg_func)
self.sentences = [s for s in... | Class to Get the sentence in this format: [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)] | SentenceGetter | [
"Apache-2.0",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentenceGetter:
"""Class to Get the sentence in this format: [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)]"""
def __init__(self, data, word_column, tag_column, sentence_column):
"""Args: data is the pandas.DataFrame which contains the above dataset"""
... | stack_v2_sparse_classes_10k_train_008801 | 7,705 | permissive | [
{
"docstring": "Args: data is the pandas.DataFrame which contains the above dataset",
"name": "__init__",
"signature": "def __init__(self, data, word_column, tag_column, sentence_column)"
},
{
"docstring": "Return one sentence",
"name": "get_next",
"signature": "def get_next(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002739 | Implement the Python class `SentenceGetter` described below.
Class description:
Class to Get the sentence in this format: [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)]
Method signatures and docstrings:
- def __init__(self, data, word_column, tag_column, sentence_column): Args: data is ... | Implement the Python class `SentenceGetter` described below.
Class description:
Class to Get the sentence in this format: [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)]
Method signatures and docstrings:
- def __init__(self, data, word_column, tag_column, sentence_column): Args: data is ... | ab03ae68053b727cb8907e08c35f265531d1cb3a | <|skeleton|>
class SentenceGetter:
"""Class to Get the sentence in this format: [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)]"""
def __init__(self, data, word_column, tag_column, sentence_column):
"""Args: data is the pandas.DataFrame which contains the above dataset"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SentenceGetter:
"""Class to Get the sentence in this format: [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)]"""
def __init__(self, data, word_column, tag_column, sentence_column):
"""Args: data is the pandas.DataFrame which contains the above dataset"""
self.... | the_stack_v2_python_sparse | ktrain/text/ner/preprocessor.py | amaiya/ktrain | train | 1,217 |
dbdd9f777e41dd16832c075db145f1d1e32cd076 | [
"m, n = (len(dungeon), len(dungeon[0]))\ndp = [[1] * n for i in range(m)]\ndp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1])\nfor i in range(m - 2, -1, -1):\n dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1])\nfor j in range(n - 1, -1, -1):\n dp[m - 1][j] = max(1, dp[m - 1][j + 1] - dungeon[m - 1... | <|body_start_0|>
m, n = (len(dungeon), len(dungeon[0]))
dp = [[1] * n for i in range(m)]
dp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1])
for i in range(m - 2, -1, -1):
dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1])
for j in range(n - 1, -1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
<|body_0|>
def calculateMinimumHP1(self, dun... | stack_v2_sparse_classes_10k_train_008802 | 2,996 | no_license | [
{
"docstring": "dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))",
"name": "calculateMinimumHP1",
"signature": "def calculateMinimumHP1(self, dungeon)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_001036 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP1(self, dungeon): dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP1(self, dungeon): dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]),... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
<|body_0|>
def calculateMinimumHP1(self, dun... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
m, n = (len(dungeon), len(dungeon[0]))
dp = [[1] * n fo... | the_stack_v2_python_sparse | Leetcode 0174. Dungeon Game.py | Chaoran-sjsu/leetcode | train | 0 | |
7e18f3a53eb3da2fc84c24b88957c8bf4d775c1e | [
"if self._units in ('C', 'F'):\n return round(self._state, 1)\nif isinstance(self._state, float):\n return round(self._state, 2)\nreturn self._state",
"if self._units in ['C', 'F']:\n return DEVICE_CLASS_TEMPERATURE\nreturn None",
"if self._units == 'C':\n return TEMP_CELSIUS\nif self._units == 'F':... | <|body_start_0|>
if self._units in ('C', 'F'):
return round(self._state, 1)
if isinstance(self._state, float):
return round(self._state, 2)
return self._state
<|end_body_0|>
<|body_start_1|>
if self._units in ['C', 'F']:
return DEVICE_CLASS_TEMPERATUR... | Representation of a multi level sensor Z-Wave sensor. | ZWaveMultilevelSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveMultilevelSensor:
"""Representation of a multi level sensor Z-Wave sensor."""
def state(self):
"""Return the state of the sensor."""
<|body_0|>
def device_class(self):
"""Return the class of this device."""
<|body_1|>
def unit_of_measurement(sel... | stack_v2_sparse_classes_10k_train_008803 | 3,651 | permissive | [
{
"docstring": "Return the state of the sensor.",
"name": "state",
"signature": "def state(self)"
},
{
"docstring": "Return the class of this device.",
"name": "device_class",
"signature": "def device_class(self)"
},
{
"docstring": "Return the unit the value is expressed in.",
... | 3 | null | Implement the Python class `ZWaveMultilevelSensor` described below.
Class description:
Representation of a multi level sensor Z-Wave sensor.
Method signatures and docstrings:
- def state(self): Return the state of the sensor.
- def device_class(self): Return the class of this device.
- def unit_of_measurement(self): ... | Implement the Python class `ZWaveMultilevelSensor` described below.
Class description:
Representation of a multi level sensor Z-Wave sensor.
Method signatures and docstrings:
- def state(self): Return the state of the sensor.
- def device_class(self): Return the class of this device.
- def unit_of_measurement(self): ... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ZWaveMultilevelSensor:
"""Representation of a multi level sensor Z-Wave sensor."""
def state(self):
"""Return the state of the sensor."""
<|body_0|>
def device_class(self):
"""Return the class of this device."""
<|body_1|>
def unit_of_measurement(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZWaveMultilevelSensor:
"""Representation of a multi level sensor Z-Wave sensor."""
def state(self):
"""Return the state of the sensor."""
if self._units in ('C', 'F'):
return round(self._state, 1)
if isinstance(self._state, float):
return round(self._state,... | the_stack_v2_python_sparse | homeassistant/components/zwave/sensor.py | BenWoodford/home-assistant | train | 11 |
41930511464d501e34aef5e0ab72a94c4f786d2e | [
"for k in filter_munge:\n if k in params and params[k] in ['true', '1']:\n params[k] = 'True'\n if k in params and params[k] in ['false', '0']:\n params[k] = 'False'\nreturn params",
"filter_class = self.get_filter_class(view, queryset)\nfilter_munge = getattr(view, 'filter_munge', ())\nparams... | <|body_start_0|>
for k in filter_munge:
if k in params and params[k] in ['true', '1']:
params[k] = 'True'
if k in params and params[k] in ['false', '0']:
params[k] = 'False'
return params
<|end_body_0|>
<|body_start_1|>
filter_class = self... | MktFilterBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MktFilterBackend:
def munge_params(self, filter_munge, params):
"""Cast some more things as truthful."""
<|body_0|>
def filter_queryset(self, request, queryset, view):
"""Overriding DRF in order to munging the incoming params. It will only munge fields that are in th... | stack_v2_sparse_classes_10k_train_008804 | 1,040 | permissive | [
{
"docstring": "Cast some more things as truthful.",
"name": "munge_params",
"signature": "def munge_params(self, filter_munge, params)"
},
{
"docstring": "Overriding DRF in order to munging the incoming params. It will only munge fields that are in the filter_munge tuple on the view, other fiel... | 2 | stack_v2_sparse_classes_30k_test_000295 | Implement the Python class `MktFilterBackend` described below.
Class description:
Implement the MktFilterBackend class.
Method signatures and docstrings:
- def munge_params(self, filter_munge, params): Cast some more things as truthful.
- def filter_queryset(self, request, queryset, view): Overriding DRF in order to ... | Implement the Python class `MktFilterBackend` described below.
Class description:
Implement the MktFilterBackend class.
Method signatures and docstrings:
- def munge_params(self, filter_munge, params): Cast some more things as truthful.
- def filter_queryset(self, request, queryset, view): Overriding DRF in order to ... | 5fa5400a447f2e905372d4c8eba6d959d22d4f3e | <|skeleton|>
class MktFilterBackend:
def munge_params(self, filter_munge, params):
"""Cast some more things as truthful."""
<|body_0|>
def filter_queryset(self, request, queryset, view):
"""Overriding DRF in order to munging the incoming params. It will only munge fields that are in th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MktFilterBackend:
def munge_params(self, filter_munge, params):
"""Cast some more things as truthful."""
for k in filter_munge:
if k in params and params[k] in ['true', '1']:
params[k] = 'True'
if k in params and params[k] in ['false', '0']:
... | the_stack_v2_python_sparse | mkt/api/filters.py | sarvex/zamboni | train | 0 | |
453d1044b80466a8c8831f0b0aec92d202c01419 | [
"if not root:\n return ''\nfrom collections import deque\nq = deque([root])\nans = []\nwhile q:\n node = q.popleft()\n ans.append(str(node.val) if node else '#')\n if node:\n q.extend([node.left, node.right])\nreturn ','.join(ans)",
"data = json.dumps(data)\nif not data:\n return\nnodes = [T... | <|body_start_0|>
if not root:
return ''
from collections import deque
q = deque([root])
ans = []
while q:
node = q.popleft()
ans.append(str(node.val) if node else '#')
if node:
q.extend([node.left, node.right])
... | TreeCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeCreator:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: list :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_008805 | 7,485 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: list :rtype: TreeNode",
"name": "deserialize",
"signature": "def deseriali... | 2 | null | Implement the Python class `TreeCreator` described below.
Class description:
Implement the TreeCreator class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data:... | Implement the Python class `TreeCreator` described below.
Class description:
Implement the TreeCreator class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data:... | 3d5a96d896ede3ea979783b8053487fe44e38969 | <|skeleton|>
class TreeCreator:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: list :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TreeCreator:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
from collections import deque
q = deque([root])
ans = []
while q:
node = q.popleft()
ans.... | the_stack_v2_python_sparse | utils/util_funcs.py | lichangg/myleet | train | 1 | |
f9170b9912c228cfa84c28c689686b5386e0da78 | [
"self.old_username = self.instance.username\nself.old_file_root = self.instance.file_root()\nif User.objects.filter(username__iexact=self.cleaned_data['username']):\n raise forms.ValidationError('A user with that username already exists.')\nreturn self.cleaned_data['username'].lower()",
"new_username = self.cl... | <|body_start_0|>
self.old_username = self.instance.username
self.old_file_root = self.instance.file_root()
if User.objects.filter(username__iexact=self.cleaned_data['username']):
raise forms.ValidationError('A user with that username already exists.')
return self.cleaned_data... | Updating the username filed | UsernameChangeForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsernameChangeForm:
"""Updating the username filed"""
def clean_username(self):
"""Record the original username in case it is needed"""
<|body_0|>
def save(self):
"""Change the media file directory name and photo name if any, to match the new username"""
... | stack_v2_sparse_classes_10k_train_008806 | 26,163 | permissive | [
{
"docstring": "Record the original username in case it is needed",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Change the media file directory name and photo name if any, to match the new username",
"name": "save",
"signature": "def save(self)"
... | 2 | stack_v2_sparse_classes_30k_train_004933 | Implement the Python class `UsernameChangeForm` described below.
Class description:
Updating the username filed
Method signatures and docstrings:
- def clean_username(self): Record the original username in case it is needed
- def save(self): Change the media file directory name and photo name if any, to match the new... | Implement the Python class `UsernameChangeForm` described below.
Class description:
Updating the username filed
Method signatures and docstrings:
- def clean_username(self): Record the original username in case it is needed
- def save(self): Change the media file directory name and photo name if any, to match the new... | e7c8ed0b07a4c9a1b4007f6089f59aafa6a3ac57 | <|skeleton|>
class UsernameChangeForm:
"""Updating the username filed"""
def clean_username(self):
"""Record the original username in case it is needed"""
<|body_0|>
def save(self):
"""Change the media file directory name and photo name if any, to match the new username"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UsernameChangeForm:
"""Updating the username filed"""
def clean_username(self):
"""Record the original username in case it is needed"""
self.old_username = self.instance.username
self.old_file_root = self.instance.file_root()
if User.objects.filter(username__iexact=self.cl... | the_stack_v2_python_sparse | physionet-django/user/forms.py | tompollard/physionet-build | train | 0 |
43b5f5a9b95dccb6133c7e2c8a2158466f958f3e | [
"if ADDRESS_NOT_FOUND:\n return HttpResponseNotFound(ADDRESS_NOT_FOUND_MSG)\nreturn Response([{'ruleId': 0, 'ruleAddress': ruleAddress, 'ruleFrom': True, 'ruleTo': True, 'ruleReason': 'string'}])",
"if ADDRESS_NOT_FOUND:\n return HttpResponseNotFound(ADDRESS_NOT_FOUND_MSG)\nif len(request.data) != 3:\n r... | <|body_start_0|>
if ADDRESS_NOT_FOUND:
return HttpResponseNotFound(ADDRESS_NOT_FOUND_MSG)
return Response([{'ruleId': 0, 'ruleAddress': ruleAddress, 'ruleFrom': True, 'ruleTo': True, 'ruleReason': 'string'}])
<|end_body_0|>
<|body_start_1|>
if ADDRESS_NOT_FOUND:
return H... | [GET] /mailFilter/{ruleAddress} Get all rules with specified ruleAddress [PUT] /mailFilter/{ruleAddress} Change a reason and direction for all rules with the specified e-mail address [DELETE] /mailFilter/{ruleAddress} Delete all rules for specified e-mail address and direction (from or to) | MailFilterRuleAddress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailFilterRuleAddress:
"""[GET] /mailFilter/{ruleAddress} Get all rules with specified ruleAddress [PUT] /mailFilter/{ruleAddress} Change a reason and direction for all rules with the specified e-mail address [DELETE] /mailFilter/{ruleAddress} Delete all rules for specified e-mail address and dir... | stack_v2_sparse_classes_10k_train_008807 | 6,047 | permissive | [
{
"docstring": ":param ruleAddress: e-mail address",
"name": "get",
"signature": "def get(self, request, ruleAddress, **kwargs)"
},
{
"docstring": ":param ruleAddress: e-mail address",
"name": "put",
"signature": "def put(self, request, ruleAddress, **kwargs)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_004405 | Implement the Python class `MailFilterRuleAddress` described below.
Class description:
[GET] /mailFilter/{ruleAddress} Get all rules with specified ruleAddress [PUT] /mailFilter/{ruleAddress} Change a reason and direction for all rules with the specified e-mail address [DELETE] /mailFilter/{ruleAddress} Delete all rul... | Implement the Python class `MailFilterRuleAddress` described below.
Class description:
[GET] /mailFilter/{ruleAddress} Get all rules with specified ruleAddress [PUT] /mailFilter/{ruleAddress} Change a reason and direction for all rules with the specified e-mail address [DELETE] /mailFilter/{ruleAddress} Delete all rul... | 73e4ac0ced6c3ac46d24ac5c3feb01a1e88bd36b | <|skeleton|>
class MailFilterRuleAddress:
"""[GET] /mailFilter/{ruleAddress} Get all rules with specified ruleAddress [PUT] /mailFilter/{ruleAddress} Change a reason and direction for all rules with the specified e-mail address [DELETE] /mailFilter/{ruleAddress} Delete all rules for specified e-mail address and dir... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MailFilterRuleAddress:
"""[GET] /mailFilter/{ruleAddress} Get all rules with specified ruleAddress [PUT] /mailFilter/{ruleAddress} Change a reason and direction for all rules with the specified e-mail address [DELETE] /mailFilter/{ruleAddress} Delete all rules for specified e-mail address and direction (from ... | the_stack_v2_python_sparse | crusoe_act/act-component/mailFilter-wrapper/mailFilter_wrapper_project/views.py | wumingruiye/CRUSOE | train | 0 |
73369719d1b6e81c208100fbf27cd79de9ab5fdf | [
"if isinstance(key, int):\n return Routing(key)\nif key not in Routing._member_map_:\n extend_enum(Routing, key, default)\nreturn Routing[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 5 <= value <= 252:\n extend_en... | <|body_start_0|>
if isinstance(key, int):
return Routing(key)
if key not in Routing._member_map_:
extend_enum(Routing, key, default)
return Routing[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise Value... | [Routing] IPv6 Routing Types | Routing | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Routing:
"""[Routing] IPv6 Routing Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_008808 | 1,523 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002274 | Implement the Python class `Routing` described below.
Class description:
[Routing] IPv6 Routing Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Routing` described below.
Class description:
[Routing] IPv6 Routing Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Routing:
"""[Routi... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class Routing:
"""[Routing] IPv6 Routing Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Routing:
"""[Routing] IPv6 Routing Types"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Routing(key)
if key not in Routing._member_map_:
extend_enum(Routing, key, default)
return Routing[key]
... | the_stack_v2_python_sparse | pcapkit/const/ipv6/routing.py | stjordanis/PyPCAPKit | train | 0 |
123e088cafc8e624e4ddbb680a0f4ee775aad23e | [
"super().__init__()\nself.nf = nf\nw = torch.empty(nx, nf)\nnn.init.normal_(w, std=0.02)\nself.weight = nn.Parameter(w)\nself.bias = nn.Parameter(torch.zeros(nf))",
"size_out = x.size()[:-1] + (self.nf,)\nx = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)\nx = x.view(*size_out)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.nf = nf
w = torch.empty(nx, nf)
nn.init.normal_(w, std=0.02)
self.weight = nn.Parameter(w)
self.bias = nn.Parameter(torch.zeros(nf))
<|end_body_0|>
<|body_start_1|>
size_out = x.size()[:-1] + (self.nf,)
x = torch.a... | 1D-convolutional layer (eqv to FCN) as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Note: Code adopted from: https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py Args: nf (int): The number of ... | Conv1D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1D:
"""1D-convolutional layer (eqv to FCN) as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Note: Code adopted from: https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils... | stack_v2_sparse_classes_10k_train_008809 | 2,885 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, nf: int, nx: int) -> None"
},
{
"docstring": "Forward pass Args: x (Tensor): [..., nx] input features Returns: Tensor: [..., nf] output features",
"name": "forward",
"signature": "def forward(self, x: Tens... | 2 | stack_v2_sparse_classes_30k_train_002777 | Implement the Python class `Conv1D` described below.
Class description:
1D-convolutional layer (eqv to FCN) as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Note: Code adopted from: https://github.com/huggingface/transformers/blob... | Implement the Python class `Conv1D` described below.
Class description:
1D-convolutional layer (eqv to FCN) as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Note: Code adopted from: https://github.com/huggingface/transformers/blob... | eb28d09957641cc594b3e5acf4ace2e4dc193584 | <|skeleton|>
class Conv1D:
"""1D-convolutional layer (eqv to FCN) as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Note: Code adopted from: https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Conv1D:
"""1D-convolutional layer (eqv to FCN) as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Note: Code adopted from: https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py Args: nf ... | the_stack_v2_python_sparse | trphysx/transformer/utils.py | yus-nas/transformer-physx | train | 0 |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('registered_courses', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Registered Courses To Display'\ncontext['detail_tex... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('registered_courses', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
contex... | View for choosing which registered course to display. Check that the user's account is still active. Redirects to registered_courses view on form valid. | ShowRegisteredCourseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowRegisteredCourseView:
"""View for choosing which registered course to display. Check that the user's account is still active. Redirects to registered_courses view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|bod... | stack_v2_sparse_classes_10k_train_008810 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_006237 | Implement the Python class `ShowRegisteredCourseView` described below.
Class description:
View for choosing which registered course to display. Check that the user's account is still active. Redirects to registered_courses view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the... | Implement the Python class `ShowRegisteredCourseView` described below.
Class description:
View for choosing which registered course to display. Check that the user's account is still active. Redirects to registered_courses view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class ShowRegisteredCourseView:
"""View for choosing which registered course to display. Check that the user's account is still active. Redirects to registered_courses view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShowRegisteredCourseView:
"""View for choosing which registered course to display. Check that the user's account is still active. Redirects to registered_courses view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleane... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
ff99a57a442e20567ade79c04eebc700c4f41b77 | [
"total = 0\ndct = {}\nfor i in range(len(time) - 1, -1, -1):\n tmp = time[i] % 60\n if tmp == 0 and dct.get(tmp, None):\n total += dct[tmp]\n elif dct.get(60 - tmp, None):\n total += dct[60 - tmp]\n dct[tmp] = dct.get(tmp, 0) + 1\nreturn total",
"total = 0\nfor i in range(len(time)):\n ... | <|body_start_0|>
total = 0
dct = {}
for i in range(len(time) - 1, -1, -1):
tmp = time[i] % 60
if tmp == 0 and dct.get(tmp, None):
total += dct[tmp]
elif dct.get(60 - tmp, None):
total += dct[60 - tmp]
dct[tmp] = dct.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numPairsDivisibleBy60(self, time):
""":type time: List[int] :rtype: int"""
<|body_0|>
def numPairsDivisibleBy60_bruce_force(self, time):
"""exceed time limit :type time: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_008811 | 1,913 | no_license | [
{
"docstring": ":type time: List[int] :rtype: int",
"name": "numPairsDivisibleBy60",
"signature": "def numPairsDivisibleBy60(self, time)"
},
{
"docstring": "exceed time limit :type time: List[int] :rtype: int",
"name": "numPairsDivisibleBy60_bruce_force",
"signature": "def numPairsDivisi... | 2 | stack_v2_sparse_classes_30k_train_002778 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numPairsDivisibleBy60(self, time): :type time: List[int] :rtype: int
- def numPairsDivisibleBy60_bruce_force(self, time): exceed time limit :type time: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numPairsDivisibleBy60(self, time): :type time: List[int] :rtype: int
- def numPairsDivisibleBy60_bruce_force(self, time): exceed time limit :type time: List[int] :rtype: int
... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def numPairsDivisibleBy60(self, time):
""":type time: List[int] :rtype: int"""
<|body_0|>
def numPairsDivisibleBy60_bruce_force(self, time):
"""exceed time limit :type time: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numPairsDivisibleBy60(self, time):
""":type time: List[int] :rtype: int"""
total = 0
dct = {}
for i in range(len(time) - 1, -1, -1):
tmp = time[i] % 60
if tmp == 0 and dct.get(tmp, None):
total += dct[tmp]
elif d... | the_stack_v2_python_sparse | python/1010.pairs-of-songs-with-total-durations-divisible-by-60.py | tainenko/Leetcode2019 | train | 5 | |
7f1bfe584ab5c65f6113c958a3cdf6d7ea934dfb | [
"self.capacity = capacity\nself.size = 0\nself.cache = dict()\nself.linkedlist = LinkedList()",
"node = self.cache.get(key)\nif node is None:\n return -1\nval = node.val\nself.linkedlist.move_to_front(node)\nreturn val",
"if key in self.cache:\n node = self.cache[key]\n node.val = value\n self.linke... | <|body_start_0|>
self.capacity = capacity
self.size = 0
self.cache = dict()
self.linkedlist = LinkedList()
<|end_body_0|>
<|body_start_1|>
node = self.cache.get(key)
if node is None:
return -1
val = node.val
self.linkedlist.move_to_front(node)... | 最久未使用缓存 | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""最久未使用缓存"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<... | stack_v2_sparse_classes_10k_train_008812 | 3,317 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
最久未使用缓存
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
最久未使用缓存
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|skeleton|>
class LRUCach... | 4f5f5124534bd4423356a5f5572b8a39b7828d80 | <|skeleton|>
class LRUCache:
"""最久未使用缓存"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
"""最久未使用缓存"""
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.size = 0
self.cache = dict()
self.linkedlist = LinkedList()
def get(self, key):
""":type key: int :rtype: int"""
node = self.cache.get... | the_stack_v2_python_sparse | leetcode/lru-cache/147339447.py | ausaki/data_structures_and_algorithms | train | 1 |
25a37b381847da5cc83a0ef0fb4ca098ce5af34f | [
"is_markerless = node_types.MARKERLESS_REGEX.match\nprefix = list(takewhile(lambda l: not is_markerless(l), node['label']))\nif 'intro' in prefix:\n title = node.get('title', '').rstrip(':')\n return 'Intro: ' + title\nelif len(prefix) > 1:\n label = 'Section ' + '.'.join(prefix[1:])\n count = len(node[... | <|body_start_0|>
is_markerless = node_types.MARKERLESS_REGEX.match
prefix = list(takewhile(lambda l: not is_markerless(l), node['label']))
if 'intro' in prefix:
title = node.get('title', '').rstrip(':')
return 'Intro: ' + title
elif len(prefix) > 1:
la... | PreambleHTMLBuilder | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreambleHTMLBuilder:
def human_label(node):
"""Derive a human-readable description for this node. Override"""
<|body_0|>
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_008813 | 9,837 | permissive | [
{
"docstring": "Derive a human-readable description for this node. Override",
"name": "human_label",
"signature": "def human_label(node)"
},
{
"docstring": "Overrides with custom, additional processing",
"name": "process_node",
"signature": "def process_node(self, node, indexes=None)"
... | 2 | stack_v2_sparse_classes_30k_train_003977 | Implement the Python class `PreambleHTMLBuilder` described below.
Class description:
Implement the PreambleHTMLBuilder class.
Method signatures and docstrings:
- def human_label(node): Derive a human-readable description for this node. Override
- def process_node(self, node, indexes=None): Overrides with custom, addi... | Implement the Python class `PreambleHTMLBuilder` described below.
Class description:
Implement the PreambleHTMLBuilder class.
Method signatures and docstrings:
- def human_label(node): Derive a human-readable description for this node. Override
- def process_node(self, node, indexes=None): Overrides with custom, addi... | 4035701a953409bbb1987d371edc6630fd97a862 | <|skeleton|>
class PreambleHTMLBuilder:
def human_label(node):
"""Derive a human-readable description for this node. Override"""
<|body_0|>
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PreambleHTMLBuilder:
def human_label(node):
"""Derive a human-readable description for this node. Override"""
is_markerless = node_types.MARKERLESS_REGEX.match
prefix = list(takewhile(lambda l: not is_markerless(l), node['label']))
if 'intro' in prefix:
title = node... | the_stack_v2_python_sparse | regulations/generator/html_builder.py | fecgov/regulations-site | train | 1 | |
b826610512ac010529b36a12de4f4f1156bcd1b8 | [
"self.response = response\nself.log_function = logfunc\nself.error = err\nself.data = ''\nself.status = 0\nif self.response:\n self.status = self.response.getcode()\n result = self.response.read()\n while result:\n self.data += result\n result = self.response.read()\nif self.error:\n self.... | <|body_start_0|>
self.response = response
self.log_function = logfunc
self.error = err
self.data = ''
self.status = 0
if self.response:
self.status = self.response.getcode()
result = self.response.read()
while result:
se... | Result from a REST API operation. | RestResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestResult:
"""Result from a REST API operation."""
def __init__(self, logfunc=None, response=None, err=None):
"""Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error."""
<|... | stack_v2_sparse_classes_10k_train_008814 | 12,813 | permissive | [
{
"docstring": "Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error.",
"name": "__init__",
"signature": "def __init__(self, logfunc=None, response=None, err=None)"
},
{
"docstring": "Get an HT... | 2 | stack_v2_sparse_classes_30k_train_001387 | Implement the Python class `RestResult` described below.
Class description:
Result from a REST API operation.
Method signatures and docstrings:
- def __init__(self, logfunc=None, response=None, err=None): Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param respo... | Implement the Python class `RestResult` described below.
Class description:
Result from a REST API operation.
Method signatures and docstrings:
- def __init__(self, logfunc=None, response=None, err=None): Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param respo... | a93a844398a11a8a85f204782fb9456f7caccdbe | <|skeleton|>
class RestResult:
"""Result from a REST API operation."""
def __init__(self, logfunc=None, response=None, err=None):
"""Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestResult:
"""Result from a REST API operation."""
def __init__(self, logfunc=None, response=None, err=None):
"""Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error."""
self.response =... | the_stack_v2_python_sparse | manila/share/drivers/zfssa/restclient.py | openstack/manila | train | 178 |
e6164e470ea8b3e7fb60a21db9dd465ee5738e07 | [
"miner = Miner(name='Miner', version='1.0.b', slug='slug_already_exists')\nminer.save()\nself.assertEqual('slug_already_exists')",
"miner = Miner(name='Miner', version='1.0.b')\nminer.save()\nself.assertNotEqual(miner.slug, '')",
"miner = Miner.objects.create(name='Miner', version='1.0.b')\nserver = Server.obje... | <|body_start_0|>
miner = Miner(name='Miner', version='1.0.b', slug='slug_already_exists')
miner.save()
self.assertEqual('slug_already_exists')
<|end_body_0|>
<|body_start_1|>
miner = Miner(name='Miner', version='1.0.b')
miner.save()
self.assertNotEqual(miner.slug, '')
<|... | Тестирование генерации slug при сохранении | PreSaveGetSlugTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreSaveGetSlugTest:
"""Тестирование генерации slug при сохранении"""
def slug_already_exists(self):
"""Тестирование slug уже задан"""
<|body_0|>
def test_known_model(self):
"""Тестирование slug не задан"""
<|body_1|>
def test_unknown_model(self):
... | stack_v2_sparse_classes_10k_train_008815 | 13,105 | permissive | [
{
"docstring": "Тестирование slug уже задан",
"name": "slug_already_exists",
"signature": "def slug_already_exists(self)"
},
{
"docstring": "Тестирование slug не задан",
"name": "test_known_model",
"signature": "def test_known_model(self)"
},
{
"docstring": "Тестирование параметр... | 3 | stack_v2_sparse_classes_30k_train_006353 | Implement the Python class `PreSaveGetSlugTest` described below.
Class description:
Тестирование генерации slug при сохранении
Method signatures and docstrings:
- def slug_already_exists(self): Тестирование slug уже задан
- def test_known_model(self): Тестирование slug не задан
- def test_unknown_model(self): Тестиро... | Implement the Python class `PreSaveGetSlugTest` described below.
Class description:
Тестирование генерации slug при сохранении
Method signatures and docstrings:
- def slug_already_exists(self): Тестирование slug уже задан
- def test_known_model(self): Тестирование slug не задан
- def test_unknown_model(self): Тестиро... | d173f1bee44d0752eefb53b1a0da847a3882a352 | <|skeleton|>
class PreSaveGetSlugTest:
"""Тестирование генерации slug при сохранении"""
def slug_already_exists(self):
"""Тестирование slug уже задан"""
<|body_0|>
def test_known_model(self):
"""Тестирование slug не задан"""
<|body_1|>
def test_unknown_model(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PreSaveGetSlugTest:
"""Тестирование генерации slug при сохранении"""
def slug_already_exists(self):
"""Тестирование slug уже задан"""
miner = Miner(name='Miner', version='1.0.b', slug='slug_already_exists')
miner.save()
self.assertEqual('slug_already_exists')
def test... | the_stack_v2_python_sparse | miningstatistic/core/tests.py | crowmurk/miners | train | 0 |
acf82c9c0e0dc7bfe950ad459fca57ad56f83f24 | [
"path = '/'.join([self.SCOPE_BASEURL, account, 'scopes', quote_plus(scope)])\nurl = build_url(choice(self.list_hosts), path=path)\nr = self._send_request(url, type_='POST')\nif r.status_code == codes.created:\n return True\nelse:\n exc_cls, exc_msg = self._get_exception(headers=r.headers, status_code=r.status... | <|body_start_0|>
path = '/'.join([self.SCOPE_BASEURL, account, 'scopes', quote_plus(scope)])
url = build_url(choice(self.list_hosts), path=path)
r = self._send_request(url, type_='POST')
if r.status_code == codes.created:
return True
else:
exc_cls, exc_msg... | Scope client class for working with rucio scopes | ScopeClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScopeClient:
"""Scope client class for working with rucio scopes"""
def add_scope(self, account, scope):
"""Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created s... | stack_v2_sparse_classes_10k_train_008816 | 3,206 | permissive | [
{
"docstring": "Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created successfully. :raises Duplicate: if scope already exists. :raises AccountNotFound: if account doesn't exist.",
"name"... | 3 | null | Implement the Python class `ScopeClient` described below.
Class description:
Scope client class for working with rucio scopes
Method signatures and docstrings:
- def add_scope(self, account, scope): Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the na... | Implement the Python class `ScopeClient` described below.
Class description:
Scope client class for working with rucio scopes
Method signatures and docstrings:
- def add_scope(self, account, scope): Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the na... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class ScopeClient:
"""Scope client class for working with rucio scopes"""
def add_scope(self, account, scope):
"""Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScopeClient:
"""Scope client class for working with rucio scopes"""
def add_scope(self, account, scope):
"""Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created successfully. ... | the_stack_v2_python_sparse | lib/rucio/client/scopeclient.py | rucio/rucio | train | 232 |
30a0c5ce18f88318ff84ad199c7a30c5d808f8ca | [
"vec = numpy.array([1, 2, 3, 4])\nmatvec_expected = numpy.array([2, 1, 4, 3])\nself.assertTrue(numpy.allclose(apply_operator((LinearQubitOperator(QubitOperator('X1')), vec)), matvec_expected))",
"qubit_operator = QubitOperator('Z3') + QubitOperator('X1') + QubitOperator('Y0')\nn_qubits = 6\noperator = generate_li... | <|body_start_0|>
vec = numpy.array([1, 2, 3, 4])
matvec_expected = numpy.array([2, 1, 4, 3])
self.assertTrue(numpy.allclose(apply_operator((LinearQubitOperator(QubitOperator('X1')), vec)), matvec_expected))
<|end_body_0|>
<|body_start_1|>
qubit_operator = QubitOperator('Z3') + QubitOper... | Tests for utility functions. | UtilityFunctionTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilityFunctionTest:
"""Tests for utility functions."""
def test_apply_operator(self):
"""Tests apply_operator() since it's executed on other processors."""
<|body_0|>
def test_generate_linear_operator(self):
"""Tests generate_linear_qubit_operator()."""
... | stack_v2_sparse_classes_10k_train_008817 | 11,830 | permissive | [
{
"docstring": "Tests apply_operator() since it's executed on other processors.",
"name": "test_apply_operator",
"signature": "def test_apply_operator(self)"
},
{
"docstring": "Tests generate_linear_qubit_operator().",
"name": "test_generate_linear_operator",
"signature": "def test_gener... | 2 | null | Implement the Python class `UtilityFunctionTest` described below.
Class description:
Tests for utility functions.
Method signatures and docstrings:
- def test_apply_operator(self): Tests apply_operator() since it's executed on other processors.
- def test_generate_linear_operator(self): Tests generate_linear_qubit_op... | Implement the Python class `UtilityFunctionTest` described below.
Class description:
Tests for utility functions.
Method signatures and docstrings:
- def test_apply_operator(self): Tests apply_operator() since it's executed on other processors.
- def test_generate_linear_operator(self): Tests generate_linear_qubit_op... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class UtilityFunctionTest:
"""Tests for utility functions."""
def test_apply_operator(self):
"""Tests apply_operator() since it's executed on other processors."""
<|body_0|>
def test_generate_linear_operator(self):
"""Tests generate_linear_qubit_operator()."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UtilityFunctionTest:
"""Tests for utility functions."""
def test_apply_operator(self):
"""Tests apply_operator() since it's executed on other processors."""
vec = numpy.array([1, 2, 3, 4])
matvec_expected = numpy.array([2, 1, 4, 3])
self.assertTrue(numpy.allclose(apply_ope... | the_stack_v2_python_sparse | src/openfermion/linalg/linear_qubit_operator_test.py | quantumlib/OpenFermion | train | 1,481 |
b55279ee802c714a05ee4efbddbe13cf4ebf2c6e | [
"self.count = []\nself.val = []\ntotal = 0\nfor i in range(0, len(encoding), 2):\n if encoding[i] == 0:\n continue\n total += encoding[i]\n self.count.append(total)\n self.val.append(encoding[i + 1])\nself.cur = 0",
"self.cur += n\ni = bisect.bisect_left(self.count, self.cur)\nif i == len(self.... | <|body_start_0|>
self.count = []
self.val = []
total = 0
for i in range(0, len(encoding), 2):
if encoding[i] == 0:
continue
total += encoding[i]
self.count.append(total)
self.val.append(encoding[i + 1])
self.cur = 0
... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, encoding):
""":type encoding: List[int] binary search 09/29/2022 15:19 Accepted 51 ms 14 MB python prefix sum + binary search medium"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_008818 | 3,450 | no_license | [
{
"docstring": ":type encoding: List[int] binary search 09/29/2022 15:19 Accepted 51 ms 14 MB python prefix sum + binary search medium",
"name": "__init__",
"signature": "def __init__(self, encoding)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(se... | 2 | stack_v2_sparse_classes_30k_train_000202 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, encoding): :type encoding: List[int] binary search 09/29/2022 15:19 Accepted 51 ms 14 MB python prefix sum + binary search medium
- def next(self, n): :t... | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, encoding): :type encoding: List[int] binary search 09/29/2022 15:19 Accepted 51 ms 14 MB python prefix sum + binary search medium
- def next(self, n): :t... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class RLEIterator:
def __init__(self, encoding):
""":type encoding: List[int] binary search 09/29/2022 15:19 Accepted 51 ms 14 MB python prefix sum + binary search medium"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, encoding):
""":type encoding: List[int] binary search 09/29/2022 15:19 Accepted 51 ms 14 MB python prefix sum + binary search medium"""
self.count = []
self.val = []
total = 0
for i in range(0, len(encoding), 2):
if encoding[i... | the_stack_v2_python_sparse | design/N900_RLEIterator.py | zerghua/leetcode-python | train | 2 | |
54b81d9d7cc5abec98fe953acd3708539b8998bd | [
"if not grid:\n return -1\nif grid and (not isinstance(grid[0], list)):\n return sum(grid)\nm, n = (len(grid), len(grid[0]))\ndp = [[float('inf')] * (n + 1) for _ in range(m + 1)]\ndp[0][1] = 0\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid... | <|body_start_0|>
if not grid:
return -1
if grid and (not isinstance(grid[0], list)):
return sum(grid)
m, n = (len(grid), len(grid[0]))
dp = [[float('inf')] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 0
for i in range(1, m + 1):
for j in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
"""dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
<|bod... | stack_v2_sparse_classes_10k_train_008819 | 1,721 | no_license | [
{
"docstring": "dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]",
"name": "minPathSum",
"signature": "def minPathSum(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def minPathSum(self, grid):
"""dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum(self, grid):
"""dp[i][j] 代表 (0,0)->(i-1_最短回文串.py.j-1_最短回文串.py) 最短路径 dp[i][j] = min(dp[i][j-1_最短回文串.py], dp[i-1_最短回文串.py][j]) + grid[i-1_最短回文串.py][j-1_最短回文串.py] dp[0][j] = inf dp[i][0] = inf dp[0][1_最短回文串.py] = 0 res = dp[-1_最短回文串.py][-1_最短回文串.py]"""
if not grid:
... | the_stack_v2_python_sparse | 4_LEETCODE/2_DP/网格问题/64_最小路径和.py | fzingithub/SwordRefers2Offer | train | 1 | |
f3ca166e20d59428e7720e06a768f0abe1cc432d | [
"index = 1\nwhile index < len(nums):\n if nums[index - 1] == nums[index]:\n del nums[index]\n else:\n index += 1\nreturn len(nums)",
"index = 0\nwhile index < len(nums):\n if nums[index] == val:\n del nums[index]\n else:\n index += 1\nreturn len(nums)"
] | <|body_start_0|>
index = 1
while index < len(nums):
if nums[index - 1] == nums[index]:
del nums[index]
else:
index += 1
return len(nums)
<|end_body_0|>
<|body_start_1|>
index = 0
while index < len(nums):
if nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
index = 1
... | stack_v2_sparse_classes_10k_train_008820 | 720 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElement",
"signature": "def removeElement(self, nums, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005315 | 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 removeElement(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 removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int
<|skeleton|>
class Sol... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
index = 1
while index < len(nums):
if nums[index - 1] == nums[index]:
del nums[index]
else:
index += 1
return len(nums)
def removeEle... | the_stack_v2_python_sparse | python_solution/021_030/RemoveDuplicates.py | CescWang1991/LeetCode-Python | train | 1 | |
6746db38c54c1a7d9e7b14895eed7294e7ed2562 | [
"cls.file_interfaces['.yaml'] = YamlInterface()\ncls.file_interfaces['.bin'] = PickleInterface()\nFileManager.initialized = True",
"if not filename:\n raise FileNotFoundError('No filename provided')\nif not FileManager.initialized:\n FileManager.init()\next = os.path.splitext(filename)[1]\nif not os.path.is... | <|body_start_0|>
cls.file_interfaces['.yaml'] = YamlInterface()
cls.file_interfaces['.bin'] = PickleInterface()
FileManager.initialized = True
<|end_body_0|>
<|body_start_1|>
if not filename:
raise FileNotFoundError('No filename provided')
if not FileManager.initiali... | Manages file interfaces. | FileManager | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileManager:
"""Manages file interfaces."""
def init(cls):
"""Initialise file interfaces."""
<|body_0|>
def locate_file(filename) -> str:
"""Find a file location. Args: ---- filename: Filename to locate Returns: Location of file"""
<|body_1|>
def get... | stack_v2_sparse_classes_10k_train_008821 | 3,664 | permissive | [
{
"docstring": "Initialise file interfaces.",
"name": "init",
"signature": "def init(cls)"
},
{
"docstring": "Find a file location. Args: ---- filename: Filename to locate Returns: Location of file",
"name": "locate_file",
"signature": "def locate_file(filename) -> str"
},
{
"doc... | 5 | null | Implement the Python class `FileManager` described below.
Class description:
Manages file interfaces.
Method signatures and docstrings:
- def init(cls): Initialise file interfaces.
- def locate_file(filename) -> str: Find a file location. Args: ---- filename: Filename to locate Returns: Location of file
- def get_fil... | Implement the Python class `FileManager` described below.
Class description:
Manages file interfaces.
Method signatures and docstrings:
- def init(cls): Initialise file interfaces.
- def locate_file(filename) -> str: Find a file location. Args: ---- filename: Filename to locate Returns: Location of file
- def get_fil... | 9f90c8b1586363b65340017bfa3af5d56d32c6d9 | <|skeleton|>
class FileManager:
"""Manages file interfaces."""
def init(cls):
"""Initialise file interfaces."""
<|body_0|>
def locate_file(filename) -> str:
"""Find a file location. Args: ---- filename: Filename to locate Returns: Location of file"""
<|body_1|>
def get... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileManager:
"""Manages file interfaces."""
def init(cls):
"""Initialise file interfaces."""
cls.file_interfaces['.yaml'] = YamlInterface()
cls.file_interfaces['.bin'] = PickleInterface()
FileManager.initialized = True
def locate_file(filename) -> str:
"""Find... | the_stack_v2_python_sparse | mpf/core/file_manager.py | missionpinball/mpf | train | 191 |
0a98861fa43c1a7bd2ebcadb706761d0b98bec02 | [
"self.res = []\ncol, left, right = (defaultdict(int), defaultdict(int), defaultdict(int))\nboard = [['.' for i in range(n)] for j in range(n)]\nself.dfs(n, board, -1, col, left, right)\nreturn self.res",
"if k == n - 1:\n self.res.append([''.join(board[i]) for i in range(n)])\n return\nfor c in range(n):\n ... | <|body_start_0|>
self.res = []
col, left, right = (defaultdict(int), defaultdict(int), defaultdict(int))
board = [['.' for i in range(n)] for j in range(n)]
self.dfs(n, board, -1, col, left, right)
return self.res
<|end_body_0|>
<|body_start_1|>
if k == n - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, n, board, k, col, left, right):
""":type board: List[str] :type k: int (k queens has been in the board) :type res: List[List[str]] :type col: dict[int] :rtype: bo... | stack_v2_sparse_classes_10k_train_008822 | 1,234 | no_license | [
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n)"
},
{
"docstring": ":type board: List[str] :type k: int (k queens has been in the board) :type res: List[List[str]] :type col: dict[int] :rtype: boolean",
"name": "dfs",
... | 2 | stack_v2_sparse_classes_30k_train_005798 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
- def dfs(self, n, board, k, col, left, right): :type board: List[str] :type k: int (k queens has been in the boar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
- def dfs(self, n, board, k, col, left, right): :type board: List[str] :type k: int (k queens has been in the boar... | 2f46f85e1e297b0a50fdb66956b1d05622a4063d | <|skeleton|>
class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, n, board, k, col, left, right):
""":type board: List[str] :type k: int (k queens has been in the board) :type res: List[List[str]] :type col: dict[int] :rtype: bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
self.res = []
col, left, right = (defaultdict(int), defaultdict(int), defaultdict(int))
board = [['.' for i in range(n)] for j in range(n)]
self.dfs(n, board, -1, col, left, right)
r... | the_stack_v2_python_sparse | dan/Problems/Hard/Backtracking/51. N-Queens/solution.py | xudaaaaan/Leetcode | train | 0 | |
dc6bd3a04cd09990d622b8b0c07fda1f951001c0 | [
"assert issubclass(work_session_model, WorkSession), 'You should define working session model properly'\nself._logger = logging.getLogger('vulyk.app')\nself.work_session = work_session_model",
"try:\n existing = self.work_session.objects(user=user_id, task=task, task_type=task.task_type).modify(upsert=True, se... | <|body_start_0|>
assert issubclass(work_session_model, WorkSession), 'You should define working session model properly'
self._logger = logging.getLogger('vulyk.app')
self.work_session = work_session_model
<|end_body_0|>
<|body_start_1|>
try:
existing = self.work_session.obje... | This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the timestamp of the event. Thus we're able to perform... | WorkSessionManager | [
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkSessionManager:
"""This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the time... | stack_v2_sparse_classes_10k_train_008823 | 6,649 | permissive | [
{
"docstring": "Constructor. :param work_session_model: Underlying mongoDB Document subclass. :type work_session_model: Type",
"name": "__init__",
"signature": "def __init__(self, work_session_model: Type[U]) -> None"
},
{
"docstring": "Starts new WorkSession for given user. By default we use `d... | 5 | stack_v2_sparse_classes_30k_train_001468 | Implement the Python class `WorkSessionManager` described below.
Class description:
This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we ... | Implement the Python class `WorkSessionManager` described below.
Class description:
This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we ... | dd89a1fdacc322a43090169aae9e36f03f1b55c2 | <|skeleton|>
class WorkSessionManager:
"""This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the time... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WorkSessionManager:
"""This class is responsible for accounting of work-sessions. Every time we give a task to user, a new session record is being created. If user skips the task, we mark it as skipped and delete the session. When user finishes the task, we close the session having added the timestamp of the ... | the_stack_v2_python_sparse | vulyk/ext/worksession.py | mrgambal/vulyk | train | 34 |
22cb82d2c92422aa89a0821898d63b60edc58920 | [
"possibles = [set() for i in range(n)]\nfor i in range(n):\n a = i + 1\n for j in range(n):\n b = j + 1\n if a % b == 0 or b % a == 0:\n possibles[i].add(b)\npossibles.sort(key=lambda s: len(s))\n\ndef try_remove_from(possible: int, start: int):\n indexes = []\n for i in range(s... | <|body_start_0|>
possibles = [set() for i in range(n)]
for i in range(n):
a = i + 1
for j in range(n):
b = j + 1
if a % b == 0 or b % a == 0:
possibles[i].add(b)
possibles.sort(key=lambda s: len(s))
def try_remo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countArrangement_1(self, n: int) -> int:
"""This looks like a back-tracking with pruning problem: - we have to try all combinations - we can abort prematuraly some prefix of solutions How de we know when to abort? - we just list the numbers that are valid at each position: ... | stack_v2_sparse_classes_10k_train_008824 | 3,168 | no_license | [
{
"docstring": "This looks like a back-tracking with pruning problem: - we have to try all combinations - we can abort prematuraly some prefix of solutions How de we know when to abort? - we just list the numbers that are valid at each position: initial phase in O(N ** 2) - we start with the indices with the le... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countArrangement_1(self, n: int) -> int: This looks like a back-tracking with pruning problem: - we have to try all combinations - we can abort prematuraly some prefix of sol... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countArrangement_1(self, n: int) -> int: This looks like a back-tracking with pruning problem: - we have to try all combinations - we can abort prematuraly some prefix of sol... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def countArrangement_1(self, n: int) -> int:
"""This looks like a back-tracking with pruning problem: - we have to try all combinations - we can abort prematuraly some prefix of solutions How de we know when to abort? - we just list the numbers that are valid at each position: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countArrangement_1(self, n: int) -> int:
"""This looks like a back-tracking with pruning problem: - we have to try all combinations - we can abort prematuraly some prefix of solutions How de we know when to abort? - we just list the numbers that are valid at each position: initial phase ... | the_stack_v2_python_sparse | backtrack/BeautifulArrangements.py | QuentinDuval/PythonExperiments | train | 3 | |
db1d4a3da7a83ce12d74b4aaf8db23295dfee816 | [
"super(Attention, self).__init__()\nassert kernel_size % 2 == 1, \"Kernel size should be odd for 'same' conv.\"\npadding = (kernel_size - 1) // 2\nself.conv = nn.Conv1d(1, 1, kernel_size, padding=padding)\nself.log_t = log_t",
"pax = eh * dhx\npax = torch.sum(pax, dim=2)\nif ax is not None:\n ax = ax.unsqueeze... | <|body_start_0|>
super(Attention, self).__init__()
assert kernel_size % 2 == 1, "Kernel size should be odd for 'same' conv."
padding = (kernel_size - 1) // 2
self.conv = nn.Conv1d(1, 1, kernel_size, padding=padding)
self.log_t = log_t
<|end_body_0|>
<|body_start_1|>
pax ... | Attention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
def __init__(self, kernel_size=11, log_t=False):
"""Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hid... | stack_v2_sparse_classes_10k_train_008825 | 19,030 | no_license | [
{
"docstring": "Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hidden state with each time-step of the encoder state. The 'location' base... | 2 | stack_v2_sparse_classes_30k_train_001692 | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, kernel_size=11, log_t=False): Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' an... | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, kernel_size=11, log_t=False): Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' an... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Attention:
def __init__(self, kernel_size=11, log_t=False):
"""Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hid... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Attention:
def __init__(self, kernel_size=11, log_t=False):
"""Module which Performs a single attention step along the second axis of a given encoded input. The module uses both 'content' and 'location' based attention. The 'content' based attention is an inner product of the decoder hidden state with... | the_stack_v2_python_sparse | generated/test_awni_speech.py | jansel/pytorch-jit-paritybench | train | 35 | |
7abd5325ab616249898840bc6e1f053de09a5e7f | [
"if six.PY2:\n values = [tensor_shape.Dimension(x) for x in (3, 7, 11, None)]\n for x in values:\n for y in values:\n self.assertEqual((x / y).value, (x // y).value)",
"if six.PY2:\n two = tensor_shape.Dimension(2)\n message = \"unsupported operand type\\\\(s\\\\) for /: 'int' and 'D... | <|body_start_0|>
if six.PY2:
values = [tensor_shape.Dimension(x) for x in (3, 7, 11, None)]
for x in values:
for y in values:
self.assertEqual((x / y).value, (x // y).value)
<|end_body_0|>
<|body_start_1|>
if six.PY2:
two = tensor_... | DimensionDivTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DimensionDivTest:
def testDivSucceeds(self):
"""Without from __future__ import division, __div__ should work."""
<|body_0|>
def testRDivFail(self):
"""Without from __future__ import division, __rdiv__ is used."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_008826 | 1,941 | permissive | [
{
"docstring": "Without from __future__ import division, __div__ should work.",
"name": "testDivSucceeds",
"signature": "def testDivSucceeds(self)"
},
{
"docstring": "Without from __future__ import division, __rdiv__ is used.",
"name": "testRDivFail",
"signature": "def testRDivFail(self)... | 2 | stack_v2_sparse_classes_30k_train_006685 | Implement the Python class `DimensionDivTest` described below.
Class description:
Implement the DimensionDivTest class.
Method signatures and docstrings:
- def testDivSucceeds(self): Without from __future__ import division, __div__ should work.
- def testRDivFail(self): Without from __future__ import division, __rdiv... | Implement the Python class `DimensionDivTest` described below.
Class description:
Implement the DimensionDivTest class.
Method signatures and docstrings:
- def testDivSucceeds(self): Without from __future__ import division, __div__ should work.
- def testRDivFail(self): Without from __future__ import division, __rdiv... | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | <|skeleton|>
class DimensionDivTest:
def testDivSucceeds(self):
"""Without from __future__ import division, __div__ should work."""
<|body_0|>
def testRDivFail(self):
"""Without from __future__ import division, __rdiv__ is used."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DimensionDivTest:
def testDivSucceeds(self):
"""Without from __future__ import division, __div__ should work."""
if six.PY2:
values = [tensor_shape.Dimension(x) for x in (3, 7, 11, None)]
for x in values:
for y in values:
self.assertE... | the_stack_v2_python_sparse | tensorflow/python/framework/tensor_shape_div_test.py | NVIDIA/tensorflow | train | 763 | |
088ac256a3cf15785085c494bc69912280c63774 | [
"client = mock_client(mocker)\nargs = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com'}}\nmocker.patch.object(client, 'get_user', return_value=USER_APP_DATA)\nmocker.patch.object(IAMUserProfile, 'update_with_app_data', return_value={})\nuser_profile = IAMCommand().get_user(client, args)\noutputs = get... | <|body_start_0|>
client = mock_client(mocker)
args = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com'}}
mocker.patch.object(client, 'get_user', return_value=USER_APP_DATA)
mocker.patch.object(IAMUserProfile, 'update_with_app_data', return_value={})
user_profile = IA... | Class to group the get user commands test | TestGetUserCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetUserCommand:
"""Class to group the get user commands test"""
def test_get_user_command__existing_user(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a user When: - The user exists in the application - Calling function get_us... | stack_v2_sparse_classes_10k_train_008827 | 13,964 | permissive | [
{
"docstring": "Given: - An app client object - A user-profile argument that contains an email of a user When: - The user exists in the application - Calling function get_user_command Then: - Ensure the resulted User Profile object holds the correct user details",
"name": "test_get_user_command__existing_us... | 3 | null | Implement the Python class `TestGetUserCommand` described below.
Class description:
Class to group the get user commands test
Method signatures and docstrings:
- def test_get_user_command__existing_user(self, mocker): Given: - An app client object - A user-profile argument that contains an email of a user When: - The... | Implement the Python class `TestGetUserCommand` described below.
Class description:
Class to group the get user commands test
Method signatures and docstrings:
- def test_get_user_command__existing_user(self, mocker): Given: - An app client object - A user-profile argument that contains an email of a user When: - The... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestGetUserCommand:
"""Class to group the get user commands test"""
def test_get_user_command__existing_user(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a user When: - The user exists in the application - Calling function get_us... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestGetUserCommand:
"""Class to group the get user commands test"""
def test_get_user_command__existing_user(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a user When: - The user exists in the application - Calling function get_user_command Th... | the_stack_v2_python_sparse | Packs/PrismaCloud/Integrations/PrismaCloudIAM/PrismaCloudIAM_test.py | demisto/content | train | 1,023 |
6835d2e1c68cb97d0d6132c3be1697ea8d8bfaa0 | [
"super(ec3poDriver, self).__init__(interface, params)\nself._logger = logging.getLogger('EC3PO Driver')\nself._interface = interface",
"if self._interface is not None:\n self._interface.set_interp_connect(state)\nelse:\n self._logger.debug('There is no UART on this servo for this specific interface.')",
"... | <|body_start_0|>
super(ec3poDriver, self).__init__(interface, params)
self._logger = logging.getLogger('EC3PO Driver')
self._interface = interface
<|end_body_0|>
<|body_start_1|>
if self._interface is not None:
self._interface.set_interp_connect(state)
else:
... | ec3poDriver | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ec3poDriver:
def __init__(self, interface, params):
"""Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init."""
<|body_0|>
def _Set_in... | stack_v2_sparse_classes_10k_train_008828 | 1,960 | permissive | [
{
"docstring": "Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init.",
"name": "__init__",
"signature": "def __init__(self, interface, params)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_007353 | Implement the Python class `ec3poDriver` described below.
Class description:
Implement the ec3poDriver class.
Method signatures and docstrings:
- def __init__(self, interface, params): Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpret... | Implement the Python class `ec3poDriver` described below.
Class description:
Implement the ec3poDriver class.
Method signatures and docstrings:
- def __init__(self, interface, params): Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpret... | c7d50190837497dafc45f6efe18bf01d6e70cfd2 | <|skeleton|>
class ec3poDriver:
def __init__(self, interface, params):
"""Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init."""
<|body_0|>
def _Set_in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ec3poDriver:
def __init__(self, interface, params):
"""Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init."""
super(ec3poDriver, self).__init__(interfa... | the_stack_v2_python_sparse | servo/drv/ec3po_driver.py | mmind/servo-hdctools | train | 2 | |
09727c782e8e6e5b52276a858467272d879e8370 | [
"A = [(a - b, a, b) for a, b in costs]\nA.sort()\nret = 0\nremain = len(A) // 2\nfor _, a, b in A:\n if remain > 0:\n ret += a\n remain -= 1\n else:\n ret += b\nreturn ret",
"A = [(abs(a - b), a, b) for a, b in costs]\nA.sort(reverse=True)\nret = 0\nremain = len(A) // 2\nfor _, a, b in ... | <|body_start_0|>
A = [(a - b, a, b) for a, b in costs]
A.sort()
ret = 0
remain = len(A) // 2
for _, a, b in A:
if remain > 0:
ret += a
remain -= 1
else:
ret += b
return ret
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""sort by city A and 004_greedy? [30, 20]? sort by total? sort by diff - either choose A or B, the difference matters a - b: incremental cost of flying A instead of B"""
<|body_0|>
def twoCitySchedCost_err... | stack_v2_sparse_classes_10k_train_008829 | 2,011 | no_license | [
{
"docstring": "sort by city A and 004_greedy? [30, 20]? sort by total? sort by diff - either choose A or B, the difference matters a - b: incremental cost of flying A instead of B",
"name": "twoCitySchedCost",
"signature": "def twoCitySchedCost(self, costs: List[List[int]]) -> int"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_007061 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoCitySchedCost(self, costs: List[List[int]]) -> int: sort by city A and 004_greedy? [30, 20]? sort by total? sort by diff - either choose A or B, the difference matters a -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoCitySchedCost(self, costs: List[List[int]]) -> int: sort by city A and 004_greedy? [30, 20]? sort by total? sort by diff - either choose A or B, the difference matters a -... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""sort by city A and 004_greedy? [30, 20]? sort by total? sort by diff - either choose A or B, the difference matters a - b: incremental cost of flying A instead of B"""
<|body_0|>
def twoCitySchedCost_err... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""sort by city A and 004_greedy? [30, 20]? sort by total? sort by diff - either choose A or B, the difference matters a - b: incremental cost of flying A instead of B"""
A = [(a - b, a, b) for a, b in costs]
A.sort()... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/1029 Two City Scheduling.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
d6afcc23d03e1975bdc65ebe37b80153f54ddd14 | [
"res = super(stock_move, self)._create_chained_picking(cr, uid, pick_name, picking, purchase_type, move, context=context)\nif picking.purchase_id:\n self.pool.get('stock.picking').write(cr, uid, [res], {'purchase_id': picking.purchase_id.id})\n self.pool.get('stock.picking').write(cr, uid, [res], {'invoice_st... | <|body_start_0|>
res = super(stock_move, self)._create_chained_picking(cr, uid, pick_name, picking, purchase_type, move, context=context)
if picking.purchase_id:
self.pool.get('stock.picking').write(cr, uid, [res], {'purchase_id': picking.purchase_id.id})
self.pool.get('stock.pic... | TO remove pricelist | stock_move | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_move:
"""TO remove pricelist"""
def _create_chained_picking(self, cr, uid, pick_name, picking, purchase_type, move, context=None):
"""This method creates chained picking and fix the problem of adding accounts for picking. @param pick_name: The name from the picking which is cre... | stack_v2_sparse_classes_10k_train_008830 | 5,611 | no_license | [
{
"docstring": "This method creates chained picking and fix the problem of adding accounts for picking. @param pick_name: The name from the picking which is created @param picking: The id of the picking which is created @param purchase_type: Purchase type @param move: The move id @return: id of creating picking... | 2 | stack_v2_sparse_classes_30k_train_003070 | Implement the Python class `stock_move` described below.
Class description:
TO remove pricelist
Method signatures and docstrings:
- def _create_chained_picking(self, cr, uid, pick_name, picking, purchase_type, move, context=None): This method creates chained picking and fix the problem of adding accounts for picking.... | Implement the Python class `stock_move` described below.
Class description:
TO remove pricelist
Method signatures and docstrings:
- def _create_chained_picking(self, cr, uid, pick_name, picking, purchase_type, move, context=None): This method creates chained picking and fix the problem of adding accounts for picking.... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_move:
"""TO remove pricelist"""
def _create_chained_picking(self, cr, uid, pick_name, picking, purchase_type, move, context=None):
"""This method creates chained picking and fix the problem of adding accounts for picking. @param pick_name: The name from the picking which is cre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class stock_move:
"""TO remove pricelist"""
def _create_chained_picking(self, cr, uid, pick_name, picking, purchase_type, move, context=None):
"""This method creates chained picking and fix the problem of adding accounts for picking. @param pick_name: The name from the picking which is created @param p... | the_stack_v2_python_sparse | v_7/GDS/shamil_v3/purchase_no_pricelist/stock.py | musabahmed/baba | train | 0 |
595542f64e8dbcdc6f9d8cf293b84c27dda263de | [
"user = request.user\nredis_conn = get_redis_connection('history')\nsku_ids = redis_conn.zrevrange('history_%s' % user.id, 0, 4)\nskus = []\nfor sku_id in sku_ids:\n sku = SKU.objects.get(id=sku_id)\n skus.append({'id': sku.id, 'name': sku.name, 'price': sku.price, 'default_image_url': sku.default_image.url})... | <|body_start_0|>
user = request.user
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.zrevrange('history_%s' % user.id, 0, 4)
skus = []
for sku_id in sku_ids:
sku = SKU.objects.get(id=sku_id)
skus.append({'id': sku.id, 'name': sku.name, 'p... | 用户浏览记录 | UserBrowseHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBrowseHistory:
"""用户浏览记录"""
def get(self, request):
"""查询用户浏览记录"""
<|body_0|>
def post(self, request):
"""保存用户浏览记录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = request.user
redis_conn = get_redis_connection('history')
... | stack_v2_sparse_classes_10k_train_008831 | 22,758 | permissive | [
{
"docstring": "查询用户浏览记录",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "保存用户浏览记录",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001430 | Implement the Python class `UserBrowseHistory` described below.
Class description:
用户浏览记录
Method signatures and docstrings:
- def get(self, request): 查询用户浏览记录
- def post(self, request): 保存用户浏览记录 | Implement the Python class `UserBrowseHistory` described below.
Class description:
用户浏览记录
Method signatures and docstrings:
- def get(self, request): 查询用户浏览记录
- def post(self, request): 保存用户浏览记录
<|skeleton|>
class UserBrowseHistory:
"""用户浏览记录"""
def get(self, request):
"""查询用户浏览记录"""
<|body_... | 2434231795b3319dfda60b19af18442ee5f6fa73 | <|skeleton|>
class UserBrowseHistory:
"""用户浏览记录"""
def get(self, request):
"""查询用户浏览记录"""
<|body_0|>
def post(self, request):
"""保存用户浏览记录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserBrowseHistory:
"""用户浏览记录"""
def get(self, request):
"""查询用户浏览记录"""
user = request.user
redis_conn = get_redis_connection('history')
sku_ids = redis_conn.zrevrange('history_%s' % user.id, 0, 4)
skus = []
for sku_id in sku_ids:
sku = SKU.objec... | the_stack_v2_python_sparse | meiduo_project/meiduo_mall/meiduo_mall/apps/users/views.py | xlztongxue/meiduoshangcheng | train | 0 |
5b504a632dcca32b1e6a9ba504ed1454c62e56e4 | [
"obj1 = objectify.fromstring(expected)\nexpected = etree.tostring(obj1)\nobj2 = objectify.fromstring(actual)\nactual = etree.tostring(obj2)\nunittest.TestCase().assertEqual(expected, actual)",
"expected = expected.encode('utf-8')\nactual = actual.encode('utf-8')\nparser = etree.XMLParser(encoding='utf-8')\nobj1 =... | <|body_start_0|>
obj1 = objectify.fromstring(expected)
expected = etree.tostring(obj1)
obj2 = objectify.fromstring(actual)
actual = etree.tostring(obj2)
unittest.TestCase().assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
expected = expected.encode('utf-8')
... | XmlUtilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlUtilities:
def assert_xml_equal(expected, actual):
"""Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:"""
<|body_0|>
def assert_xml_equal_utf_8(expected, actual):
"""This method ensures the two strings... | stack_v2_sparse_classes_10k_train_008832 | 1,227 | permissive | [
{
"docstring": "Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:",
"name": "assert_xml_equal",
"signature": "def assert_xml_equal(expected, actual)"
},
{
"docstring": "This method ensures the two strings are both in utf encoding for ... | 2 | null | Implement the Python class `XmlUtilities` described below.
Class description:
Implement the XmlUtilities class.
Method signatures and docstrings:
- def assert_xml_equal(expected, actual): Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:
- def assert_xml_e... | Implement the Python class `XmlUtilities` described below.
Class description:
Implement the XmlUtilities class.
Method signatures and docstrings:
- def assert_xml_equal(expected, actual): Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:
- def assert_xml_e... | 8420d9d4b800223bff6a648015679684f5aba38c | <|skeleton|>
class XmlUtilities:
def assert_xml_equal(expected, actual):
"""Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:"""
<|body_0|>
def assert_xml_equal_utf_8(expected, actual):
"""This method ensures the two strings... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XmlUtilities:
def assert_xml_equal(expected, actual):
"""Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:"""
obj1 = objectify.fromstring(expected)
expected = etree.tostring(obj1)
obj2 = objectify.fromstring(actual)
... | the_stack_v2_python_sparse | common/utilities/xml_utilities.py | nhsconnect/integration-adaptors | train | 15 | |
97ba2c8dbb90199871ebead20570ddb79ccca4d5 | [
"args = movie_list_parser.parse_args()\nname = args.get('name')\nmovie_lists = [movie_list.to_dict() for movie_list in db.get_movie_lists(name=name, session=session)]\nreturn jsonify(movie_lists)",
"data = request.json\nname = data.get('name')\ntry:\n movie_list = db.get_list_by_exact_name(name=name, session=s... | <|body_start_0|>
args = movie_list_parser.parse_args()
name = args.get('name')
movie_lists = [movie_list.to_dict() for movie_list in db.get_movie_lists(name=name, session=session)]
return jsonify(movie_lists)
<|end_body_0|>
<|body_start_1|>
data = request.json
name = dat... | MovieListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieListAPI:
def get(self, session=None):
"""Gets movies lists"""
<|body_0|>
def post(self, session=None):
"""Create a new list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = movie_list_parser.parse_args()
name = args.get('name')
... | stack_v2_sparse_classes_10k_train_008833 | 12,846 | permissive | [
{
"docstring": "Gets movies lists",
"name": "get",
"signature": "def get(self, session=None)"
},
{
"docstring": "Create a new list",
"name": "post",
"signature": "def post(self, session=None)"
}
] | 2 | null | Implement the Python class `MovieListAPI` described below.
Class description:
Implement the MovieListAPI class.
Method signatures and docstrings:
- def get(self, session=None): Gets movies lists
- def post(self, session=None): Create a new list | Implement the Python class `MovieListAPI` described below.
Class description:
Implement the MovieListAPI class.
Method signatures and docstrings:
- def get(self, session=None): Gets movies lists
- def post(self, session=None): Create a new list
<|skeleton|>
class MovieListAPI:
def get(self, session=None):
... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class MovieListAPI:
def get(self, session=None):
"""Gets movies lists"""
<|body_0|>
def post(self, session=None):
"""Create a new list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovieListAPI:
def get(self, session=None):
"""Gets movies lists"""
args = movie_list_parser.parse_args()
name = args.get('name')
movie_lists = [movie_list.to_dict() for movie_list in db.get_movie_lists(name=name, session=session)]
return jsonify(movie_lists)
def po... | the_stack_v2_python_sparse | flexget/components/managed_lists/lists/movie_list/api.py | BrutuZ/Flexget | train | 1 | |
a8d80efe8948e933046749e6576d037c80d2ac66 | [
"row_num = len(array)\ncol_num = len(array[0])\ni = row_num - 1\nj = 0\nwhile i >= 0 and j <= col_num - 1:\n if target < array[i][j]:\n i -= 1\n elif target > array[i][j]:\n j += 1\n else:\n return True\nreturn False",
"row_num = len(array)\ncol_num = len(array[0])\ni = 0\nj = col_nu... | <|body_start_0|>
row_num = len(array)
col_num = len(array[0])
i = row_num - 1
j = 0
while i >= 0 and j <= col_num - 1:
if target < array[i][j]:
i -= 1
elif target > array[i][j]:
j += 1
else:
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Find(self, target, array):
"""从左下角开始遍历"""
<|body_0|>
def Find1(self, target, array):
"""从右下角开始遍历"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
row_num = len(array)
col_num = len(array[0])
i = row_num - 1
j = 0... | stack_v2_sparse_classes_10k_train_008834 | 1,202 | no_license | [
{
"docstring": "从左下角开始遍历",
"name": "Find",
"signature": "def Find(self, target, array)"
},
{
"docstring": "从右下角开始遍历",
"name": "Find1",
"signature": "def Find1(self, target, array)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004419 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Find(self, target, array): 从左下角开始遍历
- def Find1(self, target, array): 从右下角开始遍历 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Find(self, target, array): 从左下角开始遍历
- def Find1(self, target, array): 从右下角开始遍历
<|skeleton|>
class Solution:
def Find(self, target, array):
"""从左下角开始遍历"""
... | 72543bf087b4dc691bb01880ed42fbc782a43f20 | <|skeleton|>
class Solution:
def Find(self, target, array):
"""从左下角开始遍历"""
<|body_0|>
def Find1(self, target, array):
"""从右下角开始遍历"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def Find(self, target, array):
"""从左下角开始遍历"""
row_num = len(array)
col_num = len(array[0])
i = row_num - 1
j = 0
while i >= 0 and j <= col_num - 1:
if target < array[i][j]:
i -= 1
elif target > array[i][j]:
... | the_stack_v2_python_sparse | 剑指offer/01-二维数组中的查找.py | kingsvalley/mannuan.github.io | train | 0 | |
10be25aec3f14644d4c49c13def2dceb57614779 | [
"@jwt.requires_auth\n@wraps(f)\ndef decorated(*args, **kwargs):\n token_info = g.jwt_oidc_token_info\n user = User.find_by_oauth_id(token_info.get('sub'))\n if user:\n g.user = user\n return f(*args, **kwargs)\n raise BusinessException('Access Denied', HTTPStatus.UNAUTHORIZED)\nreturn deco... | <|body_start_0|>
@jwt.requires_auth
@wraps(f)
def decorated(*args, **kwargs):
token_info = g.jwt_oidc_token_info
user = User.find_by_oauth_id(token_info.get('sub'))
if user:
g.user = user
return f(*args, **kwargs)
ra... | Extending JwtManager to include additional functionalities. | Auth | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auth:
"""Extending JwtManager to include additional functionalities."""
def require(cls, f):
"""Validate the Bearer Token and User in database."""
<|body_0|>
def has_one_of_roles(cls, roles):
"""Check that at least one of the realm roles are in the token by exten... | stack_v2_sparse_classes_10k_train_008835 | 3,895 | permissive | [
{
"docstring": "Validate the Bearer Token and User in database.",
"name": "require",
"signature": "def require(cls, f)"
},
{
"docstring": "Check that at least one of the realm roles are in the token by extending Auth.require. Args: roles [str,]: Comma separated list of valid roles",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_005896 | Implement the Python class `Auth` described below.
Class description:
Extending JwtManager to include additional functionalities.
Method signatures and docstrings:
- def require(cls, f): Validate the Bearer Token and User in database.
- def has_one_of_roles(cls, roles): Check that at least one of the realm roles are ... | Implement the Python class `Auth` described below.
Class description:
Extending JwtManager to include additional functionalities.
Method signatures and docstrings:
- def require(cls, f): Validate the Bearer Token and User in database.
- def has_one_of_roles(cls, roles): Check that at least one of the realm roles are ... | 3bfe09c100a0f5b98d61228324336d5f45ad93ad | <|skeleton|>
class Auth:
"""Extending JwtManager to include additional functionalities."""
def require(cls, f):
"""Validate the Bearer Token and User in database."""
<|body_0|>
def has_one_of_roles(cls, roles):
"""Check that at least one of the realm roles are in the token by exten... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Auth:
"""Extending JwtManager to include additional functionalities."""
def require(cls, f):
"""Validate the Bearer Token and User in database."""
@jwt.requires_auth
@wraps(f)
def decorated(*args, **kwargs):
token_info = g.jwt_oidc_token_info
user =... | the_stack_v2_python_sparse | selfservice-api/src/selfservice_api/utils/auth.py | bcgov/BCSC-SS | train | 2 |
c3c909f95f9855a9235c07a90ccc358272b38ca5 | [
"check_type(session, RestSession)\nsuper(EventsAPI, self).__init__()\nself._session = session\nself._object_factory = object_factory",
"check_type(resource, basestring, optional=True)\ncheck_type(type, basestring, optional=True)\ncheck_type(actorId, basestring, optional=True)\ncheck_type(_from, basestring, option... | <|body_start_0|>
check_type(session, RestSession)
super(EventsAPI, self).__init__()
self._session = session
self._object_factory = object_factory
<|end_body_0|>
<|body_start_1|>
check_type(resource, basestring, optional=True)
check_type(type, basestring, optional=True)
... | Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects. | EventsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventsAPI:
"""Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Initialize a new EventsAPI object with the provided RestSession. Args: session(Res... | stack_v2_sparse_classes_10k_train_008836 | 6,123 | permissive | [
{
"docstring": "Initialize a new EventsAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Webex Teams service. Raises: TypeError: If the parameter types are incorrect.",
"name": "__init__",
"signature": "def __init__(self, ses... | 3 | stack_v2_sparse_classes_30k_train_007286 | Implement the Python class `EventsAPI` described below.
Class description:
Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Initialize a new EventsAP... | Implement the Python class `EventsAPI` described below.
Class description:
Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Initialize a new EventsAP... | d031aab82e3fa5ce7cf57b257fef8c9a4c63d71e | <|skeleton|>
class EventsAPI:
"""Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Initialize a new EventsAPI object with the provided RestSession. Args: session(Res... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventsAPI:
"""Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Initialize a new EventsAPI object with the provided RestSession. Args: session(RestSession): Th... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/webexteamssdk/api/events.py | CiscoDevNet/meraki-code | train | 67 |
31b553c5b2974bcc10b05798119d3f925969d73f | [
"PowerSpectrumSeries.__init__(self, *args, **kwargs)\nself.__cache = cache.Cache(maxsize=1000)\nif self.overlay.ndim < 4:\n raise ValueError('Overlay is not a 4D image')",
"display = self.displayCtx.getDisplay(self.overlay)\nopts = display.opts\ncoords = opts.getVoxel()\nif coords is not None:\n return '{} ... | <|body_start_0|>
PowerSpectrumSeries.__init__(self, *args, **kwargs)
self.__cache = cache.Cache(maxsize=1000)
if self.overlay.ndim < 4:
raise ValueError('Overlay is not a 4D image')
<|end_body_0|>
<|body_start_1|>
display = self.displayCtx.getDisplay(self.overlay)
op... | The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property. | VoxelPowerSpectrumSeries | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxelPowerSpectrumSeries:
"""The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property."""
def __init__(self, *args, **kwargs):
"""Create a ``Voxel... | stack_v2_sparse_classes_10k_train_008837 | 8,639 | permissive | [
{
"docstring": "Create a ``VoxelPowerSpectrumSeries``. All arguments are passed to the :meth:`PowerSpectrumSeries.__init__` method. A :exc:`ValueError` is raised if the overlay is not a 4D :class:`.Image`.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring":... | 3 | null | Implement the Python class `VoxelPowerSpectrumSeries` described below.
Class description:
The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.
Method signatures and docstrings... | Implement the Python class `VoxelPowerSpectrumSeries` described below.
Class description:
The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.
Method signatures and docstrings... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class VoxelPowerSpectrumSeries:
"""The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property."""
def __init__(self, *args, **kwargs):
"""Create a ``Voxel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VoxelPowerSpectrumSeries:
"""The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property."""
def __init__(self, *args, **kwargs):
"""Create a ``VoxelPowerSpectrum... | the_stack_v2_python_sparse | fsleyes/plotting/powerspectrumseries.py | sanjayankur31/fsleyes | train | 1 |
aa16b7e6294ddc5eb49e28124e364895d0f9ca1c | [
"keyword = self.request.query_params.get('keyword', '')\nqueryset = self.queryset.filter(title__icontains=keyword)\nif isinstance(queryset, QuerySet):\n queryset = queryset.all()\nreturn queryset.order_by('-first_published_at')",
"queryset = self.filter_queryset(self.get_queryset())\npage = request.query_param... | <|body_start_0|>
keyword = self.request.query_params.get('keyword', '')
queryset = self.queryset.filter(title__icontains=keyword)
if isinstance(queryset, QuerySet):
queryset = queryset.all()
return queryset.order_by('-first_published_at')
<|end_body_0|>
<|body_start_1|>
... | Lists all of the items. Can get this in Wagtail API, but that is read-only. Add a get_queryset method to create parameters for the URL to filter the list of items. @todo: is this needed? Do we need write capabilities? If not, just use Wagtail's api to list the items. | ItemListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemListView:
"""Lists all of the items. Can get this in Wagtail API, but that is read-only. Add a get_queryset method to create parameters for the URL to filter the list of items. @todo: is this needed? Do we need write capabilities? If not, just use Wagtail's api to list the items."""
def ... | stack_v2_sparse_classes_10k_train_008838 | 18,619 | no_license | [
{
"docstring": "Adds search functionality for the home page items.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Modification of original list method. Added different pagination method.",
"name": "list",
"signature": "def list(self, request, *args, **... | 2 | stack_v2_sparse_classes_30k_train_000085 | Implement the Python class `ItemListView` described below.
Class description:
Lists all of the items. Can get this in Wagtail API, but that is read-only. Add a get_queryset method to create parameters for the URL to filter the list of items. @todo: is this needed? Do we need write capabilities? If not, just use Wagtai... | Implement the Python class `ItemListView` described below.
Class description:
Lists all of the items. Can get this in Wagtail API, but that is read-only. Add a get_queryset method to create parameters for the URL to filter the list of items. @todo: is this needed? Do we need write capabilities? If not, just use Wagtai... | 317b6359a666e9b8ea2247ae5c63e5062e75aac4 | <|skeleton|>
class ItemListView:
"""Lists all of the items. Can get this in Wagtail API, but that is read-only. Add a get_queryset method to create parameters for the URL to filter the list of items. @todo: is this needed? Do we need write capabilities? If not, just use Wagtail's api to list the items."""
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ItemListView:
"""Lists all of the items. Can get this in Wagtail API, but that is read-only. Add a get_queryset method to create parameters for the URL to filter the list of items. @todo: is this needed? Do we need write capabilities? If not, just use Wagtail's api to list the items."""
def get_queryset(... | the_stack_v2_python_sparse | api/views.py | Niyamas/wagtail_react_ecommerce_tutorial | train | 0 |
3106cb9233ae0604f22467633ca8f556cb0207f5 | [
"self._r1 = r1\nself._r2 = r2\nself._direction = direction",
"delev, dazim = direction\nx1 = -r1 * np.cos(elev) * np.cos(azim)\ny1 = -r1 * np.cos(elev) * np.sin(azim)\nz1 = r1 * np.sin(elev)\ndx1 = -np.cos(delev) * np.cos(dazim)\ndy1 = -np.cos(delev) * np.sin(dazim)\ndz1 = np.sin(delev)\nresult_shape = x1.shape\n... | <|body_start_0|>
self._r1 = r1
self._r2 = r2
self._direction = direction
<|end_body_0|>
<|body_start_1|>
delev, dazim = direction
x1 = -r1 * np.cos(elev) * np.cos(azim)
y1 = -r1 * np.cos(elev) * np.sin(azim)
z1 = r1 * np.sin(elev)
dx1 = -np.cos(delev) * n... | Map points from one sphere to another. spheres are cocentered | SphereToSphereMap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphereToSphereMap:
"""Map points from one sphere to another. spheres are cocentered"""
def __init__(self, r1, r2, direction):
"""r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
<|body_0|>
def m... | stack_v2_sparse_classes_10k_train_008839 | 16,243 | permissive | [
{
"docstring": "r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth",
"name": "__init__",
"signature": "def __init__(self, r1, r2, direction)"
},
{
"docstring": "In case of 2 points of intersection picks the closest",
"na... | 4 | stack_v2_sparse_classes_30k_train_001499 | Implement the Python class `SphereToSphereMap` described below.
Class description:
Map points from one sphere to another. spheres are cocentered
Method signatures and docstrings:
- def __init__(self, r1, r2, direction): r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 ele... | Implement the Python class `SphereToSphereMap` described below.
Class description:
Map points from one sphere to another. spheres are cocentered
Method signatures and docstrings:
- def __init__(self, r1, r2, direction): r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 ele... | fdab351e6c5530c8f051193158856ba6ef11d715 | <|skeleton|>
class SphereToSphereMap:
"""Map points from one sphere to another. spheres are cocentered"""
def __init__(self, r1, r2, direction):
"""r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
<|body_0|>
def m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphereToSphereMap:
"""Map points from one sphere to another. spheres are cocentered"""
def __init__(self, r1, r2, direction):
"""r1: initial sphere radius r2: projected sphere radius direction: can be a tuple or a list of 2 elements elevation, azimuth"""
self._r1 = r1
self._r2 = r... | the_stack_v2_python_sparse | retina/screen/map/mapimpl.py | neurokernel/retina | train | 5 |
c8d2eaf019620e142bdf6922820d2d2048ab44c8 | [
"with shelve.open(Constants.SONAR_DB_PATH) as db:\n tools = db['tool']\n try:\n _dict = tools[tool_name]\n except KeyError:\n _dict = {'versions': [], 'executable': {}, 'script': {}}\n if version in _dict['versions']:\n logger.error(\"%s already exists. Use 'edit' to modify existing... | <|body_start_0|>
with shelve.open(Constants.SONAR_DB_PATH) as db:
tools = db['tool']
try:
_dict = tools[tool_name]
except KeyError:
_dict = {'versions': [], 'executable': {}, 'script': {}}
if version in _dict['versions']:
... | Manage the tools in the database | Tool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tool:
"""Manage the tools in the database"""
def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
"""Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_ex... | stack_v2_sparse_classes_10k_train_008840 | 22,434 | permissive | [
{
"docstring": "Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name of HLS tool executable. None if not applicable sim_exe (str): Name of simulation tool executable. None if not ... | 6 | stack_v2_sparse_classes_30k_train_001745 | Implement the Python class `Tool` described below.
Class description:
Manage the tools in the database
Method signatures and docstrings:
- def add(tool_name, version, cad_exe, hls_exe, sim_exe, script): Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): N... | Implement the Python class `Tool` described below.
Class description:
Manage the tools in the database
Method signatures and docstrings:
- def add(tool_name, version, cad_exe, hls_exe, sim_exe, script): Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): N... | 99de16dd16d0aa77734584e67263c78a37abef86 | <|skeleton|>
class Tool:
"""Manage the tools in the database"""
def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
"""Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_ex... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tool:
"""Manage the tools in the database"""
def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
"""Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name... | the_stack_v2_python_sparse | sonar/database.py | Zyk-Hyphen/sonar | train | 0 |
c79bbf7ec731182ace441f1be630a3d4b9cbbc35 | [
"self.win = win\nself.data = {}\nwith open('level.json', 'r') as _input:\n self.data = json.load(_input)\nself.level = 0\nself.kills = 0\nself.maxlvl = maxlvl\nself.sourceFileDir = os.path.dirname(os.path.abspath(__file__))\nself.godmode = godmode",
"pygame.mixer.music.stop()\npygame.mouse.set_cursor(*pygame.c... | <|body_start_0|>
self.win = win
self.data = {}
with open('level.json', 'r') as _input:
self.data = json.load(_input)
self.level = 0
self.kills = 0
self.maxlvl = maxlvl
self.sourceFileDir = os.path.dirname(os.path.abspath(__file__))
self.godmode... | Run | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Run:
def __init__(self, win, maxlvl=14, godmode=False):
"""Konstruktor Run Objekt Args: win (pygame.window): Das Fenster maxlvl (int, optional): Maximales Level. Defaults to 14. godmode (bool, optional): Soll der Godmode aktiviert sein. Defaults to False."""
<|body_0|>
def r... | stack_v2_sparse_classes_10k_train_008841 | 3,257 | no_license | [
{
"docstring": "Konstruktor Run Objekt Args: win (pygame.window): Das Fenster maxlvl (int, optional): Maximales Level. Defaults to 14. godmode (bool, optional): Soll der Godmode aktiviert sein. Defaults to False.",
"name": "__init__",
"signature": "def __init__(self, win, maxlvl=14, godmode=False)"
},... | 2 | stack_v2_sparse_classes_30k_train_005909 | Implement the Python class `Run` described below.
Class description:
Implement the Run class.
Method signatures and docstrings:
- def __init__(self, win, maxlvl=14, godmode=False): Konstruktor Run Objekt Args: win (pygame.window): Das Fenster maxlvl (int, optional): Maximales Level. Defaults to 14. godmode (bool, opt... | Implement the Python class `Run` described below.
Class description:
Implement the Run class.
Method signatures and docstrings:
- def __init__(self, win, maxlvl=14, godmode=False): Konstruktor Run Objekt Args: win (pygame.window): Das Fenster maxlvl (int, optional): Maximales Level. Defaults to 14. godmode (bool, opt... | e7a922563413618920a5087033cf1a87af7bb420 | <|skeleton|>
class Run:
def __init__(self, win, maxlvl=14, godmode=False):
"""Konstruktor Run Objekt Args: win (pygame.window): Das Fenster maxlvl (int, optional): Maximales Level. Defaults to 14. godmode (bool, optional): Soll der Godmode aktiviert sein. Defaults to False."""
<|body_0|>
def r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Run:
def __init__(self, win, maxlvl=14, godmode=False):
"""Konstruktor Run Objekt Args: win (pygame.window): Das Fenster maxlvl (int, optional): Maximales Level. Defaults to 14. godmode (bool, optional): Soll der Godmode aktiviert sein. Defaults to False."""
self.win = win
self.data = ... | the_stack_v2_python_sparse | Run.py | JNYscript/Neon_Rush | train | 0 | |
981207fc1e8b1b076d16b04652d745c16a15ffba | [
"try:\n challenge = doc.attrib['challenge']\nexcept KeyError:\n challenge = None\npairiter = doc.iter('pair')\nreturn [RTEPair(pair, challenge=challenge) for pair in pairiter]",
"if isinstance(fileids, str):\n fileids = [fileids]\nreturn concat([self._read_etree(self.xml(fileid)) for fileid in fileids])"... | <|body_start_0|>
try:
challenge = doc.attrib['challenge']
except KeyError:
challenge = None
pairiter = doc.iter('pair')
return [RTEPair(pair, challenge=challenge) for pair in pairiter]
<|end_body_0|>
<|body_start_1|>
if isinstance(fileids, str):
... | Corpus reader for corpora in RTE challenges. This is just a wrapper around the XMLCorpusReader. See module docstring above for the expected structure of input documents. | RTECorpusReader | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-ND-3.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RTECorpusReader:
"""Corpus reader for corpora in RTE challenges. This is just a wrapper around the XMLCorpusReader. See module docstring above for the expected structure of input documents."""
def _read_etree(self, doc):
"""Map the XML input into an RTEPair. This uses the ``getiterat... | stack_v2_sparse_classes_10k_train_008842 | 4,639 | permissive | [
{
"docstring": "Map the XML input into an RTEPair. This uses the ``getiterator()`` method from the ElementTree package to find all the ``<pair>`` elements. :param doc: a parsed XML document :rtype: list(RTEPair)",
"name": "_read_etree",
"signature": "def _read_etree(self, doc)"
},
{
"docstring":... | 2 | null | Implement the Python class `RTECorpusReader` described below.
Class description:
Corpus reader for corpora in RTE challenges. This is just a wrapper around the XMLCorpusReader. See module docstring above for the expected structure of input documents.
Method signatures and docstrings:
- def _read_etree(self, doc): Map... | Implement the Python class `RTECorpusReader` described below.
Class description:
Corpus reader for corpora in RTE challenges. This is just a wrapper around the XMLCorpusReader. See module docstring above for the expected structure of input documents.
Method signatures and docstrings:
- def _read_etree(self, doc): Map... | 582e6e35f0e6c984b44ec49dcb8846d9c011d0a8 | <|skeleton|>
class RTECorpusReader:
"""Corpus reader for corpora in RTE challenges. This is just a wrapper around the XMLCorpusReader. See module docstring above for the expected structure of input documents."""
def _read_etree(self, doc):
"""Map the XML input into an RTEPair. This uses the ``getiterat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RTECorpusReader:
"""Corpus reader for corpora in RTE challenges. This is just a wrapper around the XMLCorpusReader. See module docstring above for the expected structure of input documents."""
def _read_etree(self, doc):
"""Map the XML input into an RTEPair. This uses the ``getiterator()`` method... | the_stack_v2_python_sparse | nltk/corpus/reader/rte.py | nltk/nltk | train | 11,860 |
c32d095a167e07f80dab1d517246515fb238d896 | [
"action = self.request.get('action')\nif action == 'view_plans':\n page = self.request.get('p')\n order = self.request.get('order')\n self.viewPlans(page, order)\nelse:\n self.viewPlans('1', '')",
"template_data = Controller().loadPlans(page, order)\nmessage = self.request.get('m')\nif message == '' o... | <|body_start_0|>
action = self.request.get('action')
if action == 'view_plans':
page = self.request.get('p')
order = self.request.get('order')
self.viewPlans(page, order)
else:
self.viewPlans('1', '')
<|end_body_0|>
<|body_start_1|>
templa... | View | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
def get(self):
"""Handles GET requests"""
<|body_0|>
def viewPlans(self, page, order):
"""Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagination index. @param order: The order defined by the user t... | stack_v2_sparse_classes_10k_train_008843 | 5,552 | no_license | [
{
"docstring": "Handles GET requests",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagination index. @param order: The order defined by the user to show the plans.",
... | 2 | stack_v2_sparse_classes_30k_train_006383 | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def get(self): Handles GET requests
- def viewPlans(self, page, order): Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagina... | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def get(self): Handles GET requests
- def viewPlans(self, page, order): Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagina... | 95cc24e41590853cf0d2d35e6bf2ba1bd0701d48 | <|skeleton|>
class View:
def get(self):
"""Handles GET requests"""
<|body_0|>
def viewPlans(self, page, order):
"""Loads a number of plans into a Plan list, and renders it to the HTML @param page: The current page from the pagination index. @param order: The order defined by the user t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class View:
def get(self):
"""Handles GET requests"""
action = self.request.get('action')
if action == 'view_plans':
page = self.request.get('p')
order = self.request.get('order')
self.viewPlans(page, order)
else:
self.viewPlans('1', ''... | the_stack_v2_python_sparse | python/src/plan.py | cjlallana/gae-course-application | train | 0 | |
2ffeee91f53ed69de3fe2392bb2e44aecbbf4ac2 | [
"string_builder = ''\nif s == '':\n return True\nfor i in range(len(s)):\n string_builder += s[i]\n if string_builder in dict:\n try:\n if self.wordBreak_TLE(s[i + 1:], dict):\n return True\n else:\n continue\n except IndexError:\n ... | <|body_start_0|>
string_builder = ''
if s == '':
return True
for i in range(len(s)):
string_builder += s[i]
if string_builder in dict:
try:
if self.wordBreak_TLE(s[i + 1:], dict):
return True
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
... | stack_v2_sparse_classes_10k_train_008844 | 3,284 | permissive | [
{
"docstring": "TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean",
"name": "wordBreak_TLE",
"signature": "def wordBrea... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_TLE(self, s, dict): TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can u... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_TLE(self, s, dict): TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can u... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
string_bu... | the_stack_v2_python_sparse | 139 Word Break.py | Aminaba123/LeetCode | train | 1 | |
a42013644efa98225bd0fcc117f367acbd409d27 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(username=username, email=ema... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name)
user.set_password(password)
user.save(using=self._db)
return user
<|... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, first name, last name and password."""
<|body_0|>
def create_superuser(self, username, email, password):
... | stack_v2_sparse_classes_10k_train_008845 | 3,190 | no_license | [
{
"docstring": "Creates and saves a User with the given email, first name, last name and password.",
"name": "create_user",
"signature": "def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None)"
},
{
"docstring": "Creates and saves a superuser with the gi... | 2 | stack_v2_sparse_classes_30k_train_006225 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, first name, last name a... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, first name, last name a... | d73d61e46b96561521a35777be363d2276617fc0 | <|skeleton|>
class MyUserManager:
def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, first name, last name and password."""
<|body_0|>
def create_superuser(self, username, email, password):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, first name, last name and password."""
if not email:
raise ValueError('Users must have an email address')
user ... | the_stack_v2_python_sparse | src/accounts/models.py | rcmiskin10/university-social-network | train | 0 | |
84d7cdb6fa84a379be1da943b21980834869f76a | [
"self.input = '1905'\nself.output = ['1w0j', '1w0k', '1w0l', '1x0j', '1x0k', '1x0l', '1y0j', '1y0k', '1y0l', '1z0j', '1z0k', '1z0l']\nreturn (self.input, self.output)",
"input_number, correct_output = self.SetUp()\noutput = phoneNumberMnemonics(input_number)\nself.assertEqual(output, correct_output)"
] | <|body_start_0|>
self.input = '1905'
self.output = ['1w0j', '1w0k', '1w0l', '1x0j', '1x0k', '1x0l', '1y0j', '1y0k', '1y0l', '1z0j', '1z0k', '1z0l']
return (self.input, self.output)
<|end_body_0|>
<|body_start_1|>
input_number, correct_output = self.SetUp()
output = phoneNumberMn... | Class with unittests for PhoneNumberMnemonics.py | test_PhoneNumberMnemonics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_PhoneNumberMnemonics:
"""Class with unittests for PhoneNumberMnemonics.py"""
def SetUp(self):
"""Set Up input and output lists."""
<|body_0|>
def test_Iterative_method(self):
"""Checks if output is correct."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_008846 | 1,328 | no_license | [
{
"docstring": "Set Up input and output lists.",
"name": "SetUp",
"signature": "def SetUp(self)"
},
{
"docstring": "Checks if output is correct.",
"name": "test_Iterative_method",
"signature": "def test_Iterative_method(self)"
}
] | 2 | null | Implement the Python class `test_PhoneNumberMnemonics` described below.
Class description:
Class with unittests for PhoneNumberMnemonics.py
Method signatures and docstrings:
- def SetUp(self): Set Up input and output lists.
- def test_Iterative_method(self): Checks if output is correct. | Implement the Python class `test_PhoneNumberMnemonics` described below.
Class description:
Class with unittests for PhoneNumberMnemonics.py
Method signatures and docstrings:
- def SetUp(self): Set Up input and output lists.
- def test_Iterative_method(self): Checks if output is correct.
<|skeleton|>
class test_Phone... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_PhoneNumberMnemonics:
"""Class with unittests for PhoneNumberMnemonics.py"""
def SetUp(self):
"""Set Up input and output lists."""
<|body_0|>
def test_Iterative_method(self):
"""Checks if output is correct."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class test_PhoneNumberMnemonics:
"""Class with unittests for PhoneNumberMnemonics.py"""
def SetUp(self):
"""Set Up input and output lists."""
self.input = '1905'
self.output = ['1w0j', '1w0k', '1w0l', '1x0j', '1x0k', '1x0l', '1y0j', '1y0k', '1y0l', '1z0j', '1z0k', '1z0l']
return... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/PhoneNumberMnemonics/test_PhoneNumberMnemonics.py | JakubKazimierski/PythonPortfolio | train | 9 |
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_10k_train_008847 | 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_004390 | 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_10k | 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 |
e8b1cbb9eceeb896f4a4d41ff8f253903f3f66c7 | [
"self.camID = camID\nwith open(camera_cal_file, 'r') as yfile:\n params = yaml.load(yfile)\nself.nx0 = params[camID]['nx0']\nself.ny0 = self.nx0\nself.pr0 = (self.nx0 + self.ny0) / 4.0\nself.ndy0 = params[camID]['ndy0']\nself.ndx0 = params[camID]['ndx0']\nself.cx = params[camID]['cx']\nself.cy = params[camID]['c... | <|body_start_0|>
self.camID = camID
with open(camera_cal_file, 'r') as yfile:
params = yaml.load(yfile)
self.nx0 = params[camID]['nx0']
self.ny0 = self.nx0
self.pr0 = (self.nx0 + self.ny0) / 4.0
self.ndy0 = params[camID]['ndy0']
self.ndx0 = params[camI... | camera | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class camera:
def __init__(self, camID, camera_cal_file='camera_cal_bnl.yaml'):
"""Initialize a camera class object"""
<|body_0|>
def save_dict_to_yaml(self, resxin, outfile):
"""write camera named params into yaml outfile in block style"""
<|body_1|>
def save... | stack_v2_sparse_classes_10k_train_008848 | 7,697 | permissive | [
{
"docstring": "Initialize a camera class object",
"name": "__init__",
"signature": "def __init__(self, camID, camera_cal_file='camera_cal_bnl.yaml')"
},
{
"docstring": "write camera named params into yaml outfile in block style",
"name": "save_dict_to_yaml",
"signature": "def save_dict_... | 5 | stack_v2_sparse_classes_30k_train_001344 | Implement the Python class `camera` described below.
Class description:
Implement the camera class.
Method signatures and docstrings:
- def __init__(self, camID, camera_cal_file='camera_cal_bnl.yaml'): Initialize a camera class object
- def save_dict_to_yaml(self, resxin, outfile): write camera named params into yaml... | Implement the Python class `camera` described below.
Class description:
Implement the camera class.
Method signatures and docstrings:
- def __init__(self, camID, camera_cal_file='camera_cal_bnl.yaml'): Initialize a camera class object
- def save_dict_to_yaml(self, resxin, outfile): write camera named params into yaml... | 4781f10772178eac0cc7c456c3fa03f68bfb9167 | <|skeleton|>
class camera:
def __init__(self, camID, camera_cal_file='camera_cal_bnl.yaml'):
"""Initialize a camera class object"""
<|body_0|>
def save_dict_to_yaml(self, resxin, outfile):
"""write camera named params into yaml outfile in block style"""
<|body_1|>
def save... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class camera:
def __init__(self, camID, camera_cal_file='camera_cal_bnl.yaml'):
"""Initialize a camera class object"""
self.camID = camID
with open(camera_cal_file, 'r') as yfile:
params = yaml.load(yfile)
self.nx0 = params[camID]['nx0']
self.ny0 = self.nx0
... | the_stack_v2_python_sparse | camera_calibration/camcoord.py | BNL-NowCasting/SolarForecasting | train | 2 | |
c73e3b8a572c638085919b3aefd202c99b489de8 | [
"try:\n return cls._CODE_MAP[code]\nexcept KeyError as err:\n raise ValueError(f\"Cannot find a region for the code '{code}'\") from err",
"if cls._current_region is None:\n raise ValueError('You must set the active region with `set_region()` before it can be accessed')\nreturn cls._current_region",
"t... | <|body_start_0|>
try:
return cls._CODE_MAP[code]
except KeyError as err:
raise ValueError(f"Cannot find a region for the code '{code}'") from err
<|end_body_0|>
<|body_start_1|>
if cls._current_region is None:
raise ValueError('You must set the active region ... | A collection of all the regions as an enum like object. | Regions | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regions:
"""A collection of all the regions as an enum like object."""
def from_code(cls, code: str) -> Region:
"""Get a region object based on its code. :raises ValueError: If no valid region can be found."""
<|body_0|>
def get_region(cls) -> Region:
"""Get the ... | stack_v2_sparse_classes_10k_train_008849 | 2,395 | permissive | [
{
"docstring": "Get a region object based on its code. :raises ValueError: If no valid region can be found.",
"name": "from_code",
"signature": "def from_code(cls, code: str) -> Region"
},
{
"docstring": "Get the region this app is running in. :raises ValueError: If the active region has not bee... | 3 | null | Implement the Python class `Regions` described below.
Class description:
A collection of all the regions as an enum like object.
Method signatures and docstrings:
- def from_code(cls, code: str) -> Region: Get a region object based on its code. :raises ValueError: If no valid region can be found.
- def get_region(cls... | Implement the Python class `Regions` described below.
Class description:
A collection of all the regions as an enum like object.
Method signatures and docstrings:
- def from_code(cls, code: str) -> Region: Get a region object based on its code. :raises ValueError: If no valid region can be found.
- def get_region(cls... | 86614d8fe690ca52516fef87bfffe9e61dd2c21f | <|skeleton|>
class Regions:
"""A collection of all the regions as an enum like object."""
def from_code(cls, code: str) -> Region:
"""Get a region object based on its code. :raises ValueError: If no valid region can be found."""
<|body_0|>
def get_region(cls) -> Region:
"""Get the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Regions:
"""A collection of all the regions as an enum like object."""
def from_code(cls, code: str) -> Region:
"""Get a region object based on its code. :raises ValueError: If no valid region can be found."""
try:
return cls._CODE_MAP[code]
except KeyError as err:
... | the_stack_v2_python_sparse | lms/models/region.py | hypothesis/lms | train | 44 |
6fd5f346d0e8c0069b3d5dbb8f1f97a2d3d3be0a | [
"super(RequestData, self).__init__()\nself.program = None\nself.program_timeline = None\nself.org_app = None\nself.profile = None\nself.is_host = False\nself.mentor_for = []\nself.org_admin_for = []\nself.applied_to = []\nself.not_applied_to = []\nself.student_info = None",
"if isinstance(organization, db.Model):... | <|body_start_0|>
super(RequestData, self).__init__()
self.program = None
self.program_timeline = None
self.org_app = None
self.profile = None
self.is_host = False
self.mentor_for = []
self.org_admin_for = []
self.applied_to = []
self.not_ap... | Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_timeline: The GSoCTimeline entity timeli... | RequestData | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestData:
"""Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_t... | stack_v2_sparse_classes_10k_train_008850 | 14,575 | permissive | [
{
"docstring": "Constructs an empty RequestData object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns true iff the user is admin for the specified organization. Organization may either be a key or an organization instance.",
"name": "orgAdminFor",
"si... | 6 | stack_v2_sparse_classes_30k_train_004037 | Implement the Python class `RequestData` described below.
Class description:
Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity th... | Implement the Python class `RequestData` described below.
Class description:
Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity th... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class RequestData:
"""Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RequestData:
"""Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_timeline: The ... | the_stack_v2_python_sparse | app/soc/modules/gsoc/views/helper/request_data.py | pombredanne/Melange-1 | train | 0 |
f59098d37c9d75f5838d1c95cb05601d8167acf8 | [
"dist_vect = []\nfor j in range(self._datalen):\n if inst != j:\n locator = [inst, j]\n if inst < j:\n locator.reverse()\n dist_vect.append(self._distance_array[locator[0]][locator[1]])\ndist_vect = np.array(dist_vect)\ninst_avg_dist = np.average(dist_vect)\ninst_std = np.std(dist... | <|body_start_0|>
dist_vect = []
for j in range(self._datalen):
if inst != j:
locator = [inst, j]
if inst < j:
locator.reverse()
dist_vect.append(self._distance_array[locator[0]][locator[1]])
dist_vect = np.array(dist... | Feature selection using data-mined expert knowledge. Based on the MultiSURF algorithm as introduced in: Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF for the Genetic Analysis of Complex Human Diseases. | MultiSURFstar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiSURFstar:
"""Feature selection using data-mined expert knowledge. Based on the MultiSURF algorithm as introduced in: Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF for the Genetic Analysis of Complex Human Diseases."""
def _find_neighbors(self, inst):
"""Identi... | stack_v2_sparse_classes_10k_train_008851 | 3,281 | no_license | [
{
"docstring": "Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace. This works the same regardless of endpoint type.",
"name": "_find_neighbors",
"signature": "def _find_neighbors(self, inst)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_004839 | Implement the Python class `MultiSURFstar` described below.
Class description:
Feature selection using data-mined expert knowledge. Based on the MultiSURF algorithm as introduced in: Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF for the Genetic Analysis of Complex Human Diseases.
Method signatures ... | Implement the Python class `MultiSURFstar` described below.
Class description:
Feature selection using data-mined expert knowledge. Based on the MultiSURF algorithm as introduced in: Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF for the Genetic Analysis of Complex Human Diseases.
Method signatures ... | c2719345ed5016fae664275e3b913b9d4fc582f9 | <|skeleton|>
class MultiSURFstar:
"""Feature selection using data-mined expert knowledge. Based on the MultiSURF algorithm as introduced in: Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF for the Genetic Analysis of Complex Human Diseases."""
def _find_neighbors(self, inst):
"""Identi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiSURFstar:
"""Feature selection using data-mined expert knowledge. Based on the MultiSURF algorithm as introduced in: Moore, Jason et al. Multiple Threshold Spatially Uniform ReliefF for the Genetic Analysis of Complex Human Diseases."""
def _find_neighbors(self, inst):
"""Identify nearest as... | the_stack_v2_python_sparse | implementations-develop/algorithms/MultiSURFstar/reference_impl.py | jernejvivod/bachelors-thesis | train | 0 |
0b4e70cd72a130822d9dae9ef9d13eaffb401c63 | [
"def helper(tree, lower=float('-inf'), upper=float('inf')):\n if not tree:\n return True\n val = tree.val\n if val <= lower or val >= upper:\n return False\n return helper(tree.left, lower, val) and helper(tree.right, val, upper)\nreturn helper(root)",
"if not root:\n return True\nsta... | <|body_start_0|>
def helper(tree, lower=float('-inf'), upper=float('inf')):
if not tree:
return True
val = tree.val
if val <= lower or val >= upper:
return False
return helper(tree.left, lower, val) and helper(tree.right, val, upper... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root):
"""DFS (recursive)"""
<|body_0|>
def isValidBST2(self, root):
"""DFS (Iteration)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(tree, lower=float('-inf'), upper=float('inf')):
if not tree... | stack_v2_sparse_classes_10k_train_008852 | 1,730 | permissive | [
{
"docstring": "DFS (recursive)",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": "DFS (Iteration)",
"name": "isValidBST2",
"signature": "def isValidBST2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001404 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): DFS (recursive)
- def isValidBST2(self, root): DFS (Iteration) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): DFS (recursive)
- def isValidBST2(self, root): DFS (Iteration)
<|skeleton|>
class Solution:
def isValidBST(self, root):
"""DFS (recursiv... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def isValidBST(self, root):
"""DFS (recursive)"""
<|body_0|>
def isValidBST2(self, root):
"""DFS (Iteration)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidBST(self, root):
"""DFS (recursive)"""
def helper(tree, lower=float('-inf'), upper=float('inf')):
if not tree:
return True
val = tree.val
if val <= lower or val >= upper:
return False
return he... | the_stack_v2_python_sparse | leetcode/0098_validate_binary_search_tree.py | chaosWsF/Python-Practice | train | 1 | |
96fcc3791c667e30c2cae0720a0cb138284f074b | [
"super().save_model(request, obj, form, change)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache.delete('index_page_data')",
"super().delete_model(request, obj)\nfrom celery_tasks.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncach... | <|body_start_0|>
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
<|end_body_0|>
<|body_start_1|>
super().delete_model(request, obj)
from celery_tas... | 商品种类模型管理器类 | BaseModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModel:
"""商品种类模型管理器类"""
def save_model(self, request, obj, form, change):
"""新增或更新表中的数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().save_model(request, obj, for... | stack_v2_sparse_classes_10k_train_008853 | 1,892 | no_license | [
{
"docstring": "新增或更新表中的数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "删除表中的数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | null | Implement the Python class `BaseModel` described below.
Class description:
商品种类模型管理器类
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增或更新表中的数据时调用
- def delete_model(self, request, obj): 删除表中的数据时调用 | Implement the Python class `BaseModel` described below.
Class description:
商品种类模型管理器类
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增或更新表中的数据时调用
- def delete_model(self, request, obj): 删除表中的数据时调用
<|skeleton|>
class BaseModel:
"""商品种类模型管理器类"""
def save_model(self, req... | 0267ef3cbc8c0e66f42f0b718769cce2cd94c576 | <|skeleton|>
class BaseModel:
"""商品种类模型管理器类"""
def save_model(self, request, obj, form, change):
"""新增或更新表中的数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseModel:
"""商品种类模型管理器类"""
def save_model(self, request, obj, form, change):
"""新增或更新表中的数据时调用"""
super().save_model(request, obj, form, change)
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_da... | the_stack_v2_python_sparse | Python_Workspace/DjangoDemo/dailyFresh/apps/goods/admin.py | lxconfig/BlockChainDemo | train | 14 |
28e24b31e0271fe24559f6fdfff255d20ff1d1e8 | [
"try:\n if not data['project_id'] or not data['case_id'] or (not data['id']) or (not data['host_id']):\n return JsonResponse(code=code.CODE_PARAMETER_ERROR)\nexcept KeyError:\n return JsonResponse(code=code.CODE_PARAMETER_ERROR)",
"data = JSONParser().parse(request)\nproject = get_availability_projec... | <|body_start_0|>
try:
if not data['project_id'] or not data['case_id'] or (not data['id']) or (not data['host_id']):
return JsonResponse(code=code.CODE_PARAMETER_ERROR)
except KeyError:
return JsonResponse(code=code.CODE_PARAMETER_ERROR)
<|end_body_0|>
<|body_sta... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""执行 :param request: :return:0"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
if not data['project_id'] or not data['case_... | stack_v2_sparse_classes_10k_train_008854 | 11,514 | no_license | [
{
"docstring": "校验参数 :param data: :return:",
"name": "parameter_check",
"signature": "def parameter_check(self, data)"
},
{
"docstring": "执行 :param request: :return:0",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003043 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 执行 :param request: :return:0 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 执行 :param request: :return:0
<|skeleton|>
class Test:
def parameter_check(self, data):
... | 85a3804c10c6966eecf89deb7a6baccd2a03b875 | <|skeleton|>
class Test:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""执行 :param request: :return:0"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
try:
if not data['project_id'] or not data['case_id'] or (not data['id']) or (not data['host_id']):
return JsonResponse(code=code.CODE_PARAMETER_ERROR)
except KeyError:
retur... | the_stack_v2_python_sparse | api_test/views/test_case.py | AqiComing/Aqi_Automations_API | train | 0 | |
a72cf1bd69b4cc5115247c01cb45db7465c52a90 | [
"my_stack = []\nfor c in S:\n if not my_stack or c != my_stack[-1]:\n my_stack.append(c)\n elif c == my_stack[-1]:\n my_stack.pop()\nreturn ''.join(my_stack)",
"my_dict = set((2 * c for c in ascii_lowercase))\nn = float('inf')\nwhile n != len(S):\n n = len(S)\n for cc in my_dict:\n ... | <|body_start_0|>
my_stack = []
for c in S:
if not my_stack or c != my_stack[-1]:
my_stack.append(c)
elif c == my_stack[-1]:
my_stack.pop()
return ''.join(my_stack)
<|end_body_0|>
<|body_start_1|>
my_dict = set((2 * c for c in ascii... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates0(self, S: str) -> str:
"""Purpose: Removes all duplicate characters in a string until there are none. Example: 'abbaccd' -> 'aaccd' -> 'ccd' -> 'd'. Time Complexity: O(n) Space Complexity: O(n - d), n is length of S, d is length of all duplicates, hence d <... | stack_v2_sparse_classes_10k_train_008855 | 1,003 | no_license | [
{
"docstring": "Purpose: Removes all duplicate characters in a string until there are none. Example: 'abbaccd' -> 'aaccd' -> 'ccd' -> 'd'. Time Complexity: O(n) Space Complexity: O(n - d), n is length of S, d is length of all duplicates, hence d < n for all d. Very beautiful example of when stacks are helpful!"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates0(self, S: str) -> str: Purpose: Removes all duplicate characters in a string until there are none. Example: 'abbaccd' -> 'aaccd' -> 'ccd' -> 'd'. Time Comple... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates0(self, S: str) -> str: Purpose: Removes all duplicate characters in a string until there are none. Example: 'abbaccd' -> 'aaccd' -> 'ccd' -> 'd'. Time Comple... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def removeDuplicates0(self, S: str) -> str:
"""Purpose: Removes all duplicate characters in a string until there are none. Example: 'abbaccd' -> 'aaccd' -> 'ccd' -> 'd'. Time Complexity: O(n) Space Complexity: O(n - d), n is length of S, d is length of all duplicates, hence d <... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates0(self, S: str) -> str:
"""Purpose: Removes all duplicate characters in a string until there are none. Example: 'abbaccd' -> 'aaccd' -> 'ccd' -> 'd'. Time Complexity: O(n) Space Complexity: O(n - d), n is length of S, d is length of all duplicates, hence d < n for all d. ... | the_stack_v2_python_sparse | remove_dupes.py | tashakim/puzzles_python | train | 8 | |
ae5dfa7fa6a0d7349d6ae29aeac819903facb48f | [
"rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3)\nap = APInfo(port_id=1, ip='2.2.2.2', mac='bb:bb:bb:bb:bb:bb', radio_mac='bb:bb:bb:bb:bb:00', udp_port=12345, wlc_ip='1.1.1.1', gateway_ip='1.1.1.2', ap_mode=APMode.LOCAL, rsa_ca_priv_file=rsa_ca_priv_file, rsa_priv_file=rsa_priv_file, rsa_cert_file=rsa_cer... | <|body_start_0|>
rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3)
ap = APInfo(port_id=1, ip='2.2.2.2', mac='bb:bb:bb:bb:bb:bb', radio_mac='bb:bb:bb:bb:bb:00', udp_port=12345, wlc_ip='1.1.1.1', gateway_ip='1.1.1.2', ap_mode=APMode.LOCAL, rsa_ca_priv_file=rsa_ca_priv_file, rsa_priv_file=rsa_priv_... | Tests methods for the APInfo class. | APInfoTest | [
"Apache-2.0",
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APInfoTest:
"""Tests methods for the APInfo class."""
def test_init_correct(self):
"""Test the __init__ method when parameters are correct."""
<|body_0|>
def test_init_no_mac(self):
"""Test the __init__ method when parameter 'mac' is None. Should raise an Attribu... | stack_v2_sparse_classes_10k_train_008856 | 4,398 | permissive | [
{
"docstring": "Test the __init__ method when parameters are correct.",
"name": "test_init_correct",
"signature": "def test_init_correct(self)"
},
{
"docstring": "Test the __init__ method when parameter 'mac' is None. Should raise an AttributeError.",
"name": "test_init_no_mac",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_006150 | Implement the Python class `APInfoTest` described below.
Class description:
Tests methods for the APInfo class.
Method signatures and docstrings:
- def test_init_correct(self): Test the __init__ method when parameters are correct.
- def test_init_no_mac(self): Test the __init__ method when parameter 'mac' is None. Sh... | Implement the Python class `APInfoTest` described below.
Class description:
Tests methods for the APInfo class.
Method signatures and docstrings:
- def test_init_correct(self): Test the __init__ method when parameters are correct.
- def test_init_no_mac(self): Test the __init__ method when parameter 'mac' is None. Sh... | 3a6d63af1ff468f94887a091e3a408a8449cf832 | <|skeleton|>
class APInfoTest:
"""Tests methods for the APInfo class."""
def test_init_correct(self):
"""Test the __init__ method when parameters are correct."""
<|body_0|>
def test_init_no_mac(self):
"""Test the __init__ method when parameter 'mac' is None. Should raise an Attribu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class APInfoTest:
"""Tests methods for the APInfo class."""
def test_init_correct(self):
"""Test the __init__ method when parameters are correct."""
rsa_ca_priv_file, rsa_priv_file, rsa_cert_file = range(3)
ap = APInfo(port_id=1, ip='2.2.2.2', mac='bb:bb:bb:bb:bb:bb', radio_mac='bb:bb:b... | the_stack_v2_python_sparse | scripts/automation/trex_control_plane/interactive/trex/wireless/unit_tests/trex_wireless_manager_private_test.py | elados93/trex-core | train | 1 |
dd1325090d40d4493cfa66d0e5a6127576bda873 | [
"self.collections = kwargs.pop('collections', None)\nsuper(Synchronizable, self).__init__(*args, scope=kwargs.pop('scope', 'synchronizable'), **kwargs)\nself.define_inputs('_values')\nself.define_outputs('sync')\nself.add_graph_fn('_values', 'sync', self._graph_fn_sync, flatten_ops=False)",
"syncs = list()\nparen... | <|body_start_0|>
self.collections = kwargs.pop('collections', None)
super(Synchronizable, self).__init__(*args, scope=kwargs.pop('scope', 'synchronizable'), **kwargs)
self.define_inputs('_values')
self.define_outputs('sync')
self.add_graph_fn('_values', 'sync', self._graph_fn_syn... | The Synchronizable Component adds a simple synchronization API to arbitrary Components to which this Synchronizable is added (and connected via `connections=CONNECT_ALL`). This is useful for constructions like a target network in DQN or for distributed setups where e.g. local policies need to be sync'd from a global mo... | Synchronizable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Synchronizable:
"""The Synchronizable Component adds a simple synchronization API to arbitrary Components to which this Synchronizable is added (and connected via `connections=CONNECT_ALL`). This is useful for constructions like a target network in DQN or for distributed setups where e.g. local p... | stack_v2_sparse_classes_10k_train_008857 | 4,545 | permissive | [
{
"docstring": "Keyword Args: collections (set): A set of specifiers (currently only tf), that determine which Variables of the parent Component to synchronize.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Generates the op that syncs this Synchroniz... | 2 | stack_v2_sparse_classes_30k_train_005829 | Implement the Python class `Synchronizable` described below.
Class description:
The Synchronizable Component adds a simple synchronization API to arbitrary Components to which this Synchronizable is added (and connected via `connections=CONNECT_ALL`). This is useful for constructions like a target network in DQN or fo... | Implement the Python class `Synchronizable` described below.
Class description:
The Synchronizable Component adds a simple synchronization API to arbitrary Components to which this Synchronizable is added (and connected via `connections=CONNECT_ALL`). This is useful for constructions like a target network in DQN or fo... | ff7d4768579c0e30aa6ceb932cd16f1e51940010 | <|skeleton|>
class Synchronizable:
"""The Synchronizable Component adds a simple synchronization API to arbitrary Components to which this Synchronizable is added (and connected via `connections=CONNECT_ALL`). This is useful for constructions like a target network in DQN or for distributed setups where e.g. local p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Synchronizable:
"""The Synchronizable Component adds a simple synchronization API to arbitrary Components to which this Synchronizable is added (and connected via `connections=CONNECT_ALL`). This is useful for constructions like a target network in DQN or for distributed setups where e.g. local policies need ... | the_stack_v2_python_sparse | yarl/components/common/synchronizable.py | pascalwhoop/YARL | train | 0 |
a1648c1a2bb9f3e5b92a87bc73a7821785155aea | [
"encryption_validator = EncryptionValidationHandler()\nencryption_processor = EncryptionProccessorHandler()\nencryption_resulter = EncryptionResultHandler()\nencryption_validator.set_handler(encryption_processor)\nencryption_processor.set_handler(encryption_resulter)\ndecryption_validator = DecryptionValidationHand... | <|body_start_0|>
encryption_validator = EncryptionValidationHandler()
encryption_processor = EncryptionProccessorHandler()
encryption_resulter = EncryptionResultHandler()
encryption_validator.set_handler(encryption_processor)
encryption_processor.set_handler(encryption_resulter)
... | Crypto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crypto:
def __init__(self):
"""Sets up the chain of responsibility."""
<|body_0|>
def execute_request(self, request: Request):
"""Execute the corrrect chain of responsibility handler depending on Encryption or Decryption Mode. :param request: the Request to pass to h... | stack_v2_sparse_classes_10k_train_008858 | 11,978 | no_license | [
{
"docstring": "Sets up the chain of responsibility.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Execute the corrrect chain of responsibility handler depending on Encryption or Decryption Mode. :param request: the Request to pass to handlers. :return:",
"name":... | 2 | stack_v2_sparse_classes_30k_train_003737 | Implement the Python class `Crypto` described below.
Class description:
Implement the Crypto class.
Method signatures and docstrings:
- def __init__(self): Sets up the chain of responsibility.
- def execute_request(self, request: Request): Execute the corrrect chain of responsibility handler depending on Encryption o... | Implement the Python class `Crypto` described below.
Class description:
Implement the Crypto class.
Method signatures and docstrings:
- def __init__(self): Sets up the chain of responsibility.
- def execute_request(self, request: Request): Execute the corrrect chain of responsibility handler depending on Encryption o... | 00fb890bb9d39859af2211db1f2bd783fcb04d2d | <|skeleton|>
class Crypto:
def __init__(self):
"""Sets up the chain of responsibility."""
<|body_0|>
def execute_request(self, request: Request):
"""Execute the corrrect chain of responsibility handler depending on Encryption or Decryption Mode. :param request: the Request to pass to h... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Crypto:
def __init__(self):
"""Sets up the chain of responsibility."""
encryption_validator = EncryptionValidationHandler()
encryption_processor = EncryptionProccessorHandler()
encryption_resulter = EncryptionResultHandler()
encryption_validator.set_handler(encryption_p... | the_stack_v2_python_sparse | Labs/Lab9/crypto.py | ZenenHornstein/3522_A01185704 | train | 0 | |
767c265b8a5fa12f34d0bba14d0b2bac18792c81 | [
"if options is None:\n options = {}\nif not options.get('secretseed'):\n bundle = False\n filename = '/data/freenas-v1.db'\nelse:\n bundle = True\n filename = tempfile.mkstemp()[1]\n os.chmod(filename, 384)\n with tarfile.open(filename, 'w') as tar:\n tar.add('/data/freenas-v1.db', arcna... | <|body_start_0|>
if options is None:
options = {}
if not options.get('secretseed'):
bundle = False
filename = '/data/freenas-v1.db'
else:
bundle = True
filename = tempfile.mkstemp()[1]
os.chmod(filename, 384)
wit... | ConfigService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigService:
async def save(self, job, options=None):
"""Provide configuration file. secretseed - will include the password secret seed in the bundle."""
<|body_0|>
async def upload(self, job):
"""Accepts a configuration file via job pipe."""
<|body_1|>
<|... | stack_v2_sparse_classes_10k_train_008859 | 2,351 | no_license | [
{
"docstring": "Provide configuration file. secretseed - will include the password secret seed in the bundle.",
"name": "save",
"signature": "async def save(self, job, options=None)"
},
{
"docstring": "Accepts a configuration file via job pipe.",
"name": "upload",
"signature": "async def... | 2 | stack_v2_sparse_classes_30k_test_000254 | Implement the Python class `ConfigService` described below.
Class description:
Implement the ConfigService class.
Method signatures and docstrings:
- async def save(self, job, options=None): Provide configuration file. secretseed - will include the password secret seed in the bundle.
- async def upload(self, job): Ac... | Implement the Python class `ConfigService` described below.
Class description:
Implement the ConfigService class.
Method signatures and docstrings:
- async def save(self, job, options=None): Provide configuration file. secretseed - will include the password secret seed in the bundle.
- async def upload(self, job): Ac... | 9947174014dd740145d540f03c1849a851f3b6e7 | <|skeleton|>
class ConfigService:
async def save(self, job, options=None):
"""Provide configuration file. secretseed - will include the password secret seed in the bundle."""
<|body_0|>
async def upload(self, job):
"""Accepts a configuration file via job pipe."""
<|body_1|>
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigService:
async def save(self, job, options=None):
"""Provide configuration file. secretseed - will include the password secret seed in the bundle."""
if options is None:
options = {}
if not options.get('secretseed'):
bundle = False
filename = '... | the_stack_v2_python_sparse | src/middlewared/middlewared/plugins/config.py | cbwest3/freenas | train | 1 | |
44c08862f267a5a8b97d5a398194554db1382c01 | [
"body = self.client.create_floating_ip(pool=CONF.network.floating_network_name)['floating_ip']\nfloating_ip_id_allocated = body['id']\nself.addCleanup(self.client.delete_floating_ip, floating_ip_id_allocated)\nfloating_ip_details = self.client.show_floating_ip(floating_ip_id_allocated)['floating_ip']\nbody = self.c... | <|body_start_0|>
body = self.client.create_floating_ip(pool=CONF.network.floating_network_name)['floating_ip']
floating_ip_id_allocated = body['id']
self.addCleanup(self.client.delete_floating_ip, floating_ip_id_allocated)
floating_ip_details = self.client.show_floating_ip(floating_ip_id... | Test floating ips API with compute microversion less than 2.36 | FloatingIPsTestJSON | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatingIPsTestJSON:
"""Test floating ips API with compute microversion less than 2.36"""
def test_allocate_floating_ip(self):
"""Test allocating a floating ip to a project"""
<|body_0|>
def test_delete_floating_ip(self):
"""Test deleting a valid floating ip from... | stack_v2_sparse_classes_10k_train_008860 | 5,898 | permissive | [
{
"docstring": "Test allocating a floating ip to a project",
"name": "test_allocate_floating_ip",
"signature": "def test_allocate_floating_ip(self)"
},
{
"docstring": "Test deleting a valid floating ip from project",
"name": "test_delete_floating_ip",
"signature": "def test_delete_floati... | 2 | null | Implement the Python class `FloatingIPsTestJSON` described below.
Class description:
Test floating ips API with compute microversion less than 2.36
Method signatures and docstrings:
- def test_allocate_floating_ip(self): Test allocating a floating ip to a project
- def test_delete_floating_ip(self): Test deleting a v... | Implement the Python class `FloatingIPsTestJSON` described below.
Class description:
Test floating ips API with compute microversion less than 2.36
Method signatures and docstrings:
- def test_allocate_floating_ip(self): Test allocating a floating ip to a project
- def test_delete_floating_ip(self): Test deleting a v... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class FloatingIPsTestJSON:
"""Test floating ips API with compute microversion less than 2.36"""
def test_allocate_floating_ip(self):
"""Test allocating a floating ip to a project"""
<|body_0|>
def test_delete_floating_ip(self):
"""Test deleting a valid floating ip from... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FloatingIPsTestJSON:
"""Test floating ips API with compute microversion less than 2.36"""
def test_allocate_floating_ip(self):
"""Test allocating a floating ip to a project"""
body = self.client.create_floating_ip(pool=CONF.network.floating_network_name)['floating_ip']
floating_ip... | the_stack_v2_python_sparse | tempest/api/compute/floating_ips/test_floating_ips_actions.py | openstack/tempest | train | 270 |
d7cb986dddbab89fe4551ce619ad0b3067effd1f | [
"self.collect_function = collect_function\nself.collapse_function = collapse_function\nself.do_commutative_analysis = do_commutative_analysis\nsuper().__init__()",
"if self.do_commutative_analysis:\n dag = dag_to_dagdependency(dag)\nblocks = self.collect_function(dag)\nself.collapse_function(dag, blocks)\nif s... | <|body_start_0|>
self.collect_function = collect_function
self.collapse_function = collapse_function
self.do_commutative_analysis = do_commutative_analysis
super().__init__()
<|end_body_0|>
<|body_start_1|>
if self.do_commutative_analysis:
dag = dag_to_dagdependency(... | A general transpiler pass to collect and to consolidate blocks of nodes in a circuit. This transpiler pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` takes a DAG and returns a list of blocks. The collapsing function ``collapse_function`` t... | CollectAndCollapse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectAndCollapse:
"""A general transpiler pass to collect and to consolidate blocks of nodes in a circuit. This transpiler pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` takes a DAG and returns a list of blocks. T... | stack_v2_sparse_classes_10k_train_008861 | 4,438 | permissive | [
{
"docstring": "Args: collect_function (callable): a function that takes a DAG and returns a list of \"collected\" blocks of nodes collapse_function (callable): a function that takes a DAG and a list of \"collected\" blocks, and consolidates each block. do_commutative_analysis (bool): if True, exploits commutat... | 2 | stack_v2_sparse_classes_30k_train_004478 | Implement the Python class `CollectAndCollapse` described below.
Class description:
A general transpiler pass to collect and to consolidate blocks of nodes in a circuit. This transpiler pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` take... | Implement the Python class `CollectAndCollapse` described below.
Class description:
A general transpiler pass to collect and to consolidate blocks of nodes in a circuit. This transpiler pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` take... | 0b51250e219ca303654fc28a318c21366584ccd3 | <|skeleton|>
class CollectAndCollapse:
"""A general transpiler pass to collect and to consolidate blocks of nodes in a circuit. This transpiler pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` takes a DAG and returns a list of blocks. T... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CollectAndCollapse:
"""A general transpiler pass to collect and to consolidate blocks of nodes in a circuit. This transpiler pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` takes a DAG and returns a list of blocks. The collapsing... | the_stack_v2_python_sparse | qiskit/transpiler/passes/optimization/collect_and_collapse.py | 1ucian0/qiskit-terra | train | 6 |
803f68a59b240f6bc2cd96f5cb1602e5b68190a3 | [
"patten = ''\nfor x in p:\n if x == '*' and len(patten) > 0 and (patten[-1] == '*'):\n continue\n patten += x\nmem = dict()\n\ndef match(s, p):\n if (s, p) in mem:\n return mem[s, p]\n if len(p) == 0:\n return len(s) == 0\n if len(s) == 0:\n return p in '*' * len(p)\n i... | <|body_start_0|>
patten = ''
for x in p:
if x == '*' and len(patten) > 0 and (patten[-1] == '*'):
continue
patten += x
mem = dict()
def match(s, p):
if (s, p) in mem:
return mem[s, p]
if len(p) == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch2(self, s, p):
"""动态规划"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
patten = ''
for x in p:
if x == '*' and len(patten) > 0 ... | stack_v2_sparse_classes_10k_train_008862 | 2,412 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
},
{
"docstring": "动态规划",
"name": "isMatch2",
"signature": "def isMatch2(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000485 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch2(self, s, p): 动态规划 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch2(self, s, p): 动态规划
<|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: s... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch2(self, s, p):
"""动态规划"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
patten = ''
for x in p:
if x == '*' and len(patten) > 0 and (patten[-1] == '*'):
continue
patten += x
mem = dict()
def match(s, p):
if (s... | the_stack_v2_python_sparse | Tencent/hard/通配符匹配.py | 2226171237/Algorithmpractice | train | 0 | |
4bc8f0bfb6cdb80d47c3f0545e559fbf01850196 | [
"self.coef_ = None\nself.intercept_ = None\nself._theta = None",
"assert X_train.shape[0] == y_train.shape[0], 'The size of X_train must be equal to the size of y_train'\nX_b = np.vstack([np.ones((len(X_train), 1)), X_train])\nself._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)\nself.coef_ = self.... | <|body_start_0|>
self.coef_ = None
self.intercept_ = None
self._theta = None
<|end_body_0|>
<|body_start_1|>
assert X_train.shape[0] == y_train.shape[0], 'The size of X_train must be equal to the size of y_train'
X_b = np.vstack([np.ones((len(X_train), 1)), X_train])
sel... | LinearRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegression:
def __int__(self):
"""构造方法"""
<|body_0|>
def fit_nomal(self, X_train, y_train):
"""根据训练数据集X_train, y_train训练Linear Regression模型"""
<|body_1|>
def predict(self, X_predict):
"""给定待预测数据集X_predict,返回表示X_predict的结果向量"""
<|bod... | stack_v2_sparse_classes_10k_train_008863 | 1,092 | no_license | [
{
"docstring": "构造方法",
"name": "__int__",
"signature": "def __int__(self)"
},
{
"docstring": "根据训练数据集X_train, y_train训练Linear Regression模型",
"name": "fit_nomal",
"signature": "def fit_nomal(self, X_train, y_train)"
},
{
"docstring": "给定待预测数据集X_predict,返回表示X_predict的结果向量",
"na... | 3 | stack_v2_sparse_classes_30k_train_005347 | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def __int__(self): 构造方法
- def fit_nomal(self, X_train, y_train): 根据训练数据集X_train, y_train训练Linear Regression模型
- def predict(self, X_predict): 给定待预测数据集X_predict,返回... | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def __int__(self): 构造方法
- def fit_nomal(self, X_train, y_train): 根据训练数据集X_train, y_train训练Linear Regression模型
- def predict(self, X_predict): 给定待预测数据集X_predict,返回... | 517ac7b7992a686fa5370b6fda8b62663735853c | <|skeleton|>
class LinearRegression:
def __int__(self):
"""构造方法"""
<|body_0|>
def fit_nomal(self, X_train, y_train):
"""根据训练数据集X_train, y_train训练Linear Regression模型"""
<|body_1|>
def predict(self, X_predict):
"""给定待预测数据集X_predict,返回表示X_predict的结果向量"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearRegression:
def __int__(self):
"""构造方法"""
self.coef_ = None
self.intercept_ = None
self._theta = None
def fit_nomal(self, X_train, y_train):
"""根据训练数据集X_train, y_train训练Linear Regression模型"""
assert X_train.shape[0] == y_train.shape[0], 'The size of X... | the_stack_v2_python_sparse | MachineLearning/PlayML/LinearRegression.py | CharlesBird/Resources | train | 1 | |
ed62a18590d04c2e0abd79169cc74f77220acd95 | [
"self.nuts = [Coconut(variety) for variety in ['middle eastern', 'south asian', 'american']]\nself.weights = [2.5, 3.0, 3.5]\nfor i in range(0, 3):\n self.assertEqual(self.nuts[i]._Coconut__weight, self.weights[i], 'The weight is wrong')",
"varieties = [Coconut(variety) for variety in ['middle eastern', 'south... | <|body_start_0|>
self.nuts = [Coconut(variety) for variety in ['middle eastern', 'south asian', 'american']]
self.weights = [2.5, 3.0, 3.5]
for i in range(0, 3):
self.assertEqual(self.nuts[i]._Coconut__weight, self.weights[i], 'The weight is wrong')
<|end_body_0|>
<|body_start_1|>
... | TestCoconuts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCoconuts:
def test_weight(self):
"""Tests that different coconut types each have a different weight"""
<|body_0|>
def test_total_weight(self):
"""Tests that the sum of a specified number of coconuts of each type returned matches the expected total"""
<|bo... | stack_v2_sparse_classes_10k_train_008864 | 2,241 | no_license | [
{
"docstring": "Tests that different coconut types each have a different weight",
"name": "test_weight",
"signature": "def test_weight(self)"
},
{
"docstring": "Tests that the sum of a specified number of coconuts of each type returned matches the expected total",
"name": "test_total_weight"... | 3 | stack_v2_sparse_classes_30k_train_006499 | Implement the Python class `TestCoconuts` described below.
Class description:
Implement the TestCoconuts class.
Method signatures and docstrings:
- def test_weight(self): Tests that different coconut types each have a different weight
- def test_total_weight(self): Tests that the sum of a specified number of coconuts... | Implement the Python class `TestCoconuts` described below.
Class description:
Implement the TestCoconuts class.
Method signatures and docstrings:
- def test_weight(self): Tests that different coconut types each have a different weight
- def test_total_weight(self): Tests that the sum of a specified number of coconuts... | 4ca74dd054be17e7a57da891c5d239e3f915d3f1 | <|skeleton|>
class TestCoconuts:
def test_weight(self):
"""Tests that different coconut types each have a different weight"""
<|body_0|>
def test_total_weight(self):
"""Tests that the sum of a specified number of coconuts of each type returned matches the expected total"""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCoconuts:
def test_weight(self):
"""Tests that different coconut types each have a different weight"""
self.nuts = [Coconut(variety) for variety in ['middle eastern', 'south asian', 'american']]
self.weights = [2.5, 3.0, 3.5]
for i in range(0, 3):
self.assertEqu... | the_stack_v2_python_sparse | Lesson 2 - Converting Data Into Structured Objects/project/attempt_1/test_coconuts.py | jmwoloso/Python_3 | train | 0 | |
b40eb1adc242a7c9c1d2161ab713b7a1ebe15df4 | [
"super(DurationPredictorLoss, self).__init__()\nself.criterion = torch.nn.MSELoss(reduction=reduction)\nself.offset = offset",
"targets = torch.log(targets.float() + self.offset)\nloss = self.criterion(outputs, targets)\nreturn loss"
] | <|body_start_0|>
super(DurationPredictorLoss, self).__init__()
self.criterion = torch.nn.MSELoss(reduction=reduction)
self.offset = offset
<|end_body_0|>
<|body_start_1|>
targets = torch.log(targets.float() + self.offset)
loss = self.criterion(outputs, targets)
return lo... | Loss function module for duration predictor. The loss value is Calculated in log domain to make it Gaussian. | DurationPredictorLoss | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DurationPredictorLoss:
"""Loss function module for duration predictor. The loss value is Calculated in log domain to make it Gaussian."""
def __init__(self, offset=1.0, reduction='mean'):
"""Initilize duration predictor loss module. Args: offset (float, optional): Offset value to avo... | stack_v2_sparse_classes_10k_train_008865 | 1,534 | permissive | [
{
"docstring": "Initilize duration predictor loss module. Args: offset (float, optional): Offset value to avoid nan in log domain. reduction (str): Reduction type in loss calculation.",
"name": "__init__",
"signature": "def __init__(self, offset=1.0, reduction='mean')"
},
{
"docstring": "Calcula... | 2 | stack_v2_sparse_classes_30k_train_005580 | Implement the Python class `DurationPredictorLoss` described below.
Class description:
Loss function module for duration predictor. The loss value is Calculated in log domain to make it Gaussian.
Method signatures and docstrings:
- def __init__(self, offset=1.0, reduction='mean'): Initilize duration predictor loss mo... | Implement the Python class `DurationPredictorLoss` described below.
Class description:
Loss function module for duration predictor. The loss value is Calculated in log domain to make it Gaussian.
Method signatures and docstrings:
- def __init__(self, offset=1.0, reduction='mean'): Initilize duration predictor loss mo... | c68b4590ab20eaf55e0b96b82325a90177fffd5c | <|skeleton|>
class DurationPredictorLoss:
"""Loss function module for duration predictor. The loss value is Calculated in log domain to make it Gaussian."""
def __init__(self, offset=1.0, reduction='mean'):
"""Initilize duration predictor loss module. Args: offset (float, optional): Offset value to avo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DurationPredictorLoss:
"""Loss function module for duration predictor. The loss value is Calculated in log domain to make it Gaussian."""
def __init__(self, offset=1.0, reduction='mean'):
"""Initilize duration predictor loss module. Args: offset (float, optional): Offset value to avoid nan in log... | the_stack_v2_python_sparse | parallel_wavegan/losses/duration_prediction_loss.py | kan-bayashi/ParallelWaveGAN | train | 1,405 |
734dfb90aa36e313b993b584aa43139193fc8621 | [
"customer_data = self.parse_request()\ncustomer = Customer.objects.create(**customer_data)\nsession.auth.set_data(self.request, customer)\nreturn http.HttpResponse()",
"customer = session.auth.get_data(self.request)\nif customer is None:\n return http.HttpResponseForbidden()\npassword_old = kwargs.pop('passwor... | <|body_start_0|>
customer_data = self.parse_request()
customer = Customer.objects.create(**customer_data)
session.auth.set_data(self.request, customer)
return http.HttpResponse()
<|end_body_0|>
<|body_start_1|>
customer = session.auth.get_data(self.request)
if customer i... | CustomerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerView:
def post(self, request, *args, **kwargs):
"""Create customer. Automatically logins."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Update customer fields. 404 if not logged in. If want to set password, old password has to be provided in 'pass... | stack_v2_sparse_classes_10k_train_008866 | 5,815 | no_license | [
{
"docstring": "Create customer. Automatically logins.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update customer fields. 404 if not logged in. If want to set password, old password has to be provided in 'password_old' parameter.",
"name": "p... | 2 | null | Implement the Python class `CustomerView` described below.
Class description:
Implement the CustomerView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Create customer. Automatically logins.
- def put(self, request, *args, **kwargs): Update customer fields. 404 if not logged in. ... | Implement the Python class `CustomerView` described below.
Class description:
Implement the CustomerView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Create customer. Automatically logins.
- def put(self, request, *args, **kwargs): Update customer fields. 404 if not logged in. ... | 038834c0f544d6997613d61d593a7d5abf673c70 | <|skeleton|>
class CustomerView:
def post(self, request, *args, **kwargs):
"""Create customer. Automatically logins."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Update customer fields. 404 if not logged in. If want to set password, old password has to be provided in 'pass... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomerView:
def post(self, request, *args, **kwargs):
"""Create customer. Automatically logins."""
customer_data = self.parse_request()
customer = Customer.objects.create(**customer_data)
session.auth.set_data(self.request, customer)
return http.HttpResponse()
de... | the_stack_v2_python_sparse | sites/hermanmiller/shop/views.py | alexgula/django_sites | train | 0 | |
d2cc412e30fb8ab6432776ebfa83e70e630a5bec | [
"self.cv = cv\nself.age = 0\nself.particles = []",
"self.age += dt\nfor p in self.particles:\n p.update(dt)\nfor i in range(len(self.particles) - 1, -1, -1):\n if not self.particles[i].alive():\n del self.particles[i]"
] | <|body_start_0|>
self.cv = cv
self.age = 0
self.particles = []
<|end_body_0|>
<|body_start_1|>
self.age += dt
for p in self.particles:
p.update(dt)
for i in range(len(self.particles) - 1, -1, -1):
if not self.particles[i].alive():
... | Generic class for fireworks. The main "behavior" of a fireworks is specified via its update method. E.g., new particles can be emitted and added to the particle list. The Fireworks base class automatically updates all particles from the particle list in its update method. Attributes: cv (Tk.canvas): the canvas in which... | Fireworks | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fireworks:
"""Generic class for fireworks. The main "behavior" of a fireworks is specified via its update method. E.g., new particles can be emitted and added to the particle list. The Fireworks base class automatically updates all particles from the particle list in its update method. Attributes... | stack_v2_sparse_classes_10k_train_008867 | 16,427 | permissive | [
{
"docstring": "Init Fireworks objects. Args: cv (Tk.canvas): the canvas in which the particle is drawn.",
"name": "__init__",
"signature": "def __init__(self, cv=None)"
},
{
"docstring": "Update the fireworks' particles and remove dead ones. Args: dt (float): the time that has passed after the ... | 2 | stack_v2_sparse_classes_30k_train_003803 | Implement the Python class `Fireworks` described below.
Class description:
Generic class for fireworks. The main "behavior" of a fireworks is specified via its update method. E.g., new particles can be emitted and added to the particle list. The Fireworks base class automatically updates all particles from the particl... | Implement the Python class `Fireworks` described below.
Class description:
Generic class for fireworks. The main "behavior" of a fireworks is specified via its update method. E.g., new particles can be emitted and added to the particle list. The Fireworks base class automatically updates all particles from the particl... | c6b6d80e9d59f5d115ca8b8fc020fcd6cb030af8 | <|skeleton|>
class Fireworks:
"""Generic class for fireworks. The main "behavior" of a fireworks is specified via its update method. E.g., new particles can be emitted and added to the particle list. The Fireworks base class automatically updates all particles from the particle list in its update method. Attributes... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Fireworks:
"""Generic class for fireworks. The main "behavior" of a fireworks is specified via its update method. E.g., new particles can be emitted and added to the particle list. The Fireworks base class automatically updates all particles from the particle list in its update method. Attributes: cv (Tk.canv... | the_stack_v2_python_sparse | scripts/sheet9/9.2.py | LennartElbe/PythOnline | train | 0 |
5aef20d5f59cc6618328ccf4456ddbc28457dea0 | [
"try:\n f = open('.\\\\etc\\\\Name_Highscore.txt', 'r')\n self.NAME_HIGHSCORE_TABLE = {}\n text = f.readline()\n while text != '':\n temp = text.split(' ')\n self.NAME_HIGHSCORE_TABLE[temp[0]] = int(temp[1])\n text = f.readline()\n f.close()\n self.scores = tuple(self.NAME_HIG... | <|body_start_0|>
try:
f = open('.\\etc\\Name_Highscore.txt', 'r')
self.NAME_HIGHSCORE_TABLE = {}
text = f.readline()
while text != '':
temp = text.split(' ')
self.NAME_HIGHSCORE_TABLE[temp[0]] = int(temp[1])
text = f... | This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore"""
def __init__(self, grid_size):
... | stack_v2_sparse_classes_10k_train_008868 | 8,822 | no_license | [
{
"docstring": ":param grid_size: Is the size of one square side in Pixel",
"name": "__init__",
"signature": "def __init__(self, grid_size)"
},
{
"docstring": "Gets the name the Player Enters, but has following restrictionsto the name: - has to be 1-10 chars - no ' ' are allowed :param DISP: The... | 5 | stack_v2_sparse_classes_30k_train_007161 | Implement the Python class `Player` described below.
Class description:
This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore
Met... | Implement the Python class `Player` described below.
Class description:
This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore
Met... | 0aea111fe5335047f123a3afac0cbe42669df4ae | <|skeleton|>
class Player:
"""This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore"""
def __init__(self, grid_size):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Player:
"""This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore"""
def __init__(self, grid_size):
""":param... | the_stack_v2_python_sparse | Player.py | free43/Pac-Man-in-Python-with-pygame | train | 0 |
a4a18c37df588cc7d4965486140b62e9b15bba47 | [
"dp = [0] * (n + 1)\nif n <= 2:\n return n\ndp[1] = 1\ndp[2] = 2\nfor i in range(3, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nprint(dp[n])\nreturn dp[n]",
"def rec(n, memo):\n if n in memo:\n return memo[n]\n memo[n] = rec(n - 1, memo) + rec(n - 2, memo)\n return memo[n]\nmemo = {}\nmemo[1] =... | <|body_start_0|>
dp = [0] * (n + 1)
if n <= 2:
return n
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
print(dp[n])
return dp[n]
<|end_body_0|>
<|body_start_1|>
def rec(n, memo):
if n in mem... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs_rec(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * (n + 1)
if n <= 2:
return n
... | stack_v2_sparse_classes_10k_train_008869 | 1,740 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs_rec",
"signature": "def climbStairs_rec(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001600 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs_rec(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 climbStairs(self, n): :type n: int :rtype: int
- def climbStairs_rec(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs(self, n):
"... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs_rec(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
dp = [0] * (n + 1)
if n <= 2:
return n
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
print(dp[n])
return dp[n]
def climb... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00070.Climbing Stairs.py | roger6blog/LeetCode | train | 0 | |
a05ad29d5592a1517c358384b5559256a8cf13b0 | [
"self.existing_robots.append(self)\nself.name = None\nself.reset()",
"letters = ''.join(random.sample(string.uppercase, self.LETTERS))\nnumbers = random.randint(0, 10 ** self.DIGITS - 1)\nreturn letters + '{0:0{1}}'.format(numbers, self.DIGITS)",
"while True:\n name = self.generate_name()\n if name not in... | <|body_start_0|>
self.existing_robots.append(self)
self.name = None
self.reset()
<|end_body_0|>
<|body_start_1|>
letters = ''.join(random.sample(string.uppercase, self.LETTERS))
numbers = random.randint(0, 10 ** self.DIGITS - 1)
return letters + '{0:0{1}}'.format(numbers... | A robot with a unique random name. | Robot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Robot:
"""A robot with a unique random name."""
def __init__(self):
"""Create (and boot up) a new robot with a random name."""
<|body_0|>
def generate_name(self):
"""Generate a new random robot name."""
<|body_1|>
def reset(self):
"""Reset ro... | stack_v2_sparse_classes_10k_train_008870 | 858 | no_license | [
{
"docstring": "Create (and boot up) a new robot with a random name.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generate a new random robot name.",
"name": "generate_name",
"signature": "def generate_name(self)"
},
{
"docstring": "Reset robot's nam... | 3 | stack_v2_sparse_classes_30k_train_000879 | Implement the Python class `Robot` described below.
Class description:
A robot with a unique random name.
Method signatures and docstrings:
- def __init__(self): Create (and boot up) a new robot with a random name.
- def generate_name(self): Generate a new random robot name.
- def reset(self): Reset robot's name. | Implement the Python class `Robot` described below.
Class description:
A robot with a unique random name.
Method signatures and docstrings:
- def __init__(self): Create (and boot up) a new robot with a random name.
- def generate_name(self): Generate a new random robot name.
- def reset(self): Reset robot's name.
<|... | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | <|skeleton|>
class Robot:
"""A robot with a unique random name."""
def __init__(self):
"""Create (and boot up) a new robot with a random name."""
<|body_0|>
def generate_name(self):
"""Generate a new random robot name."""
<|body_1|>
def reset(self):
"""Reset ro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Robot:
"""A robot with a unique random name."""
def __init__(self):
"""Create (and boot up) a new robot with a random name."""
self.existing_robots.append(self)
self.name = None
self.reset()
def generate_name(self):
"""Generate a new random robot name."""
... | the_stack_v2_python_sparse | all_data/exercism_data/python/robot-name/480850c388f94bfab36a461b16d658f3.py | itsolutionscorp/AutoStyle-Clustering | train | 4 |
9e64d080cd55242b09139f47866002d0f7223ca2 | [
"super(AbsoluteThreshold, self).__init__(self.__class__.__name__, time_series, baseline_time_series)\nself.absolute_threshold_value_upper = absolute_threshold_value_upper\nself.absolute_threshold_value_lower = absolute_threshold_value_lower\nif not self.absolute_threshold_value_lower and (not self.absolute_threshol... | <|body_start_0|>
super(AbsoluteThreshold, self).__init__(self.__class__.__name__, time_series, baseline_time_series)
self.absolute_threshold_value_upper = absolute_threshold_value_upper
self.absolute_threshold_value_lower = absolute_threshold_value_lower
if not self.absolute_threshold_va... | Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series. | AbsoluteThreshold | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbsoluteThreshold:
"""Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series."""
def __init__(self, time_series, absolute_threshold_value_upper=None, absolute_threshold_value_lower=None, baseline_time_series=None):
... | stack_v2_sparse_classes_10k_train_008871 | 2,914 | permissive | [
{
"docstring": "Initialize algorithm, check all required args are present :param time_series: The current time series dict to run anomaly detection on :param absolute_threshold_value_upper: Time series values above this are considered anomalies :param absolute_threshold_value_lower: Time series values below thi... | 2 | stack_v2_sparse_classes_30k_train_005666 | Implement the Python class `AbsoluteThreshold` described below.
Class description:
Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series.
Method signatures and docstrings:
- def __init__(self, time_series, absolute_threshold_value_upper=None,... | Implement the Python class `AbsoluteThreshold` described below.
Class description:
Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series.
Method signatures and docstrings:
- def __init__(self, time_series, absolute_threshold_value_upper=None,... | b0dc7df586394578d29389d306223523dc99c827 | <|skeleton|>
class AbsoluteThreshold:
"""Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series."""
def __init__(self, time_series, absolute_threshold_value_upper=None, absolute_threshold_value_lower=None, baseline_time_series=None):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AbsoluteThreshold:
"""Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series."""
def __init__(self, time_series, absolute_threshold_value_upper=None, absolute_threshold_value_lower=None, baseline_time_series=None):
"""Init... | the_stack_v2_python_sparse | src/luminol/algorithms/anomaly_detector_algorithms/absolute_threshold.py | linkedin/luminol | train | 1,159 |
d3150354202d91857be31e8470106116151dd44e | [
"self.time_value = time_value\nif ok_button_label is None:\n ok_button_label = 'Edit'\nself.ok_button_label = ok_button_label\nself.validating_function = validating_function",
"if time_value is not None:\n self.time_value = time_value\nself.w_value.SetData(str(self.time_value.value))\nself.w_utc_datetime.Se... | <|body_start_0|>
self.time_value = time_value
if ok_button_label is None:
ok_button_label = 'Edit'
self.ok_button_label = ok_button_label
self.validating_function = validating_function
<|end_body_0|>
<|body_start_1|>
if time_value is not None:
self.time_v... | A class representing a dialog for editing a time value. | TimeValueEditDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeValueEditDialog:
"""A class representing a dialog for editing a time value."""
def __init__(self, time_value, ok_button_label=None, validating_function=None):
"""Initialize the instance."""
<|body_0|>
def load_time_value(self, time_value=None):
"""Load the pr... | stack_v2_sparse_classes_10k_train_008872 | 9,476 | no_license | [
{
"docstring": "Initialize the instance.",
"name": "__init__",
"signature": "def __init__(self, time_value, ok_button_label=None, validating_function=None)"
},
{
"docstring": "Load the provided time value.",
"name": "load_time_value",
"signature": "def load_time_value(self, time_value=No... | 6 | null | Implement the Python class `TimeValueEditDialog` described below.
Class description:
A class representing a dialog for editing a time value.
Method signatures and docstrings:
- def __init__(self, time_value, ok_button_label=None, validating_function=None): Initialize the instance.
- def load_time_value(self, time_val... | Implement the Python class `TimeValueEditDialog` described below.
Class description:
A class representing a dialog for editing a time value.
Method signatures and docstrings:
- def __init__(self, time_value, ok_button_label=None, validating_function=None): Initialize the instance.
- def load_time_value(self, time_val... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class TimeValueEditDialog:
"""A class representing a dialog for editing a time value."""
def __init__(self, time_value, ok_button_label=None, validating_function=None):
"""Initialize the instance."""
<|body_0|>
def load_time_value(self, time_value=None):
"""Load the pr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TimeValueEditDialog:
"""A class representing a dialog for editing a time value."""
def __init__(self, time_value, ok_button_label=None, validating_function=None):
"""Initialize the instance."""
self.time_value = time_value
if ok_button_label is None:
ok_button_label = ... | the_stack_v2_python_sparse | Python modules/pb_gui_core.py | webclinic017/fa-absa-py3 | train | 0 |
8e3676fdcd721a02654ab67ebf08f3e04acdd363 | [
"global console\nconsole = init_console()\ncommand, options = self.parse_options(argv)\nold_argv = sys.argv\nsys.argv = argv\ntry:\n return command.run(options)\nexcept Exception as e:\n logger.exception('Unexpected exception when running command \"%s\": %s', command.name, e)\n return 1\nfinally:\n sys.... | <|body_start_0|>
global console
console = init_console()
command, options = self.parse_options(argv)
old_argv = sys.argv
sys.argv = argv
try:
return command.run(options)
except Exception as e:
logger.exception('Unexpected exception when run... | Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite. | RBExt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBExt:
"""Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite."""
def run(self, argv):
"""Run an rbext command with the provided arguments. Dur... | stack_v2_sparse_classes_10k_train_008873 | 36,982 | permissive | [
{
"docstring": "Run an rbext command with the provided arguments. During the duration of the run, :py:data:`sys.argv` will be set to the provided arguments. Args: argv (list of unicode): The command line arguments passed to the command. This should not include the executable name as the first element. Returns: ... | 2 | stack_v2_sparse_classes_30k_train_001284 | Implement the Python class `RBExt` described below.
Class description:
Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite.
Method signatures and docstrings:
- def run(self, arg... | Implement the Python class `RBExt` described below.
Class description:
Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite.
Method signatures and docstrings:
- def run(self, arg... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class RBExt:
"""Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite."""
def run(self, argv):
"""Run an rbext command with the provided arguments. Dur... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RBExt:
"""Command line tool for helping develop Review Board extensions. This tool provides subcommands useful for extension developers. It currently provides: * ``test``: Runs an extension's test suite."""
def run(self, argv):
"""Run an rbext command with the provided arguments. During the durat... | the_stack_v2_python_sparse | reviewboard/cmdline/rbext.py | reviewboard/reviewboard | train | 1,141 |
e7c93a36e6cc5fbe90c6faaa7f64a7a79d8469cc | [
"self.protocol = self.dstype[datasourcetype]\nself.kwargs = kwargs\nmodule_ = importlib.import_module('contextmonkey.tracelayer.handlers.%s.%sRequestHandlerFactory' % (self.protocol.lower(), self.protocol))\nclass_ = getattr(module_, '%sRequestHandlerFactory' % self.protocol)\nself.datasourcehandlerconnection = cla... | <|body_start_0|>
self.protocol = self.dstype[datasourcetype]
self.kwargs = kwargs
module_ = importlib.import_module('contextmonkey.tracelayer.handlers.%s.%sRequestHandlerFactory' % (self.protocol.lower(), self.protocol))
class_ = getattr(module_, '%sRequestHandlerFactory' % self.protocol... | Provide methods to fetch traces from file, model, and database. | DataSourceHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSourceHandler:
"""Provide methods to fetch traces from file, model, and database."""
def __init__(self, datasourcetype, **kwargs):
"""Initialize appropriate source handler factory."""
<|body_0|>
def executeFetch(self, uuid, modality):
"""Forward trace fetch r... | stack_v2_sparse_classes_10k_train_008874 | 4,232 | no_license | [
{
"docstring": "Initialize appropriate source handler factory.",
"name": "__init__",
"signature": "def __init__(self, datasourcetype, **kwargs)"
},
{
"docstring": "Forward trace fetch request to appropriate source handler factory.",
"name": "executeFetch",
"signature": "def executeFetch(... | 2 | stack_v2_sparse_classes_30k_train_002292 | Implement the Python class `DataSourceHandler` described below.
Class description:
Provide methods to fetch traces from file, model, and database.
Method signatures and docstrings:
- def __init__(self, datasourcetype, **kwargs): Initialize appropriate source handler factory.
- def executeFetch(self, uuid, modality): ... | Implement the Python class `DataSourceHandler` described below.
Class description:
Provide methods to fetch traces from file, model, and database.
Method signatures and docstrings:
- def __init__(self, datasourcetype, **kwargs): Initialize appropriate source handler factory.
- def executeFetch(self, uuid, modality): ... | 9974889a726d7f60c6da0d6ccab97113ce635a14 | <|skeleton|>
class DataSourceHandler:
"""Provide methods to fetch traces from file, model, and database."""
def __init__(self, datasourcetype, **kwargs):
"""Initialize appropriate source handler factory."""
<|body_0|>
def executeFetch(self, uuid, modality):
"""Forward trace fetch r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataSourceHandler:
"""Provide methods to fetch traces from file, model, and database."""
def __init__(self, datasourcetype, **kwargs):
"""Initialize appropriate source handler factory."""
self.protocol = self.dstype[datasourcetype]
self.kwargs = kwargs
module_ = importlib.... | the_stack_v2_python_sparse | contextmonkey/tracelayer/handlers/DataSourceHandler.py | manojrege/contextmonkey | train | 6 |
20b95b78af0aef7699c4365042db1c054ebb09c9 | [
"background = Background(color, image, elements, mode=mode, finish=False)\nbackground.finish()\nreturn background",
"super(Background, self).__init__('', elements, normal_params, finish=False)\nW, H = functions.get_screen_size()\nif image:\n painter = ImageFrame(image, mode=mode)\nelif color:\n painter = Ba... | <|body_start_0|>
background = Background(color, image, elements, mode=mode, finish=False)
background.finish()
return background
<|end_body_0|>
<|body_start_1|>
super(Background, self).__init__('', elements, normal_params, finish=False)
W, H = functions.get_screen_size()
... | Background element for another element or menu. | Background | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Background:
"""Background element for another element or menu."""
def make(color=None, image=None, elements=None, mode='scale to screen'):
"""Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the im... | stack_v2_sparse_classes_10k_train_008875 | 2,483 | permissive | [
{
"docstring": "Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the image of the background. <Mode>: None : if an image is passed, its original size is kept. Otherwise, a <color> (white by default) rect of the size of the sc... | 2 | stack_v2_sparse_classes_30k_train_006288 | Implement the Python class `Background` described below.
Class description:
Background element for another element or menu.
Method signatures and docstrings:
- def make(color=None, image=None, elements=None, mode='scale to screen'): Background element for another element or menu. <color>: if not None, define the colo... | Implement the Python class `Background` described below.
Class description:
Background element for another element or menu.
Method signatures and docstrings:
- def make(color=None, image=None, elements=None, mode='scale to screen'): Background element for another element or menu. <color>: if not None, define the colo... | e9dc52ff209f684be578f57a324f5bcf29d536ad | <|skeleton|>
class Background:
"""Background element for another element or menu."""
def make(color=None, image=None, elements=None, mode='scale to screen'):
"""Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the im... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Background:
"""Background element for another element or menu."""
def make(color=None, image=None, elements=None, mode='scale to screen'):
"""Background element for another element or menu. <color>: if not None, define the color for the background. <image>: if not None, define the image of the ba... | the_stack_v2_python_sparse | elements/background.py | YannThorimbert/Thorpy | train | 32 |
b5fccf2bd2997aa01ff98409b3da657ba559e7da | [
"super().__init__()\nself.heads = heads\nself.mlp_query = nn.ModuleList([nn.Linear(query_dim, att_dim, bias=False) for _ in range(heads)])\nself.mlp_key = nn.ModuleList([nn.Linear(key_dim, att_dim, bias=False) for _ in range(heads)])",
"cs, es = ([], [])\nfor h in range(self.heads):\n q = query.unsqueeze(1)\n ... | <|body_start_0|>
super().__init__()
self.heads = heads
self.mlp_query = nn.ModuleList([nn.Linear(query_dim, att_dim, bias=False) for _ in range(heads)])
self.mlp_key = nn.ModuleList([nn.Linear(key_dim, att_dim, bias=False) for _ in range(heads)])
<|end_body_0|>
<|body_start_1|>
... | MultiHeadDotAttn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadDotAttn:
def __init__(self, query_dim, key_dim, att_dim, heads):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, key_len=None, scaling=1.0):
""":para... | stack_v2_sparse_classes_10k_train_008876 | 10,910 | no_license | [
{
"docstring": "basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim",
"name": "__init__",
"signature": "def __init__(self, query_dim, key_dim, att_dim, heads)"
},
{
"docstring": ":param query: previous hidden state of the decoder, in shape (batch... | 2 | stack_v2_sparse_classes_30k_train_005435 | Implement the Python class `MultiHeadDotAttn` described below.
Class description:
Implement the MultiHeadDotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim, heads): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- de... | Implement the Python class `MultiHeadDotAttn` described below.
Class description:
Implement the MultiHeadDotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim, heads): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- de... | d354b06afbd8ae8172314af524f4f6cdeded363c | <|skeleton|>
class MultiHeadDotAttn:
def __init__(self, query_dim, key_dim, att_dim, heads):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, key_len=None, scaling=1.0):
""":para... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiHeadDotAttn:
def __init__(self, query_dim, key_dim, att_dim, heads):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
super().__init__()
self.heads = heads
self.mlp_query = nn.ModuleList([nn.Linear(query_dim, att_d... | the_stack_v2_python_sparse | style_word_alignment/self-attn-mask/model.py | ihungalexhsu/Text-style-tranfer | train | 1 | |
6fed6ccadd4f760eb1943f9f67e2976817678c36 | [
"if len(graph_dict) == 1:\n graph = list(graph_dict.values())[0]\n self._normal_node_map = graph.normal_node_map\n self._node_id_map_name = graph.node_id_map_name\n self._const_node_temp_cache = graph.const_node_temp_cache\n self._parameter_node_temp_cache = graph.parameter_node_temp_cache\n self.... | <|body_start_0|>
if len(graph_dict) == 1:
graph = list(graph_dict.values())[0]
self._normal_node_map = graph.normal_node_map
self._node_id_map_name = graph.node_id_map_name
self._const_node_temp_cache = graph.const_node_temp_cache
self._parameter_node_... | The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph. | DebuggerMultiGraph | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebuggerMultiGraph:
"""The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph."""
def add_graph(self, graph_dict):
"""Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict."""
<|body_0|>
def _add_gra... | stack_v2_sparse_classes_10k_train_008877 | 4,342 | permissive | [
{
"docstring": "Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict.",
"name": "add_graph",
"signature": "def add_graph(self, graph_dict)"
},
{
"docstring": "Add graph scope to the inputs and outputs in node",
"name": "_add_graph_scope",
"signat... | 2 | null | Implement the Python class `DebuggerMultiGraph` described below.
Class description:
The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph.
Method signatures and docstrings:
- def add_graph(self, graph_dict): Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, gr... | Implement the Python class `DebuggerMultiGraph` described below.
Class description:
The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph.
Method signatures and docstrings:
- def add_graph(self, graph_dict): Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, gr... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class DebuggerMultiGraph:
"""The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph."""
def add_graph(self, graph_dict):
"""Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict."""
<|body_0|>
def _add_gra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DebuggerMultiGraph:
"""The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph."""
def add_graph(self, graph_dict):
"""Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict."""
if len(graph_dict) == 1:
grap... | the_stack_v2_python_sparse | mindinsight/debugger/stream_cache/debugger_multigraph.py | mindspore-ai/mindinsight | train | 224 |
d59b7a5f85c6a06f0deaf1343ac2b35a3fdd1997 | [
"self.num_units = num_units\nself.kernel_size = kernel_size\nself.dilation_rate = dilation_rate",
"with tf.variable_scope(scope or type(self).__name__):\n input_dim = int(inputs.get_shape()[2])\n stddev = 1 / input_dim ** 0.5\n w = tf.get_variable('filter', [self.kernel_size, input_dim, self.num_units], ... | <|body_start_0|>
self.num_units = num_units
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope(scope or type(self).__name__):
input_dim = int(inputs.get_shape()[2])
stddev = 1 / input_dim ** 0.... | a 1-D atrous convolutional layer | AConv1dLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
<|body_0|>
def __call__(self,... | stack_v2_sparse_classes_10k_train_008878 | 11,183 | permissive | [
{
"docstring": "constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation",
"name": "__init__",
"signature": "def __init__(self, num_units, kernel_size, dilation_rate)"
},
{
"docstring": "Create the variables and do the forward co... | 2 | stack_v2_sparse_classes_30k_train_006375 | Implement the Python class `AConv1dLayer` described below.
Class description:
a 1-D atrous convolutional layer
Method signatures and docstrings:
- def __init__(self, num_units, kernel_size, dilation_rate): constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate ... | Implement the Python class `AConv1dLayer` described below.
Class description:
a 1-D atrous convolutional layer
Method signatures and docstrings:
- def __init__(self, num_units, kernel_size, dilation_rate): constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate ... | fb530cf617ff86fe8a249d4582dfe90a303da295 | <|skeleton|>
class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
<|body_0|>
def __call__(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
self.num_units = num_units
self.kernel_... | the_stack_v2_python_sparse | nabu/neuralnetworks/classifiers/layer.py | DavidKarlas/nabu | train | 1 |
5dbcada26174abe15d3fab2e2fa678c1c8888d83 | [
"super().__init__(*args, **kwargs)\nself.unit = unit\nself.data_type = data_type",
"if not isinstance(value, self.data_type):\n try:\n value = self.data_type(value)\n except ValueError:\n self.report(value, context)\n return\nif isinstance(value, Decimal):\n value = round_decimal(val... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.unit = unit
self.data_type = data_type
<|end_body_0|>
<|body_start_1|>
if not isinstance(value, self.data_type):
try:
value = self.data_type(value)
except ValueError:
self.rep... | Quantity is a property with unit. | Quantity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quantity:
"""Quantity is a property with unit."""
def __init__(self, *args: str, unit, data_type=int, **kwargs):
"""Init method."""
<|body_0|>
def handle(self, value, context):
"""Handle value with unit."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_008879 | 4,580 | permissive | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, *args: str, unit, data_type=int, **kwargs)"
},
{
"docstring": "Handle value with unit.",
"name": "handle",
"signature": "def handle(self, value, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003939 | Implement the Python class `Quantity` described below.
Class description:
Quantity is a property with unit.
Method signatures and docstrings:
- def __init__(self, *args: str, unit, data_type=int, **kwargs): Init method.
- def handle(self, value, context): Handle value with unit. | Implement the Python class `Quantity` described below.
Class description:
Quantity is a property with unit.
Method signatures and docstrings:
- def __init__(self, *args: str, unit, data_type=int, **kwargs): Init method.
- def handle(self, value, context): Handle value with unit.
<|skeleton|>
class Quantity:
"""Q... | 00909d2c47d158bfeac300e1d7477c4f87c52096 | <|skeleton|>
class Quantity:
"""Quantity is a property with unit."""
def __init__(self, *args: str, unit, data_type=int, **kwargs):
"""Init method."""
<|body_0|>
def handle(self, value, context):
"""Handle value with unit."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Quantity:
"""Quantity is a property with unit."""
def __init__(self, *args: str, unit, data_type=int, **kwargs):
"""Init method."""
super().__init__(*args, **kwargs)
self.unit = unit
self.data_type = data_type
def handle(self, value, context):
"""Handle value ... | the_stack_v2_python_sparse | knowit/properties/general.py | ratoaq2/knowit | train | 27 |
c0f79d0ebf6e8415ac50441946a9c08eb9bd4d77 | [
"carry = 0\nres = ListNode(0)\npre = res\nwhile l1 or l2 or carry:\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n carry, val = divmod(carry, 10)\n pre.next = ListNode(val)\n pre = pre.next\nreturn res.next",
"m, n = ('', '')\nwhile ... | <|body_start_0|>
carry = 0
res = ListNode(0)
pre = res
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
carry, val = divmod(carry, 10)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
""":param l1:ListNode :param l2: ListNode :return: ListNode"""
<|body_0|>
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
""":param l1:ListNode :param l2: ListNode :return: L... | stack_v2_sparse_classes_10k_train_008880 | 3,699 | no_license | [
{
"docstring": ":param l1:ListNode :param l2: ListNode :return: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": ":param l1:ListNode :param l2: ListNode :return: ListNode",
"name": "addTwoNumbers1",
"sign... | 2 | stack_v2_sparse_classes_30k_train_002661 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: :param l1:ListNode :param l2: ListNode :return: ListNode
- def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: :param l1:ListNode :param l2: ListNode :return: ListNode
- def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -... | f32cd4dc9670e55ffa6abe04c9184bfa5d8bbc41 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
""":param l1:ListNode :param l2: ListNode :return: ListNode"""
<|body_0|>
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
""":param l1:ListNode :param l2: ListNode :return: L... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
""":param l1:ListNode :param l2: ListNode :return: ListNode"""
carry = 0
res = ListNode(0)
pre = res
while l1 or l2 or carry:
if l1:
carry += l1.val
l1... | the_stack_v2_python_sparse | leecode/0710/两数相加.py | songdanlee/python_code_basic | train | 0 | |
c5a3ac9f940a7fc2dc669884477d9636fd3ef5d7 | [
"print('\\r\\n')\npath = os.path.dirname(os.path.realpath(__file__))\nself.run_check(path)",
"print('\\r\\n')\npath = os.path.dirname(os.path.realpath(__file__))\npath += '/../pygccxml/'\nself.run_check(path)",
"print('\\r\\n')\npath = os.path.dirname(os.path.realpath(__file__))\npath += '/../docs/examples/'\nf... | <|body_start_0|>
print('\r\n')
path = os.path.dirname(os.path.realpath(__file__))
self.run_check(path)
<|end_body_0|>
<|body_start_1|>
print('\r\n')
path = os.path.dirname(os.path.realpath(__file__))
path += '/../pygccxml/'
self.run_check(path)
<|end_body_1|>
<|... | Test | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_pep8_conformance_unitests(self):
"""Pep8 conformance test (unitests) Runs on the unittest directory."""
<|body_0|>
def test_pep8_conformance_pygccxml(self):
"""Pep8 conformance test (pygccxml) Runs on the pygccxml directory."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_008881 | 2,428 | permissive | [
{
"docstring": "Pep8 conformance test (unitests) Runs on the unittest directory.",
"name": "test_pep8_conformance_unitests",
"signature": "def test_pep8_conformance_unitests(self)"
},
{
"docstring": "Pep8 conformance test (pygccxml) Runs on the pygccxml directory.",
"name": "test_pep8_confor... | 5 | stack_v2_sparse_classes_30k_train_004903 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_pep8_conformance_unitests(self): Pep8 conformance test (unitests) Runs on the unittest directory.
- def test_pep8_conformance_pygccxml(self): Pep8 conformance test (pygccxml) Ru... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_pep8_conformance_unitests(self): Pep8 conformance test (unitests) Runs on the unittest directory.
- def test_pep8_conformance_pygccxml(self): Pep8 conformance test (pygccxml) Ru... | f872d056f477ed2438cd22b422d60dc924469805 | <|skeleton|>
class Test:
def test_pep8_conformance_unitests(self):
"""Pep8 conformance test (unitests) Runs on the unittest directory."""
<|body_0|>
def test_pep8_conformance_pygccxml(self):
"""Pep8 conformance test (pygccxml) Runs on the pygccxml directory."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test:
def test_pep8_conformance_unitests(self):
"""Pep8 conformance test (unitests) Runs on the unittest directory."""
print('\r\n')
path = os.path.dirname(os.path.realpath(__file__))
self.run_check(path)
def test_pep8_conformance_pygccxml(self):
"""Pep8 conformanc... | the_stack_v2_python_sparse | unittests/pep8_tester.py | iMichka/pygccxml | train | 0 | |
5f149ca45fd6be17ab8a68c8f981ecd76e593a9c | [
"try:\n error = response.json()['error']\n self._message = error['message']\n self.code = error['code']\n self.type = error['type']\nexcept:\n self._message = response.reason\n self.code = response.status_code\n self.type = PINN_ERROR_CODE_MAP[response.status_code]\nsuper(PinnError, self).__ini... | <|body_start_0|>
try:
error = response.json()['error']
self._message = error['message']
self.code = error['code']
self.type = error['type']
except:
self._message = response.reason
self.code = response.status_code
self.ty... | Base exception class for a Pinn API Error. | PinnError | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PinnError:
"""Base exception class for a Pinn API Error."""
def __init__(self, response):
"""Create a PinnError object with a response dictionary object."""
<|body_0|>
def from_response(response):
"""Create an error of the right PinnError subclass from an API res... | stack_v2_sparse_classes_10k_train_008882 | 4,553 | permissive | [
{
"docstring": "Create a PinnError object with a response dictionary object.",
"name": "__init__",
"signature": "def __init__(self, response)"
},
{
"docstring": "Create an error of the right PinnError subclass from an API response.",
"name": "from_response",
"signature": "def from_respon... | 2 | stack_v2_sparse_classes_30k_train_001260 | Implement the Python class `PinnError` described below.
Class description:
Base exception class for a Pinn API Error.
Method signatures and docstrings:
- def __init__(self, response): Create a PinnError object with a response dictionary object.
- def from_response(response): Create an error of the right PinnError sub... | Implement the Python class `PinnError` described below.
Class description:
Base exception class for a Pinn API Error.
Method signatures and docstrings:
- def __init__(self, response): Create a PinnError object with a response dictionary object.
- def from_response(response): Create an error of the right PinnError sub... | d7d3f2d2a4cdc3eb01ae85a117c0e3d8bc1732bd | <|skeleton|>
class PinnError:
"""Base exception class for a Pinn API Error."""
def __init__(self, response):
"""Create a PinnError object with a response dictionary object."""
<|body_0|>
def from_response(response):
"""Create an error of the right PinnError subclass from an API res... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PinnError:
"""Base exception class for a Pinn API Error."""
def __init__(self, response):
"""Create a PinnError object with a response dictionary object."""
try:
error = response.json()['error']
self._message = error['message']
self.code = error['code']... | the_stack_v2_python_sparse | pinn/errors.py | pinntech/pinn-python | train | 2 |
9da83533feb426dad7194cc78eb79869d4248ff3 | [
"roc_reading = {'confidenceThreshold': threshold, 'recall': tpr, 'falsePositiveRate': fpr}\nif 'confidenceMetrics' not in self.metadata.keys():\n self.metadata['confidenceMetrics'] = []\nself.metadata['confidenceMetrics'].append(roc_reading)",
"if len(fpr) != len(tpr) or len(fpr) != len(threshold) or len(tpr) ... | <|body_start_0|>
roc_reading = {'confidenceThreshold': threshold, 'recall': tpr, 'falsePositiveRate': fpr}
if 'confidenceMetrics' not in self.metadata.keys():
self.metadata['confidenceMetrics'] = []
self.metadata['confidenceMetrics'].append(roc_reading)
<|end_body_0|>
<|body_start_1... | An artifact for storing classification metrics. Args: name: Name of the metrics artifact. uri: The metrics artifact's location on disk or cloud storage. metadata: The key-value scalar metrics. | ClassificationMetrics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationMetrics:
"""An artifact for storing classification metrics. Args: name: Name of the metrics artifact. uri: The metrics artifact's location on disk or cloud storage. metadata: The key-value scalar metrics."""
def log_roc_data_point(self, fpr: float, tpr: float, threshold: float)... | stack_v2_sparse_classes_10k_train_008883 | 17,073 | permissive | [
{
"docstring": "Logs a single data point in the ROC curve to metadata. Args: fpr: False positive rate value of the data point. tpr: True positive rate value of the data point. threshold: Threshold value for the data point.",
"name": "log_roc_data_point",
"signature": "def log_roc_data_point(self, fpr: f... | 6 | stack_v2_sparse_classes_30k_train_006525 | Implement the Python class `ClassificationMetrics` described below.
Class description:
An artifact for storing classification metrics. Args: name: Name of the metrics artifact. uri: The metrics artifact's location on disk or cloud storage. metadata: The key-value scalar metrics.
Method signatures and docstrings:
- de... | Implement the Python class `ClassificationMetrics` described below.
Class description:
An artifact for storing classification metrics. Args: name: Name of the metrics artifact. uri: The metrics artifact's location on disk or cloud storage. metadata: The key-value scalar metrics.
Method signatures and docstrings:
- de... | 3fb199658f68e7debf4906d9ce32a9a307e39243 | <|skeleton|>
class ClassificationMetrics:
"""An artifact for storing classification metrics. Args: name: Name of the metrics artifact. uri: The metrics artifact's location on disk or cloud storage. metadata: The key-value scalar metrics."""
def log_roc_data_point(self, fpr: float, tpr: float, threshold: float)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClassificationMetrics:
"""An artifact for storing classification metrics. Args: name: Name of the metrics artifact. uri: The metrics artifact's location on disk or cloud storage. metadata: The key-value scalar metrics."""
def log_roc_data_point(self, fpr: float, tpr: float, threshold: float) -> None:
... | the_stack_v2_python_sparse | sdk/python/kfp/dsl/types/artifact_types.py | kubeflow/pipelines | train | 3,434 |
468dd4cb11c17d3ef96177b58fca869d529f9b33 | [
"self.graph = graph\nself.bound = set()\nself.known_namespaces = {'adms': namespace.Namespace('http://www.w3.org/ns/adms#'), 'aiiso': namespace.Namespace('http://purl.org/vocab/aiiso/schema#'), 'cc': namespace.Namespace('http://creativecommons.org/ns#'), 'dc': namespace.DCTERMS, 'dcat': namespace.Namespace('http://... | <|body_start_0|>
self.graph = graph
self.bound = set()
self.known_namespaces = {'adms': namespace.Namespace('http://www.w3.org/ns/adms#'), 'aiiso': namespace.Namespace('http://purl.org/vocab/aiiso/schema#'), 'cc': namespace.Namespace('http://creativecommons.org/ns#'), 'dc': namespace.DCTERMS, 'd... | Class representing the namespaces available to an RDF graph. | Namespaces | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Namespaces:
"""Class representing the namespaces available to an RDF graph."""
def __init__(self, graph):
""":param graph: the graph object to bind the used namespaces to"""
<|body_0|>
def __getattr__(self, prefix):
"""Returns the namespace associated with the gi... | stack_v2_sparse_classes_10k_train_008884 | 3,814 | permissive | [
{
"docstring": ":param graph: the graph object to bind the used namespaces to",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Returns the namespace associated with the given prefix and ensures it is bound to the graph if it hasn't been already. :param prefix: th... | 2 | stack_v2_sparse_classes_30k_train_002362 | Implement the Python class `Namespaces` described below.
Class description:
Class representing the namespaces available to an RDF graph.
Method signatures and docstrings:
- def __init__(self, graph): :param graph: the graph object to bind the used namespaces to
- def __getattr__(self, prefix): Returns the namespace a... | Implement the Python class `Namespaces` described below.
Class description:
Class representing the namespaces available to an RDF graph.
Method signatures and docstrings:
- def __init__(self, graph): :param graph: the graph object to bind the used namespaces to
- def __getattr__(self, prefix): Returns the namespace a... | 8b01a0294a809fde491094cb6928b57fee90a9a6 | <|skeleton|>
class Namespaces:
"""Class representing the namespaces available to an RDF graph."""
def __init__(self, graph):
""":param graph: the graph object to bind the used namespaces to"""
<|body_0|>
def __getattr__(self, prefix):
"""Returns the namespace associated with the gi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Namespaces:
"""Class representing the namespaces available to an RDF graph."""
def __init__(self, graph):
""":param graph: the graph object to bind the used namespaces to"""
self.graph = graph
self.bound = set()
self.known_namespaces = {'adms': namespace.Namespace('http://... | the_stack_v2_python_sparse | ckanext/nhm/dcat/utils.py | pribadihcr/ckanext-nhm | train | 0 |
a073e42b383eaf294bcc173e0d30578a1bb5333e | [
"envi.Opcode.__init__(self, va, opcode, mnem, prefixes, size, operands, iflags)\nif prefixes & PREFIX_VEX and (not opcode & INS_VEXNOPREF):\n mnem = 'v' + mnem\nself.mnem = mnem",
"pfx = self.getPrefixName()\nif pfx:\n pfx = '%s: ' % pfx\nreturn pfx + self.mnem + ' ' + ','.join([o.repr(self) for o in self.o... | <|body_start_0|>
envi.Opcode.__init__(self, va, opcode, mnem, prefixes, size, operands, iflags)
if prefixes & PREFIX_VEX and (not opcode & INS_VEXNOPREF):
mnem = 'v' + mnem
self.mnem = mnem
<|end_body_0|>
<|body_start_1|>
pfx = self.getPrefixName()
if pfx:
... | Amd64Opcode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Amd64Opcode:
def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0):
"""Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well"""
<... | stack_v2_sparse_classes_10k_train_008885 | 30,851 | permissive | [
{
"docstring": "Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well",
"name": "__init__",
"signature": "def __init__(self, va, opcode, mnem, prefixes, size, operands, ifl... | 3 | null | Implement the Python class `Amd64Opcode` described below.
Class description:
Implement the Amd64Opcode class.
Method signatures and docstrings:
- def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0): Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically th... | Implement the Python class `Amd64Opcode` described below.
Class description:
Implement the Amd64Opcode class.
Method signatures and docstrings:
- def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0): Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically th... | b07e161cc28b19fdda0d047eefafed22c5b00f15 | <|skeleton|>
class Amd64Opcode:
def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0):
"""Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well"""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Amd64Opcode:
def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0):
"""Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well"""
envi.Opcode.__i... | the_stack_v2_python_sparse | envi/archs/amd64/disasm.py | vivisect/vivisect | train | 833 | |
2998d58e1a5f110965aba3124aa8df76b8f73e24 | [
"manager = TeamChannelManager(context)\npayload = {'teamChannelUrl': channel_url, 'privateChannel': private_channel, 'privateChannelGroupOwner': private_channel_group_owner}\nreturn_type = TeamChannel(context)\nqry = ServiceOperationQuery(manager, 'AddTeamChannel', None, payload, None, return_type)\nqry.static = Tr... | <|body_start_0|>
manager = TeamChannelManager(context)
payload = {'teamChannelUrl': channel_url, 'privateChannel': private_channel, 'privateChannelGroupOwner': private_channel_group_owner}
return_type = TeamChannel(context)
qry = ServiceOperationQuery(manager, 'AddTeamChannel', None, pay... | This class is a placeholder for all TeamChannel related methods. | TeamChannelManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamChannelManager:
"""This class is a placeholder for all TeamChannel related methods."""
def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None):
"""Create Team Channel based folder with specific prodID. :param office365.sharepoint.client... | stack_v2_sparse_classes_10k_train_008886 | 3,071 | permissive | [
{
"docstring": "Create Team Channel based folder with specific prodID. :param office365.sharepoint.client_context.ClientContext context: SharePoint client context :param str channel_url: Team channel URL to be stored in the folder metadata. :param bool private_channel: :param str private_channel_group_owner:",
... | 4 | null | Implement the Python class `TeamChannelManager` described below.
Class description:
This class is a placeholder for all TeamChannel related methods.
Method signatures and docstrings:
- def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None): Create Team Channel based folder... | Implement the Python class `TeamChannelManager` described below.
Class description:
This class is a placeholder for all TeamChannel related methods.
Method signatures and docstrings:
- def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None): Create Team Channel based folder... | cbd245d1af8d69e013c469cfc2a9851f51c91417 | <|skeleton|>
class TeamChannelManager:
"""This class is a placeholder for all TeamChannel related methods."""
def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None):
"""Create Team Channel based folder with specific prodID. :param office365.sharepoint.client... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeamChannelManager:
"""This class is a placeholder for all TeamChannel related methods."""
def add_team_channel(context, channel_url, private_channel=False, private_channel_group_owner=None):
"""Create Team Channel based folder with specific prodID. :param office365.sharepoint.client_context.Clie... | the_stack_v2_python_sparse | office365/sharepoint/teams/channel_manager.py | vgrem/Office365-REST-Python-Client | train | 1,006 |
49f2864cb44f4ef69e6fcd9d945904d5e219b72e | [
"super(StreamPowerThresholdModel, self).__init__(input_file=input_file, params=params)\nself.flow_router = FlowRouter(self.grid, **self.params)\nself.lake_filler = DepressionFinderAndRouter(self.grid, **self.params)\nself.eroder = StreamPowerSmoothThresholdEroder(self.grid, K_sp=self.params['K_sp'], threshold_sp=se... | <|body_start_0|>
super(StreamPowerThresholdModel, self).__init__(input_file=input_file, params=params)
self.flow_router = FlowRouter(self.grid, **self.params)
self.lake_filler = DepressionFinderAndRouter(self.grid, **self.params)
self.eroder = StreamPowerSmoothThresholdEroder(self.grid, ... | A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term. | StreamPowerThresholdModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamPowerThresholdModel:
"""A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term."""
def __init__(self, input_file=None, params=None):
"""Initialize the StreamPowerThresholdModel."""
<... | stack_v2_sparse_classes_10k_train_008887 | 2,839 | no_license | [
{
"docstring": "Initialize the StreamPowerThresholdModel.",
"name": "__init__",
"signature": "def __init__(self, input_file=None, params=None)"
},
{
"docstring": "Advance model for one time-step of duration dt.",
"name": "run_one_step",
"signature": "def run_one_step(self, dt)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005152 | Implement the Python class `StreamPowerThresholdModel` described below.
Class description:
A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None... | Implement the Python class `StreamPowerThresholdModel` described below.
Class description:
A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=None... | 3506ec741a7c8a170ea654d40c6119fefe1b93ba | <|skeleton|>
class StreamPowerThresholdModel:
"""A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term."""
def __init__(self, input_file=None, params=None):
"""Initialize the StreamPowerThresholdModel."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StreamPowerThresholdModel:
"""A StreamPowerThresholdModel computes erosion using a form of the unit stream power model that represents a threshold using an exponential term."""
def __init__(self, input_file=None, params=None):
"""Initialize the StreamPowerThresholdModel."""
super(StreamPo... | the_stack_v2_python_sparse | erosion_modeling_suite/erosion_model/single_component/stream_power_threshold/stream_power_threshold_model.py | kbarnhart/inverting_topography_postglacial | train | 4 |
8a2c625dc5abf745fd4f36636544e1834c8c2ff8 | [
"create_listener_flow = linear_flow.Flow(constants.CREATE_LISTENER_FLOW)\ncreate_listener_flow.add(lifecycle_tasks.ListenersToErrorOnRevertTask(requires=constants.LISTENERS))\ncreate_listener_flow.add(amphora_driver_tasks.ListenersUpdate(requires=constants.LOADBALANCER_ID))\ncreate_listener_flow.add(network_tasks.U... | <|body_start_0|>
create_listener_flow = linear_flow.Flow(constants.CREATE_LISTENER_FLOW)
create_listener_flow.add(lifecycle_tasks.ListenersToErrorOnRevertTask(requires=constants.LISTENERS))
create_listener_flow.add(amphora_driver_tasks.ListenersUpdate(requires=constants.LOADBALANCER_ID))
... | ListenerFlows | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListenerFlows:
def get_create_listener_flow(self):
"""Create a flow to create a listener :returns: The flow for creating a listener"""
<|body_0|>
def get_create_all_listeners_flow(self):
"""Create a flow to create all listeners :returns: The flow for creating all lis... | stack_v2_sparse_classes_10k_train_008888 | 5,910 | permissive | [
{
"docstring": "Create a flow to create a listener :returns: The flow for creating a listener",
"name": "get_create_listener_flow",
"signature": "def get_create_listener_flow(self)"
},
{
"docstring": "Create a flow to create all listeners :returns: The flow for creating all listeners",
"name... | 5 | null | Implement the Python class `ListenerFlows` described below.
Class description:
Implement the ListenerFlows class.
Method signatures and docstrings:
- def get_create_listener_flow(self): Create a flow to create a listener :returns: The flow for creating a listener
- def get_create_all_listeners_flow(self): Create a fl... | Implement the Python class `ListenerFlows` described below.
Class description:
Implement the ListenerFlows class.
Method signatures and docstrings:
- def get_create_listener_flow(self): Create a flow to create a listener :returns: The flow for creating a listener
- def get_create_all_listeners_flow(self): Create a fl... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class ListenerFlows:
def get_create_listener_flow(self):
"""Create a flow to create a listener :returns: The flow for creating a listener"""
<|body_0|>
def get_create_all_listeners_flow(self):
"""Create a flow to create all listeners :returns: The flow for creating all lis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListenerFlows:
def get_create_listener_flow(self):
"""Create a flow to create a listener :returns: The flow for creating a listener"""
create_listener_flow = linear_flow.Flow(constants.CREATE_LISTENER_FLOW)
create_listener_flow.add(lifecycle_tasks.ListenersToErrorOnRevertTask(requires=... | the_stack_v2_python_sparse | octavia/controller/worker/v2/flows/listener_flows.py | openstack/octavia | train | 147 | |
b18cb7257fdbe56ffa350f031633452a4354cc28 | [
"headers = self._get_default_headers()\ntry:\n if self.request_validator.client_authentication_required(request):\n log.debug('Authenticating client, %r.', request)\n if not self.request_validator.authenticate_client(request):\n log.debug('Client authentication failed, %r.', request)\n ... | <|body_start_0|>
headers = self._get_default_headers()
try:
if self.request_validator.client_authentication_required(request):
log.debug('Authenticating client, %r.', request)
if not self.request_validator.authenticate_client(request):
log.... | `Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authorization server should take special care when enabling ... | ResourceOwnerPasswordCredentialsGrant | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceOwnerPasswordCredentialsGrant:
"""`Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application.... | stack_v2_sparse_classes_10k_train_008889 | 8,484 | permissive | [
{
"docstring": "Return token or error in json format. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the access token request is valid and authorized, the authorization server issues an ... | 2 | stack_v2_sparse_classes_30k_train_000539 | Implement the Python class `ResourceOwnerPasswordCredentialsGrant` described below.
Class description:
`Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating sys... | Implement the Python class `ResourceOwnerPasswordCredentialsGrant` described below.
Class description:
`Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating sys... | 00f9a212004a80df790ed071a59af53a05f5e3f2 | <|skeleton|>
class ResourceOwnerPasswordCredentialsGrant:
"""`Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResourceOwnerPasswordCredentialsGrant:
"""`Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authoriz... | the_stack_v2_python_sparse | oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py | oauthlib/oauthlib | train | 1,223 |
c39e7c23ffbc1d32f298acc4ef7cb458527f0dac | [
"super().__init__()\nimport sklearn\nimport sklearn.svm\nself.model = sklearn.svm.LinearSVR",
"specs = super(LinearSVR, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{LinearSVR} \\\\textit{Linear Support Vector Regressor} is\\n similar to SVR with parameter kernel=’l... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.LinearSVR
<|end_body_0|>
<|body_start_1|>
specs = super(LinearSVR, cls).getInputSpecification()
specs.description = 'The \\xmlNode{LinearSVR} \\textit{Linear Support Vector Reg... | Linear Support Vector Regressor | LinearSVR | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearSVR:
"""Linear Support Vector Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that s... | stack_v2_sparse_classes_10k_train_008890 | 6,358 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | stack_v2_sparse_classes_30k_train_004593 | Implement the Python class `LinearSVR` described below.
Class description:
Linear Support Vector Regressor
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refere... | Implement the Python class `LinearSVR` described below.
Class description:
Linear Support Vector Regressor
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refere... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class LinearSVR:
"""Linear Support Vector Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearSVR:
"""Linear Support Vector Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.LinearSVR
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/SVM/LinearSVR.py | idaholab/raven | train | 201 |
adeadef0a9995f28fbac2dc8a8e3efa9a3075c97 | [
"state = self.device.states.get(self.entity_description.key)\nif not state or not state.value:\n return None\nif self.entity_description.native_value:\n return self.entity_description.native_value(state.value)\nif isinstance(state.value, (dict, list)):\n return None\nreturn state.value",
"if not (default... | <|body_start_0|>
state = self.device.states.get(self.entity_description.key)
if not state or not state.value:
return None
if self.entity_description.native_value:
return self.entity_description.native_value(state.value)
if isinstance(state.value, (dict, list)):
... | Representation of an Overkiz Sensor. | OverkizStateSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OverkizStateSensor:
"""Representation of an Overkiz Sensor."""
def native_value(self) -> StateType:
"""Return the value of the sensor."""
<|body_0|>
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k_train_008891 | 20,039 | permissive | [
{
"docstring": "Return the value of the sensor.",
"name": "native_value",
"signature": "def native_value(self) -> StateType"
},
{
"docstring": "Return the unit of measurement.",
"name": "native_unit_of_measurement",
"signature": "def native_unit_of_measurement(self) -> str | None"
}
] | 2 | stack_v2_sparse_classes_30k_train_001218 | Implement the Python class `OverkizStateSensor` described below.
Class description:
Representation of an Overkiz Sensor.
Method signatures and docstrings:
- def native_value(self) -> StateType: Return the value of the sensor.
- def native_unit_of_measurement(self) -> str | None: Return the unit of measurement. | Implement the Python class `OverkizStateSensor` described below.
Class description:
Representation of an Overkiz Sensor.
Method signatures and docstrings:
- def native_value(self) -> StateType: Return the value of the sensor.
- def native_unit_of_measurement(self) -> str | None: Return the unit of measurement.
<|ske... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OverkizStateSensor:
"""Representation of an Overkiz Sensor."""
def native_value(self) -> StateType:
"""Return the value of the sensor."""
<|body_0|>
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OverkizStateSensor:
"""Representation of an Overkiz Sensor."""
def native_value(self) -> StateType:
"""Return the value of the sensor."""
state = self.device.states.get(self.entity_description.key)
if not state or not state.value:
return None
if self.entity_des... | the_stack_v2_python_sparse | homeassistant/components/overkiz/sensor.py | home-assistant/core | train | 35,501 |
c5752e3d5dfc16b9d5edfa37d5ac298327c9b94d | [
"check_path_cmd = NginxUtil.get_cmd_options(path=nginx_ins_path)\nexec_cmd_no_error(node, check_path_cmd, timeout=180, message=u'Check NGINX install path failed!')\ncommand = f'rm -rf {nginx_ins_path}'\nmessage = u'Cleanup the NGINX failed!'\nexec_cmd_no_error(node, command, timeout=180, message=message)",
"for n... | <|body_start_0|>
check_path_cmd = NginxUtil.get_cmd_options(path=nginx_ins_path)
exec_cmd_no_error(node, check_path_cmd, timeout=180, message=u'Check NGINX install path failed!')
command = f'rm -rf {nginx_ins_path}'
message = u'Cleanup the NGINX failed!'
exec_cmd_no_error(node, c... | This class implements: - Initialization of NGINX environment, - Cleanup of NGINX environment. | NGINXTools | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NGINXTools:
"""This class implements: - Initialization of NGINX environment, - Cleanup of NGINX environment."""
def cleanup_nginx_framework(node, nginx_ins_path):
"""Cleanup the NGINX framework on the DUT node. :param node: Will cleanup the nginx on this nodes. :param nginx_ins_path:... | stack_v2_sparse_classes_10k_train_008892 | 5,290 | permissive | [
{
"docstring": "Cleanup the NGINX framework on the DUT node. :param node: Will cleanup the nginx on this nodes. :param nginx_ins_path: NGINX install path. :type node: dict :type nginx_ins_path: str :raises RuntimeError: If it fails to cleanup the nginx.",
"name": "cleanup_nginx_framework",
"signature": ... | 5 | stack_v2_sparse_classes_30k_train_000762 | Implement the Python class `NGINXTools` described below.
Class description:
This class implements: - Initialization of NGINX environment, - Cleanup of NGINX environment.
Method signatures and docstrings:
- def cleanup_nginx_framework(node, nginx_ins_path): Cleanup the NGINX framework on the DUT node. :param node: Wil... | Implement the Python class `NGINXTools` described below.
Class description:
This class implements: - Initialization of NGINX environment, - Cleanup of NGINX environment.
Method signatures and docstrings:
- def cleanup_nginx_framework(node, nginx_ins_path): Cleanup the NGINX framework on the DUT node. :param node: Wil... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class NGINXTools:
"""This class implements: - Initialization of NGINX environment, - Cleanup of NGINX environment."""
def cleanup_nginx_framework(node, nginx_ins_path):
"""Cleanup the NGINX framework on the DUT node. :param node: Will cleanup the nginx on this nodes. :param nginx_ins_path:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NGINXTools:
"""This class implements: - Initialization of NGINX environment, - Cleanup of NGINX environment."""
def cleanup_nginx_framework(node, nginx_ins_path):
"""Cleanup the NGINX framework on the DUT node. :param node: Will cleanup the nginx on this nodes. :param nginx_ins_path: NGINX instal... | the_stack_v2_python_sparse | resources/libraries/python/NGINX/NGINXTools.py | FDio/csit | train | 28 |
b524d88baff6bdcc47fa3486a383a688a967b9fa | [
"try:\n from bokeh.plotting import Figure\nexcept (ModuleNotFoundError, ImportError) as Error:\n raise Error(\"Using 'BokehArtifact' requires bokeh package. Use pip install mlrun[bokeh] to install it.\")\nif figure is not None and (not isinstance(figure, Figure)):\n raise ValueError(\"BokehArtifact require... | <|body_start_0|>
try:
from bokeh.plotting import Figure
except (ModuleNotFoundError, ImportError) as Error:
raise Error("Using 'BokehArtifact' requires bokeh package. Use pip install mlrun[bokeh] to install it.")
if figure is not None and (not isinstance(figure, Figure)):... | Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format. | LegacyBokehArtifact | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegacyBokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ... | stack_v2_sparse_classes_10k_train_008893 | 15,717 | permissive | [
{
"docstring": "Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('bokeh.plotting.Figure' object) to save as an artifact. :param key: Key for the artifact to be stored in the database. :param target_path: Path to save the artifact.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_004441 | Implement the Python class `LegacyBokehArtifact` described below.
Class description:
Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format.
Method signatures and docstrings:
- def __init__(self, figure=None, key: str=None, target_path: str=None): Initialize a Bokeh art... | Implement the Python class `LegacyBokehArtifact` described below.
Class description:
Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format.
Method signatures and docstrings:
- def __init__(self, figure=None, key: str=None, target_path: str=None): Initialize a Bokeh art... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class LegacyBokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LegacyBokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('bokeh.plott... | the_stack_v2_python_sparse | mlrun/artifacts/plots.py | mlrun/mlrun | train | 1,093 |
cfe4cee5340b7546440229e7ed73c951a6d96ee5 | [
"false_token = '12345'\nself.info('Will use token %s', false_token)\nclient = ComputeClient(self.clients.compute_url, false_token)\nclient.CONNECTION_RETRY_LIMIT = self.clients.retry\nwith self.assertRaises(ClientError) as cl_error:\n client.list_servers()\n self.assertEqual(cl_error.exception.status, 401)",
... | <|body_start_0|>
false_token = '12345'
self.info('Will use token %s', false_token)
client = ComputeClient(self.clients.compute_url, false_token)
client.CONNECTION_RETRY_LIMIT = self.clients.retry
with self.assertRaises(ClientError) as cl_error:
client.list_servers()
... | Test Astakos functionality | AstakosTestSuite | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AstakosTestSuite:
"""Test Astakos functionality"""
def test_001_unauthorized_access(self):
"""Test that access without a valid token fails"""
<|body_0|>
def test_002_name2uuid(self):
"""Test that usernames2uuids and uuids2usernames are complementary"""
<|... | stack_v2_sparse_classes_10k_train_008894 | 2,931 | permissive | [
{
"docstring": "Test that access without a valid token fails",
"name": "test_001_unauthorized_access",
"signature": "def test_001_unauthorized_access(self)"
},
{
"docstring": "Test that usernames2uuids and uuids2usernames are complementary",
"name": "test_002_name2uuid",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_test_000006 | Implement the Python class `AstakosTestSuite` described below.
Class description:
Test Astakos functionality
Method signatures and docstrings:
- def test_001_unauthorized_access(self): Test that access without a valid token fails
- def test_002_name2uuid(self): Test that usernames2uuids and uuids2usernames are comple... | Implement the Python class `AstakosTestSuite` described below.
Class description:
Test Astakos functionality
Method signatures and docstrings:
- def test_001_unauthorized_access(self): Test that access without a valid token fails
- def test_002_name2uuid(self): Test that usernames2uuids and uuids2usernames are comple... | d4fffe4942e9e3c5ac7f41af0f5643dd0645023e | <|skeleton|>
class AstakosTestSuite:
"""Test Astakos functionality"""
def test_001_unauthorized_access(self):
"""Test that access without a valid token fails"""
<|body_0|>
def test_002_name2uuid(self):
"""Test that usernames2uuids and uuids2usernames are complementary"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AstakosTestSuite:
"""Test Astakos functionality"""
def test_001_unauthorized_access(self):
"""Test that access without a valid token fails"""
false_token = '12345'
self.info('Will use token %s', false_token)
client = ComputeClient(self.clients.compute_url, false_token)
... | the_stack_v2_python_sparse | snf-tools/synnefo_tools/burnin/astakos_tests.py | philipgian/synnefo | train | 0 |
6d15daf53afe24495ec139b3ba62be1abbe7fd14 | [
"self.nums = nums\n\ndef create_linetree(left, right):\n if left == right:\n node = LineTree([left, right])\n node.sumrange = nums[left]\n return node\n else:\n mid = (left + right) // 2\n curnode = LineTree([left, right])\n curnode.left = create_linetree(left, mid)\n... | <|body_start_0|>
self.nums = nums
def create_linetree(left, right):
if left == right:
node = LineTree([left, right])
node.sumrange = nums[left]
return node
else:
mid = (left + right) // 2
curnode = L... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k_train_008895 | 2,286 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_003463 | 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 update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 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 update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | d1a08ddeb06423bb23e8c22c88b3fde048e86b46 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
def create_linetree(left, right):
if left == right:
node = LineTree([left, right])
node.sumrange = nums[left]
return node
else:
... | the_stack_v2_python_sparse | test70.py | xfx1993/goto1000 | train | 0 | |
8d8c10531fad5f016f77fbd84fee07e3127c644b | [
"params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}\nparams.update(kwargs)\nreturn self.api._get('emails/get_or_create', params=params)",
"params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}\nparams.update(kwargs)\nreturn self.api._get('emails/disable', params=params)"
] | <|body_start_0|>
params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}
params.update(kwargs)
return self.api._get('emails/get_or_create', params=params)
<|end_body_0|>
<|body_start_1|>
params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}
params... | EmailsManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailsManager:
def get_or_create(self, obj_type, obj_id, **kwargs):
"""Get or create email to an object."""
<|body_0|>
def disable(self, obj_type, obj_id, **kwargs):
"""Disable email to an object."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
para... | stack_v2_sparse_classes_10k_train_008896 | 668 | permissive | [
{
"docstring": "Get or create email to an object.",
"name": "get_or_create",
"signature": "def get_or_create(self, obj_type, obj_id, **kwargs)"
},
{
"docstring": "Disable email to an object.",
"name": "disable",
"signature": "def disable(self, obj_type, obj_id, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003764 | Implement the Python class `EmailsManager` described below.
Class description:
Implement the EmailsManager class.
Method signatures and docstrings:
- def get_or_create(self, obj_type, obj_id, **kwargs): Get or create email to an object.
- def disable(self, obj_type, obj_id, **kwargs): Disable email to an object. | Implement the Python class `EmailsManager` described below.
Class description:
Implement the EmailsManager class.
Method signatures and docstrings:
- def get_or_create(self, obj_type, obj_id, **kwargs): Get or create email to an object.
- def disable(self, obj_type, obj_id, **kwargs): Disable email to an object.
<|s... | 7b85de81619146d3d54fececda068010ae73775b | <|skeleton|>
class EmailsManager:
def get_or_create(self, obj_type, obj_id, **kwargs):
"""Get or create email to an object."""
<|body_0|>
def disable(self, obj_type, obj_id, **kwargs):
"""Disable email to an object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmailsManager:
def get_or_create(self, obj_type, obj_id, **kwargs):
"""Get or create email to an object."""
params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}
params.update(kwargs)
return self.api._get('emails/get_or_create', params=params)
def disable(... | the_stack_v2_python_sparse | todoist/managers/emails.py | Doist/todoist-python | train | 627 | |
e1ddcf8193c6ef040285c378805513b83cd3464c | [
"stock_prices_first_order = np.array([[10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30], [10, 15, 30, 40, 50]], dtype=float)\nstock_prices_second_order = np.array([[10, 15, 30, 40, 50], [10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30]], dtype=float)\ntest_case_first_order = StockMarket(... | <|body_start_0|>
stock_prices_first_order = np.array([[10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30], [10, 15, 30, 40, 50]], dtype=float)
stock_prices_second_order = np.array([[10, 15, 30, 40, 50], [10, 15, 20, 15, 10], [5, 15, 10, 15, 20], [30, 25, 20, 25, 30]], dtype=float)
te... | TestStockMarket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStockMarket:
def test_four_stocks_two_optimal_paths(self):
"""This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50.... | stack_v2_sparse_classes_10k_train_008897 | 3,083 | no_license | [
{
"docstring": "This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50. :return: Succes if both stock orders lead to the maximum equity of 50 in ... | 3 | stack_v2_sparse_classes_30k_train_000697 | Implement the Python class `TestStockMarket` described below.
Class description:
Implement the TestStockMarket class.
Method signatures and docstrings:
- def test_four_stocks_two_optimal_paths(self): This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. Th... | Implement the Python class `TestStockMarket` described below.
Class description:
Implement the TestStockMarket class.
Method signatures and docstrings:
- def test_four_stocks_two_optimal_paths(self): This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. Th... | 98478976eac1fe3c3052d4deac1b382788d4e509 | <|skeleton|>
class TestStockMarket:
def test_four_stocks_two_optimal_paths(self):
"""This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestStockMarket:
def test_four_stocks_two_optimal_paths(self):
"""This unittest tests the 'dynamic_programming_bottom_up()' method by testing 4 stocks given in two different orders. There are two different paths in which different stocks can be bought to achieve the maximum equity of 50. :return: Succ... | the_stack_v2_python_sparse | Stockmarket/test_private.py | Macquine/Code-Portfolio | train | 0 | |
111064024e8fdf6df5e05a3001644f0f4bc6b798 | [
"super(MLP, self).__init__()\nself.regularizer = tf.contrib.layers.l2_regularizer(scale=wd)\nself.initializer = tf.contrib.layers.xavier_initializer()\nself.variance_initializer = tf.contrib.layers.variance_scaling_initializer(factor=0.1, mode='FAN_IN', uniform=False, seed=None, dtype=tf.dtypes.float32)\nself.drop_... | <|body_start_0|>
super(MLP, self).__init__()
self.regularizer = tf.contrib.layers.l2_regularizer(scale=wd)
self.initializer = tf.contrib.layers.xavier_initializer()
self.variance_initializer = tf.contrib.layers.variance_scaling_initializer(factor=0.1, mode='FAN_IN', uniform=False, seed=N... | Definition of MLP Networks. | MLP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
"""Definition of MLP Networks."""
def __init__(self, keep_prob, wd, feature_dim):
"""Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the r... | stack_v2_sparse_classes_10k_train_008898 | 3,214 | permissive | [
{
"docstring": "Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the representation space.",
"name": "__init__",
"signature": "def __init__(self, keep_prob, wd, fea... | 3 | null | Implement the Python class `MLP` described below.
Class description:
Definition of MLP Networks.
Method signatures and docstrings:
- def __init__(self, keep_prob, wd, feature_dim): Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-effic... | Implement the Python class `MLP` described below.
Class description:
Definition of MLP Networks.
Method signatures and docstrings:
- def __init__(self, keep_prob, wd, feature_dim): Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-effic... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class MLP:
"""Definition of MLP Networks."""
def __init__(self, keep_prob, wd, feature_dim):
"""Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MLP:
"""Definition of MLP Networks."""
def __init__(self, keep_prob, wd, feature_dim):
"""Creates a model for classifying an image using VGG networks. Args: keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the dimension of the representation... | the_stack_v2_python_sparse | dble/mlp.py | Tarkiyah/googleResearch | train | 11 |
387debdfcbfb6cbd032b5f4d00345a5d893ff4aa | [
"threading.Thread.__init__(self)\nself.threadName = name\nself.people = people",
"print('开始线程: ' + self.threadName)\nchiHuoGuo(self.people)\nprint('qq交流群:226296743')\nprint('结束线程: ' + self.name)"
] | <|body_start_0|>
threading.Thread.__init__(self)
self.threadName = name
self.people = people
<|end_body_0|>
<|body_start_1|>
print('开始线程: ' + self.threadName)
chiHuoGuo(self.people)
print('qq交流群:226296743')
print('结束线程: ' + self.name)
<|end_body_1|>
| myThread | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
<|body_0|>
def run(self):
"""重写run方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threading.Thread.__init__(self)
self.threadName = name
self.people = peopl... | stack_v2_sparse_classes_10k_train_008899 | 5,122 | permissive | [
{
"docstring": "重写threading.Thread初始化内容",
"name": "__init__",
"signature": "def __init__(self, people, name)"
},
{
"docstring": "重写run方法",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `myThread` described below.
Class description:
Implement the myThread class.
Method signatures and docstrings:
- def __init__(self, people, name): 重写threading.Thread初始化内容
- def run(self): 重写run方法 | Implement the Python class `myThread` described below.
Class description:
Implement the myThread class.
Method signatures and docstrings:
- def __init__(self, people, name): 重写threading.Thread初始化内容
- def run(self): 重写run方法
<|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thr... | e046cdd35bd63e9430416ea6954b1aaef4bc50d5 | <|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
<|body_0|>
def run(self):
"""重写run方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
threading.Thread.__init__(self)
self.threadName = name
self.people = people
def run(self):
"""重写run方法"""
print('开始线程: ' + self.threadName)
chiHuoGuo(self.people)
print... | the_stack_v2_python_sparse | 第一期/北京-菜鸟渣渣/Fast_Learning_python3/thread/thread_join&setDeamon.py | beidou9313/deeptest | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.