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 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
51df1fa6665a9c3500d50700c2df411f266a07d7 | [
"try:\n dbclient = None\n dbclient = MyDB('JIRA')\n version_filter = ''\n if version_id_list:\n version_filter = 'AND nodeassociation.SINK_NODE_ID in (%s)' % ','.join(version_id_list)\n if issue_type_id:\n issue_type_filter = ' AND issuetype.ID=%s ' % issue_type_id\n else:\n i... | <|body_start_0|>
try:
dbclient = None
dbclient = MyDB('JIRA')
version_filter = ''
if version_id_list:
version_filter = 'AND nodeassociation.SINK_NODE_ID in (%s)' % ','.join(version_id_list)
if issue_type_id:
issue_type_f... | JiraDefect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiraDefect:
def get_defects_by_version_ids(version_id_list, issue_type_id):
"""根据项目版本获取缺陷"""
<|body_0|>
def get_defect_custom_field_info(defect_id):
"""根据缺陷id获取缺陷自定义字段信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
dbclient = Non... | stack_v2_sparse_classes_75kplus_train_069900 | 5,498 | permissive | [
{
"docstring": "根据项目版本获取缺陷",
"name": "get_defects_by_version_ids",
"signature": "def get_defects_by_version_ids(version_id_list, issue_type_id)"
},
{
"docstring": "根据缺陷id获取缺陷自定义字段信息",
"name": "get_defect_custom_field_info",
"signature": "def get_defect_custom_field_info(defect_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027637 | Implement the Python class `JiraDefect` described below.
Class description:
Implement the JiraDefect class.
Method signatures and docstrings:
- def get_defects_by_version_ids(version_id_list, issue_type_id): 根据项目版本获取缺陷
- def get_defect_custom_field_info(defect_id): 根据缺陷id获取缺陷自定义字段信息 | Implement the Python class `JiraDefect` described below.
Class description:
Implement the JiraDefect class.
Method signatures and docstrings:
- def get_defects_by_version_ids(version_id_list, issue_type_id): 根据项目版本获取缺陷
- def get_defect_custom_field_info(defect_id): 根据缺陷id获取缺陷自定义字段信息
<|skeleton|>
class JiraDefect:
... | 6e073808297eab642ff00b5ea39b6b283ee13ad2 | <|skeleton|>
class JiraDefect:
def get_defects_by_version_ids(version_id_list, issue_type_id):
"""根据项目版本获取缺陷"""
<|body_0|>
def get_defect_custom_field_info(defect_id):
"""根据缺陷id获取缺陷自定义字段信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JiraDefect:
def get_defects_by_version_ids(version_id_list, issue_type_id):
"""根据项目版本获取缺陷"""
try:
dbclient = None
dbclient = MyDB('JIRA')
version_filter = ''
if version_id_list:
version_filter = 'AND nodeassociation.SINK_NODE_ID i... | the_stack_v2_python_sparse | backend/jira/defect.py | themycode/test-management-platform | train | 0 | |
6598a89e9ffcb6f7067200642c3ec1165fa0e2cc | [
"super().__init__()\nself.weight = weight\nself.wiki_page_dict = {}",
"if not os.path.isfile(wiki_dump):\n logger.warning(\"Wiki dump doesn't exit, download a new one\")\n urllib.request.urlretrieve(WIKI_DUMP_URL, wiki_dump)\nwith open(wiki_dump, 'r') as f:\n old_wiki_dict = json.load(f)\ndataset = QuizB... | <|body_start_0|>
super().__init__()
self.weight = weight
self.wiki_page_dict = {}
<|end_body_0|>
<|body_start_1|>
if not os.path.isfile(wiki_dump):
logger.warning("Wiki dump doesn't exit, download a new one")
urllib.request.urlretrieve(WIKI_DUMP_URL, wiki_dump)
... | The reranker uses wiki entities in that page to rescore the answers | FeatureReranker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureReranker:
"""The reranker uses wiki entities in that page to rescore the answers"""
def __init__(self, weight: int):
"""Args: weight: int, extra score if an anchor text in a wikipage is mentioned in the original question"""
<|body_0|>
def train(self, path: str, re... | stack_v2_sparse_classes_75kplus_train_069901 | 6,480 | permissive | [
{
"docstring": "Args: weight: int, extra score if an anchor text in a wikipage is mentioned in the original question",
"name": "__init__",
"signature": "def __init__(self, weight: int)"
},
{
"docstring": "download all the wikipage info in the training set Args: path: str, pkl model path retrieve... | 6 | stack_v2_sparse_classes_30k_train_021926 | Implement the Python class `FeatureReranker` described below.
Class description:
The reranker uses wiki entities in that page to rescore the answers
Method signatures and docstrings:
- def __init__(self, weight: int): Args: weight: int, extra score if an anchor text in a wikipage is mentioned in the original question... | Implement the Python class `FeatureReranker` described below.
Class description:
The reranker uses wiki entities in that page to rescore the answers
Method signatures and docstrings:
- def __init__(self, weight: int): Args: weight: int, extra score if an anchor text in a wikipage is mentioned in the original question... | 8ff2ff2b5311d01f89833ebcdff0dc8c2ece7654 | <|skeleton|>
class FeatureReranker:
"""The reranker uses wiki entities in that page to rescore the answers"""
def __init__(self, weight: int):
"""Args: weight: int, extra score if an anchor text in a wikipage is mentioned in the original question"""
<|body_0|>
def train(self, path: str, re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureReranker:
"""The reranker uses wiki entities in that page to rescore the answers"""
def __init__(self, weight: int):
"""Args: weight: int, extra score if an anchor text in a wikipage is mentioned in the original question"""
super().__init__()
self.weight = weight
se... | the_stack_v2_python_sparse | src/qanta/feature_reranker.py | zhr1201/QuizBowlChallenge | train | 1 |
b0288d915642e58ee4c56f2011056b7002ce162a | [
"exporter = tsert_export(filename)\nexporter.set_electrode_positions(self.electrode_positions)\nexporter.set_topography(self.topography)\nexporter.add_data(self.data, version, **kwargs)\nexporter.add_metadata(self.metadata)",
"logger.info('Exporting to pygimli DataContainer')\nlogger.info('{} data will be exporte... | <|body_start_0|>
exporter = tsert_export(filename)
exporter.set_electrode_positions(self.electrode_positions)
exporter.set_topography(self.topography)
exporter.add_data(self.data, version, **kwargs)
exporter.add_metadata(self.metadata)
<|end_body_0|>
<|body_start_1|>
log... | ERTExporters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ERTExporters:
def export_tsert(self, filename, version, **kwargs):
"""Export data to TSERT"""
<|body_0|>
def export_to_pygimli_scheme(self, norrec='nor', timestep=None):
"""Export the data into a pygimili.DataContainerERT object. For now, do NOT set any sensor positi... | stack_v2_sparse_classes_75kplus_train_069902 | 12,616 | permissive | [
{
"docstring": "Export data to TSERT",
"name": "export_tsert",
"signature": "def export_tsert(self, filename, version, **kwargs)"
},
{
"docstring": "Export the data into a pygimili.DataContainerERT object. For now, do NOT set any sensor positions Parameters ---------- Returns -------",
"name... | 2 | stack_v2_sparse_classes_30k_val_002931 | Implement the Python class `ERTExporters` described below.
Class description:
Implement the ERTExporters class.
Method signatures and docstrings:
- def export_tsert(self, filename, version, **kwargs): Export data to TSERT
- def export_to_pygimli_scheme(self, norrec='nor', timestep=None): Export the data into a pygimi... | Implement the Python class `ERTExporters` described below.
Class description:
Implement the ERTExporters class.
Method signatures and docstrings:
- def export_tsert(self, filename, version, **kwargs): Export data to TSERT
- def export_to_pygimli_scheme(self, norrec='nor', timestep=None): Export the data into a pygimi... | adecc344837c0bf53c5e005a97c2c231b6f9eac2 | <|skeleton|>
class ERTExporters:
def export_tsert(self, filename, version, **kwargs):
"""Export data to TSERT"""
<|body_0|>
def export_to_pygimli_scheme(self, norrec='nor', timestep=None):
"""Export the data into a pygimili.DataContainerERT object. For now, do NOT set any sensor positi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ERTExporters:
def export_tsert(self, filename, version, **kwargs):
"""Export data to TSERT"""
exporter = tsert_export(filename)
exporter.set_electrode_positions(self.electrode_positions)
exporter.set_topography(self.topography)
exporter.add_data(self.data, version, **kw... | the_stack_v2_python_sparse | lib/reda/containers/ERT.py | geophysics-ubonn/reda | train | 14 | |
0cf0b80f9605081cd12d77fd86260304c714246d | [
"sp = ' ' if opt_sp and self.name in COMPOUND else ''\nif self.elem_type is None:\n return CPP_TYPE[self.name] + sp\nreturn CPP_TYPE[self.name] % self.elem_type.cppType(opt_sp=True) + sp",
"type = self.cppType()\nif self.name in BY_CREF:\n type += ' const&'\nreturn type",
"cpp_type = self.cppType()\nif se... | <|body_start_0|>
sp = ' ' if opt_sp and self.name in COMPOUND else ''
if self.elem_type is None:
return CPP_TYPE[self.name] + sp
return CPP_TYPE[self.name] % self.elem_type.cppType(opt_sp=True) + sp
<|end_body_0|>
<|body_start_1|>
type = self.cppType()
if self.name i... | IDLType | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IDLType:
def cppType(self, opt_sp=False):
"""Gets the C++ type declaration of this IDL type. The opt_sp puts a trailing space after a closing angle bracket if the type itself ends with a closing angle bracket."""
<|body_0|>
def cppArgType(self):
"""Gets the C++ type ... | stack_v2_sparse_classes_75kplus_train_069903 | 15,282 | no_license | [
{
"docstring": "Gets the C++ type declaration of this IDL type. The opt_sp puts a trailing space after a closing angle bracket if the type itself ends with a closing angle bracket.",
"name": "cppType",
"signature": "def cppType(self, opt_sp=False)"
},
{
"docstring": "Gets the C++ type declaratio... | 4 | stack_v2_sparse_classes_30k_train_031188 | Implement the Python class `IDLType` described below.
Class description:
Implement the IDLType class.
Method signatures and docstrings:
- def cppType(self, opt_sp=False): Gets the C++ type declaration of this IDL type. The opt_sp puts a trailing space after a closing angle bracket if the type itself ends with a closi... | Implement the Python class `IDLType` described below.
Class description:
Implement the IDLType class.
Method signatures and docstrings:
- def cppType(self, opt_sp=False): Gets the C++ type declaration of this IDL type. The opt_sp puts a trailing space after a closing angle bracket if the type itself ends with a closi... | ad831300367843058ee7c01a82e745f026e1fcbf | <|skeleton|>
class IDLType:
def cppType(self, opt_sp=False):
"""Gets the C++ type declaration of this IDL type. The opt_sp puts a trailing space after a closing angle bracket if the type itself ends with a closing angle bracket."""
<|body_0|>
def cppArgType(self):
"""Gets the C++ type ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IDLType:
def cppType(self, opt_sp=False):
"""Gets the C++ type declaration of this IDL type. The opt_sp puts a trailing space after a closing angle bracket if the type itself ends with a closing angle bracket."""
sp = ' ' if opt_sp and self.name in COMPOUND else ''
if self.elem_type is... | the_stack_v2_python_sparse | python/idl_cpp_types.py | ogoodman/serf | train | 1 | |
ba00dde0d688d2c2b547de1ce246f2a61c7be356 | [
"try:\n payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')\n user = get_object_or_404(User, id=payload['id'])\nexcept (TypeError, ValueError, OverflowError, Exception):\n raise Http404\nuser.email_notification_subscription = False\nuser.save()\nresp = {'message': 'you have successfully ch... | <|body_start_0|>
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
user = get_object_or_404(User, id=payload['id'])
except (TypeError, ValueError, OverflowError, Exception):
raise Http404
user.email_notification_subscription = False
... | Allow users to unsubscribe from notifications | UnSubscribeAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnSubscribeAPIView:
"""Allow users to unsubscribe from notifications"""
def get(self, request, token):
"""unsubscribe from email notifications"""
<|body_0|>
def put(self, request):
"""unsubscribe from app notifications"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_069904 | 5,586 | permissive | [
{
"docstring": "unsubscribe from email notifications",
"name": "get",
"signature": "def get(self, request, token)"
},
{
"docstring": "unsubscribe from app notifications",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050222 | Implement the Python class `UnSubscribeAPIView` described below.
Class description:
Allow users to unsubscribe from notifications
Method signatures and docstrings:
- def get(self, request, token): unsubscribe from email notifications
- def put(self, request): unsubscribe from app notifications | Implement the Python class `UnSubscribeAPIView` described below.
Class description:
Allow users to unsubscribe from notifications
Method signatures and docstrings:
- def get(self, request, token): unsubscribe from email notifications
- def put(self, request): unsubscribe from app notifications
<|skeleton|>
class UnS... | e8438b78b88c52d108520429d0b67cd3d13e0824 | <|skeleton|>
class UnSubscribeAPIView:
"""Allow users to unsubscribe from notifications"""
def get(self, request, token):
"""unsubscribe from email notifications"""
<|body_0|>
def put(self, request):
"""unsubscribe from app notifications"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnSubscribeAPIView:
"""Allow users to unsubscribe from notifications"""
def get(self, request, token):
"""unsubscribe from email notifications"""
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
user = get_object_or_404(User, id=payload['id... | the_stack_v2_python_sparse | authors/apps/usernotifications/views.py | andela/ah-sealteam | train | 1 |
cda531a991cd09accc9ce899899ab21ee5683e93 | [
"if root == None:\n return ''\nstack = []\nstack.append([root, 0])\ns = ''\nwhile len(stack) > 0:\n node, level = stack[-1]\n if level == 0:\n stack[-1][1] += 1\n if node.left:\n stack.append([node.left, 0])\n elif level == 1:\n stack[-1][1] += 1\n if node.right:\n... | <|body_start_0|>
if root == None:
return ''
stack = []
stack.append([root, 0])
s = ''
while len(stack) > 0:
node, level = stack[-1]
if level == 0:
stack[-1][1] += 1
if node.left:
stack.append(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root == None:
retu... | stack_v2_sparse_classes_75kplus_train_069905 | 1,986 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode)"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054125 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode): Encodes a tree to a single string.
- def deserialize(self, data: str): Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode): Encodes a tree to a single string.
- def deserialize(self, data: str): Decodes your encoded data to tree.
<|skeleton|>
class Codec:
def seria... | aefc8006ccac4a4720dda1bd932a04fd1880ec9d | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode):
"""Encodes a tree to a single string."""
if root == None:
return ''
stack = []
stack.append([root, 0])
s = ''
while len(stack) > 0:
node, level = stack[-1]
if level == 0:
... | the_stack_v2_python_sparse | BST/serialize_deserialize_using_stack.py | viswan29/Leetcode | train | 0 | |
3882cd583ec9e0df7a4e3bb12bd88d5dc6e88a6c | [
"self.__base_url = base_url\nself.__access_key = access_key\nself.domain = domain",
"try:\n issue_types_url = '{}/metadata/issue-types'.format(self.__base_url)\n issue_types = make_rest_call(url=issue_types_url, secret_key=self.__access_key)\n json_issue_type = issue_types['entries']\nexcept Exception:\n... | <|body_start_0|>
self.__base_url = base_url
self.__access_key = access_key
self.domain = domain
<|end_body_0|>
<|body_start_1|>
try:
issue_types_url = '{}/metadata/issue-types'.format(self.__base_url)
issue_types = make_rest_call(url=issue_types_url, secret_key=s... | Represents a scorecard object. | ScoreCardHelperClass | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScoreCardHelperClass:
"""Represents a scorecard object."""
def __init__(self, base_url, access_key, domain=None):
"""__init__ method will initialize the object of scorecardhelper class."""
<|body_0|>
def get_issues(self, **config):
"""get_issues method will get t... | stack_v2_sparse_classes_75kplus_train_069906 | 4,215 | permissive | [
{
"docstring": "__init__ method will initialize the object of scorecardhelper class.",
"name": "__init__",
"signature": "def __init__(self, base_url, access_key, domain=None)"
},
{
"docstring": "get_issues method will get the issues data of a company.",
"name": "get_issues",
"signature":... | 5 | null | Implement the Python class `ScoreCardHelperClass` described below.
Class description:
Represents a scorecard object.
Method signatures and docstrings:
- def __init__(self, base_url, access_key, domain=None): __init__ method will initialize the object of scorecardhelper class.
- def get_issues(self, **config): get_iss... | Implement the Python class `ScoreCardHelperClass` described below.
Class description:
Represents a scorecard object.
Method signatures and docstrings:
- def __init__(self, base_url, access_key, domain=None): __init__ method will initialize the object of scorecardhelper class.
- def get_issues(self, **config): get_iss... | 4536a3f6b9bdef902312b3d96f9c2e66b8bf52c1 | <|skeleton|>
class ScoreCardHelperClass:
"""Represents a scorecard object."""
def __init__(self, base_url, access_key, domain=None):
"""__init__ method will initialize the object of scorecardhelper class."""
<|body_0|>
def get_issues(self, **config):
"""get_issues method will get t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScoreCardHelperClass:
"""Represents a scorecard object."""
def __init__(self, base_url, access_key, domain=None):
"""__init__ method will initialize the object of scorecardhelper class."""
self.__base_url = base_url
self.__access_key = access_key
self.domain = domain
... | the_stack_v2_python_sparse | Solutions/SecurityScorecard Cybersecurity Ratings/Data Connectors/SecurityScorecardIssue/SecurityScorecardIssueSentinelConnector/scorecard.py | Azure/Azure-Sentinel | train | 3,697 |
7716ee073940c81c419afe2f163e081402a256c9 | [
"if dungeon is None or len(dungeon) == 0:\n return 0\nm = len(dungeon)\nn = len(dungeon[0])\nhp = [[0 for j in range(n)] for i in range(m)]\nhp[m - 1][n - 1] = abs(dungeon[m - 1][n - 1]) + 1 if dungeon[m - 1][n - 1] < 0 else 1\nfor j in range(n - 2, -1, -1):\n need = hp[m - 1][j + 1] - dungeon[m - 1][j]\n ... | <|body_start_0|>
if dungeon is None or len(dungeon) == 0:
return 0
m = len(dungeon)
n = len(dungeon[0])
hp = [[0 for j in range(n)] for i in range(m)]
hp[m - 1][n - 1] = abs(dungeon[m - 1][n - 1]) + 1 if dungeon[m - 1][n - 1] < 0 else 1
for j in range(n - 2, -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_0|>
def calculateMinimumHP2(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if dun... | stack_v2_sparse_classes_75kplus_train_069907 | 2,309 | no_license | [
{
"docstring": ":type dungeon: List[List[int]] :rtype: int",
"name": "calculateMinimumHP",
"signature": "def calculateMinimumHP(self, dungeon)"
},
{
"docstring": ":type dungeon: List[List[int]] :rtype: int",
"name": "calculateMinimumHP2",
"signature": "def calculateMinimumHP2(self, dunge... | 2 | stack_v2_sparse_classes_30k_train_020204 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def calculateMinimumHP2(self, dungeon): :type dungeon: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def calculateMinimumHP2(self, dungeon): :type dungeon: List[List[int]] :rtype: int
<|skeleton... | 54d3d9530b25272d4a2e5dc33e7035c44f506dc5 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_0|>
def calculateMinimumHP2(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
if dungeon is None or len(dungeon) == 0:
return 0
m = len(dungeon)
n = len(dungeon[0])
hp = [[0 for j in range(n)] for i in range(m)]
hp[m - 1][n - 1] =... | the_stack_v2_python_sparse | old/DungeonGame.py | MaxIakovliev/algorithms | train | 0 | |
33503f923c891efbc5642917745ee32465f3430d | [
"vocab_size = 100\nsequence_length = 512\nd_model = 64\nd_latents = 48\nnum_layers = 2\nencoder_cfg = cfg.EncoderConfig(v_last_dim=d_latents, num_self_attends_per_block=num_layers)\nsequence_encoder_cfg = cfg.SequenceEncoderConfig(d_model=d_model, d_latents=d_latents, vocab_size=vocab_size, encoder=encoder_cfg)\nte... | <|body_start_0|>
vocab_size = 100
sequence_length = 512
d_model = 64
d_latents = 48
num_layers = 2
encoder_cfg = cfg.EncoderConfig(v_last_dim=d_latents, num_self_attends_per_block=num_layers)
sequence_encoder_cfg = cfg.SequenceEncoderConfig(d_model=d_model, d_late... | ClassifierTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierTest:
def test_perceiver_trainer(self, num_classes):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_head):
"""Validate that the Keras object can be invoked."""
<|b... | stack_v2_sparse_classes_75kplus_train_069908 | 8,478 | permissive | [
{
"docstring": "Validate that the Keras object can be created.",
"name": "test_perceiver_trainer",
"signature": "def test_perceiver_trainer(self, num_classes)"
},
{
"docstring": "Validate that the Keras object can be invoked.",
"name": "test_perceiver_trainer_tensor_call",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_019014 | Implement the Python class `ClassifierTest` described below.
Class description:
Implement the ClassifierTest class.
Method signatures and docstrings:
- def test_perceiver_trainer(self, num_classes): Validate that the Keras object can be created.
- def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_h... | Implement the Python class `ClassifierTest` described below.
Class description:
Implement the ClassifierTest class.
Method signatures and docstrings:
- def test_perceiver_trainer(self, num_classes): Validate that the Keras object can be created.
- def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_h... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class ClassifierTest:
def test_perceiver_trainer(self, num_classes):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_head):
"""Validate that the Keras object can be invoked."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassifierTest:
def test_perceiver_trainer(self, num_classes):
"""Validate that the Keras object can be created."""
vocab_size = 100
sequence_length = 512
d_model = 64
d_latents = 48
num_layers = 2
encoder_cfg = cfg.EncoderConfig(v_last_dim=d_latents, nu... | the_stack_v2_python_sparse | official/projects/perceiver/modeling/models/classifier_test.py | jianzhnie/models | train | 2 | |
60f20bb4d7b7964ceca30bd694f06e3681d15528 | [
"neighbors = {}\nencoder = _IntegerEncoder()\nn_entries = len(table)\nfor n, (sequence, value) in enumerate(table.items()):\n if n % 1000000 == 0 or (n < 1000000 and n % 100000 == 0):\n logging.info('loading ScaM results %r/%r', n, n_entries)\n neighbor_sequences = [neighbor.docid for neighbor in value... | <|body_start_0|>
neighbors = {}
encoder = _IntegerEncoder()
n_entries = len(table)
for n, (sequence, value) in enumerate(table.items()):
if n % 1000000 == 0 or (n < 1000000 and n % 100000 == 0):
logging.info('loading ScaM results %r/%r', n, n_entries)
... | Matcher that uses pre-computed lookup tables generated by ScaM. | ScaMMatcher | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaMMatcher:
"""Matcher that uses pre-computed lookup tables generated by ScaM."""
def __init__(self, table, dtype='u4'):
"""Initialize as ScaMMatcher. Args: table: Mapping[str, result_pb2.NearestNeighbor] mapping each sequence to all of its (approximate) neighbors within some fixed ... | stack_v2_sparse_classes_75kplus_train_069909 | 19,209 | permissive | [
{
"docstring": "Initialize as ScaMMatcher. Args: table: Mapping[str, result_pb2.NearestNeighbor] mapping each sequence to all of its (approximate) neighbors within some fixed edit distance. dtype: optional object convertable to numpy.dtype to use for storing positive integer IDs. Raises: ValueError: if dtype wa... | 3 | stack_v2_sparse_classes_30k_train_011062 | Implement the Python class `ScaMMatcher` described below.
Class description:
Matcher that uses pre-computed lookup tables generated by ScaM.
Method signatures and docstrings:
- def __init__(self, table, dtype='u4'): Initialize as ScaMMatcher. Args: table: Mapping[str, result_pb2.NearestNeighbor] mapping each sequence... | Implement the Python class `ScaMMatcher` described below.
Class description:
Matcher that uses pre-computed lookup tables generated by ScaM.
Method signatures and docstrings:
- def __init__(self, table, dtype='u4'): Initialize as ScaMMatcher. Args: table: Mapping[str, result_pb2.NearestNeighbor] mapping each sequence... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ScaMMatcher:
"""Matcher that uses pre-computed lookup tables generated by ScaM."""
def __init__(self, table, dtype='u4'):
"""Initialize as ScaMMatcher. Args: table: Mapping[str, result_pb2.NearestNeighbor] mapping each sequence to all of its (approximate) neighbors within some fixed ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScaMMatcher:
"""Matcher that uses pre-computed lookup tables generated by ScaM."""
def __init__(self, table, dtype='u4'):
"""Initialize as ScaMMatcher. Args: table: Mapping[str, result_pb2.NearestNeighbor] mapping each sequence to all of its (approximate) neighbors within some fixed edit distance... | the_stack_v2_python_sparse | aptamers_mlpd/preprocess/clustering.py | Jimmy-INL/google-research | train | 1 |
d3b5daa677faa8560d7471e25695676446ec9b57 | [
"super(ConvertVideoTask, self).__init__(*args, **kwargs)\nself.setOption('videoArgs', self.__defaultVideoArgs)\nself.setOption('audioArgs', self.__defaultAudioArgs)\nself.setOption('bitRate', self.__defaultBitRate)",
"videoArgs = self.option('videoArgs')\naudioArgs = self.option('audioArgs')\nbitRate = self.optio... | <|body_start_0|>
super(ConvertVideoTask, self).__init__(*args, **kwargs)
self.setOption('videoArgs', self.__defaultVideoArgs)
self.setOption('audioArgs', self.__defaultAudioArgs)
self.setOption('bitRate', self.__defaultBitRate)
<|end_body_0|>
<|body_start_1|>
videoArgs = self.op... | Convert a video using ffmpeg. | ConvertVideoTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertVideoTask:
"""Convert a video using ffmpeg."""
def __init__(self, *args, **kwargs):
"""Create a convert video object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ConvertVide... | stack_v2_sparse_classes_75kplus_train_069910 | 2,356 | permissive | [
{
"docstring": "Create a convert video object.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform the task.",
"name": "_perform",
"signature": "def _perform(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044937 | Implement the Python class `ConvertVideoTask` described below.
Class description:
Convert a video using ffmpeg.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a convert video object.
- def _perform(self): Perform the task. | Implement the Python class `ConvertVideoTask` described below.
Class description:
Convert a video using ffmpeg.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a convert video object.
- def _perform(self): Perform the task.
<|skeleton|>
class ConvertVideoTask:
"""Convert a video u... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class ConvertVideoTask:
"""Convert a video using ffmpeg."""
def __init__(self, *args, **kwargs):
"""Create a convert video object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvertVideoTask:
"""Convert a video using ffmpeg."""
def __init__(self, *args, **kwargs):
"""Create a convert video object."""
super(ConvertVideoTask, self).__init__(*args, **kwargs)
self.setOption('videoArgs', self.__defaultVideoArgs)
self.setOption('audioArgs', self.__d... | the_stack_v2_python_sparse | src/lib/kombi/Task/Video/ConvertVideoTask.py | kombiHQ/kombi | train | 2 |
ef45431218b3fcd4ef9e9d0ee9031555d10302cb | [
"self.file_path = file_path\nself.file_size = file_size\nself.file_type = file_type",
"if dictionary is None:\n return None\nfile_path = dictionary.get('filePath')\nfile_size = dictionary.get('fileSize')\nfile_type = dictionary.get('fileType')\nreturn cls(file_path, file_size, file_type)"
] | <|body_start_0|>
self.file_path = file_path
self.file_size = file_size
self.file_type = file_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
file_path = dictionary.get('filePath')
file_size = dictionary.get('fileSize')
file_typ... | Implementation of the 'SiteBackupFile' model. TODO: type description here. Attributes: file_path (string): Output file path on Windows proxy VM or on SMB share. This will be autogenerated when 'BackupSiteParam.data_dir_path' is empty. The file 'sitetemplate.pnp' in the directory contains the PnP site template. file_siz... | SiteBackupFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteBackupFile:
"""Implementation of the 'SiteBackupFile' model. TODO: type description here. Attributes: file_path (string): Output file path on Windows proxy VM or on SMB share. This will be autogenerated when 'BackupSiteParam.data_dir_path' is empty. The file 'sitetemplate.pnp' in the director... | stack_v2_sparse_classes_75kplus_train_069911 | 1,941 | permissive | [
{
"docstring": "Constructor for the SiteBackupFile class",
"name": "__init__",
"signature": "def __init__(self, file_path=None, file_size=None, file_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of th... | 2 | stack_v2_sparse_classes_30k_train_004337 | Implement the Python class `SiteBackupFile` described below.
Class description:
Implementation of the 'SiteBackupFile' model. TODO: type description here. Attributes: file_path (string): Output file path on Windows proxy VM or on SMB share. This will be autogenerated when 'BackupSiteParam.data_dir_path' is empty. The ... | Implement the Python class `SiteBackupFile` described below.
Class description:
Implementation of the 'SiteBackupFile' model. TODO: type description here. Attributes: file_path (string): Output file path on Windows proxy VM or on SMB share. This will be autogenerated when 'BackupSiteParam.data_dir_path' is empty. The ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SiteBackupFile:
"""Implementation of the 'SiteBackupFile' model. TODO: type description here. Attributes: file_path (string): Output file path on Windows proxy VM or on SMB share. This will be autogenerated when 'BackupSiteParam.data_dir_path' is empty. The file 'sitetemplate.pnp' in the director... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SiteBackupFile:
"""Implementation of the 'SiteBackupFile' model. TODO: type description here. Attributes: file_path (string): Output file path on Windows proxy VM or on SMB share. This will be autogenerated when 'BackupSiteParam.data_dir_path' is empty. The file 'sitetemplate.pnp' in the directory contains th... | the_stack_v2_python_sparse | cohesity_management_sdk/models/site_backup_file.py | cohesity/management-sdk-python | train | 24 |
52ab09b9e258452d4d8f188d72ff96b7b09d1d5a | [
"snapshot = RdsClusterSnapshot if engine.startswith('aurora') else RdsInstanceSnapshot\nargs = {snapshot.snapshot_id_field: snapshot_id, 'AttributeName': 'restore', 'ValuesToRemove': ['all']}\ngetattr(rds_client, snapshot.modify_attribute_method)(**args)",
"snapshot = RdsClusterSnapshot if engine.startswith('auro... | <|body_start_0|>
snapshot = RdsClusterSnapshot if engine.startswith('aurora') else RdsInstanceSnapshot
args = {snapshot.snapshot_id_field: snapshot_id, 'AttributeName': 'restore', 'ValuesToRemove': ['all']}
getattr(rds_client, snapshot.modify_attribute_method)(**args)
<|end_body_0|>
<|body_star... | RdsSnapshotOperations | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RdsSnapshotOperations:
def make_private(rds_client, engine, snapshot_id):
"""Change RDS snapshot to be private. :param rds_client: RDS boto3 client :param engine: The name of the database engine to modify snapshot attribute for (aurora, aurora-*, mariadb, mysql, ...) :param snapshot_id: ... | stack_v2_sparse_classes_75kplus_train_069912 | 16,587 | permissive | [
{
"docstring": "Change RDS snapshot to be private. :param rds_client: RDS boto3 client :param engine: The name of the database engine to modify snapshot attribute for (aurora, aurora-*, mariadb, mysql, ...) :param snapshot_id: The identifier for the DB snapshot to make private :return: nothing",
"name": "ma... | 2 | null | Implement the Python class `RdsSnapshotOperations` described below.
Class description:
Implement the RdsSnapshotOperations class.
Method signatures and docstrings:
- def make_private(rds_client, engine, snapshot_id): Change RDS snapshot to be private. :param rds_client: RDS boto3 client :param engine: The name of the... | Implement the Python class `RdsSnapshotOperations` described below.
Class description:
Implement the RdsSnapshotOperations class.
Method signatures and docstrings:
- def make_private(rds_client, engine, snapshot_id): Change RDS snapshot to be private. :param rds_client: RDS boto3 client :param engine: The name of the... | fd2b29754fd3d297aa0af6fa5f9f337196f04e6d | <|skeleton|>
class RdsSnapshotOperations:
def make_private(rds_client, engine, snapshot_id):
"""Change RDS snapshot to be private. :param rds_client: RDS boto3 client :param engine: The name of the database engine to modify snapshot attribute for (aurora, aurora-*, mariadb, mysql, ...) :param snapshot_id: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RdsSnapshotOperations:
def make_private(rds_client, engine, snapshot_id):
"""Change RDS snapshot to be private. :param rds_client: RDS boto3 client :param engine: The name of the database engine to modify snapshot attribute for (aurora, aurora-*, mariadb, mysql, ...) :param snapshot_id: The identifier... | the_stack_v2_python_sparse | hammer/library/aws/rds.py | kurmiashish/hammer | train | 0 | |
80b2c664bf95039f3f1c8abb460ba7dc04c81b88 | [
"self.normalize = normalize\nself.image_normalize = ops.CropMirrorNormalize(device='gpu', mean=[value * 255 for value in mean], std=[value * 255 for value in std], output_layout='CHW', image_type=types.DALIImageType.BGR)\nself.scaler = ops.Normalize(device='gpu', scale=float(255 / scaler), mean=0, stddev=1)\nself.i... | <|body_start_0|>
self.normalize = normalize
self.image_normalize = ops.CropMirrorNormalize(device='gpu', mean=[value * 255 for value in mean], std=[value * 255 for value in std], output_layout='CHW', image_type=types.DALIImageType.BGR)
self.scaler = ops.Normalize(device='gpu', scale=float(255 / ... | Standard augmentation which resize the input image into desired size and pad it to square, also additionally normalize the input | StandardAugment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardAugment:
"""Standard augmentation which resize the input image into desired size and pad it to square, also additionally normalize the input"""
def __init__(self, input_size: int, scaler: Union[int, float]=255, mean: List[float]=[0.0, 0.0, 0.0], std: List[float]=[1.0, 1.0, 1.0], imag... | stack_v2_sparse_classes_75kplus_train_069913 | 22,608 | no_license | [
{
"docstring": "Initialization Args: input_size (int): Target size of image resize scaler (Union[int,float], optional): The scaling factor applied to the input pixel value. Defaults to 255. mean (List[float], optional): Mean pixel values for image normalization. Defaults to [0.,0.,0.]. std (List[float], optiona... | 2 | stack_v2_sparse_classes_30k_train_023699 | Implement the Python class `StandardAugment` described below.
Class description:
Standard augmentation which resize the input image into desired size and pad it to square, also additionally normalize the input
Method signatures and docstrings:
- def __init__(self, input_size: int, scaler: Union[int, float]=255, mean:... | Implement the Python class `StandardAugment` described below.
Class description:
Standard augmentation which resize the input image into desired size and pad it to square, also additionally normalize the input
Method signatures and docstrings:
- def __init__(self, input_size: int, scaler: Union[int, float]=255, mean:... | 1532db8447d03e75d5ec26f93111270a4ccb7a7e | <|skeleton|>
class StandardAugment:
"""Standard augmentation which resize the input image into desired size and pad it to square, also additionally normalize the input"""
def __init__(self, input_size: int, scaler: Union[int, float]=255, mean: List[float]=[0.0, 0.0, 0.0], std: List[float]=[1.0, 1.0, 1.0], imag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StandardAugment:
"""Standard augmentation which resize the input image into desired size and pad it to square, also additionally normalize the input"""
def __init__(self, input_size: int, scaler: Union[int, float]=255, mean: List[float]=[0.0, 0.0, 0.0], std: List[float]=[1.0, 1.0, 1.0], image_pad_value: ... | the_stack_v2_python_sparse | src/development/vortex/development/utils/data/augment/modules/nvidia_dali/modules.py | jesslynsepthiaa/vortex | train | 0 |
a6373872488a3865d22117a7d5e26712311b0775 | [
"if len(nums) == 1:\n return nums[0]\nmaxsum = -float('inf')\nsum = 0\nfor i in range(len(nums)):\n sum = max(sum + nums[i], nums[i])\n maxsum = max(maxsum, sum)\nreturn maxsum",
"dp = [0] * len(nums)\ndp[0] = nums[0]\nmaxSum = nums[0]\nfor i in range(1, len(nums)):\n dp[i] = max(dp[i - 1] + nums[i], ... | <|body_start_0|>
if len(nums) == 1:
return nums[0]
maxsum = -float('inf')
sum = 0
for i in range(len(nums)):
sum = max(sum + nums[i], nums[i])
maxsum = max(maxsum, sum)
return maxsum
<|end_body_0|>
<|body_start_1|>
dp = [0] * len(nums)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int 解法:动态规划"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 1:
retur... | stack_v2_sparse_classes_75kplus_train_069914 | 1,081 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray0",
"signature": "def maxSubArray0(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 解法:动态规划",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray0(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int 解法:动态规划 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray0(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int 解法:动态规划
<|skeleton|>
class Solution:
def ma... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def maxSubArray0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int 解法:动态规划"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSubArray0(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 1:
return nums[0]
maxsum = -float('inf')
sum = 0
for i in range(len(nums)):
sum = max(sum + nums[i], nums[i])
maxsum = max(maxsum, sum)
... | the_stack_v2_python_sparse | 53.最大子序和.py | yangyuxiang1996/leetcode | train | 0 | |
4ded124c159fc0565039ea9e4934a5cf46e782c4 | [
"m = len(obstacleGrid)\nif m == 0:\n return 0\nn = len(obstacleGrid[0])\nself.cnt = 0\n\ndef help(obstacleGrid, x, y, m, n):\n if obstacleGrid[x][y]:\n return\n if obstacleGrid[x][y] == 0 and x == m - 1 and (y == n - 1):\n self.cnt += 1\n if x < m and y < n:\n if y + 1 < n and obsta... | <|body_start_0|>
m = len(obstacleGrid)
if m == 0:
return 0
n = len(obstacleGrid[0])
self.cnt = 0
def help(obstacleGrid, x, y, m, n):
if obstacleGrid[x][y]:
return
if obstacleGrid[x][y] == 0 and x == m - 1 and (y == n - 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePathsWithObstacles1(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathsWithObstacles2(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_1|>
def uniquePa... | stack_v2_sparse_classes_75kplus_train_069915 | 2,216 | no_license | [
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles1",
"signature": "def uniquePathsWithObstacles1(self, obstacleGrid)"
},
{
"docstring": ":type obstacleGrid: List[List[int]] :rtype: int",
"name": "uniquePathsWithObstacles2",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_030958 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles1(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathsWithObstacles2(self, obstacleGrid): :type obstacleGrid: List[L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsWithObstacles1(self, obstacleGrid): :type obstacleGrid: List[List[int]] :rtype: int
- def uniquePathsWithObstacles2(self, obstacleGrid): :type obstacleGrid: List[L... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def uniquePathsWithObstacles1(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_0|>
def uniquePathsWithObstacles2(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
<|body_1|>
def uniquePa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def uniquePathsWithObstacles1(self, obstacleGrid):
""":type obstacleGrid: List[List[int]] :rtype: int"""
m = len(obstacleGrid)
if m == 0:
return 0
n = len(obstacleGrid[0])
self.cnt = 0
def help(obstacleGrid, x, y, m, n):
if obs... | the_stack_v2_python_sparse | py/leetcode/63.py | wfeng1991/learnpy | train | 0 | |
e5aa7f3f364e0ae576c7d2d8980f7ea1c4881863 | [
"self.data_set_reader = data_set_reader\nself.param = param\nself.model_class = model_class\nself.predictor = None\nself.input_keys = []\nself.init_data_params()\nself.init_env()",
"model_path = self.param['inference_model_path']\nconfig = AnalysisConfig(model_path + '/' + 'model', model_path + '/' + 'params')\ni... | <|body_start_0|>
self.data_set_reader = data_set_reader
self.param = param
self.model_class = model_class
self.predictor = None
self.input_keys = []
self.init_data_params()
self.init_env()
<|end_body_0|>
<|body_start_1|>
model_path = self.param['inference... | Predictor: 模型预测 | Predictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Predictor: 模型预测"""
def __init__(self, param, data_set_reader, model_class):
"""1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model"""
<|body_0... | stack_v2_sparse_classes_75kplus_train_069916 | 3,405 | permissive | [
{
"docstring": "1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model",
"name": "__init__",
"signature": "def __init__(self, param, data_set_reader, model_class)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_034242 | Implement the Python class `Predictor` described below.
Class description:
Predictor: 模型预测
Method signatures and docstrings:
- def __init__(self, param, data_set_reader, model_class): 1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基... | Implement the Python class `Predictor` described below.
Class description:
Predictor: 模型预测
Method signatures and docstrings:
- def __init__(self, param, data_set_reader, model_class): 1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基... | e08f3cb7b9db4c837000316c791542580ba02624 | <|skeleton|>
class Predictor:
"""Predictor: 模型预测"""
def __init__(self, param, data_set_reader, model_class):
"""1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model"""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predictor:
"""Predictor: 模型预测"""
def __init__(self, param, data_set_reader, model_class):
"""1.解析input_data的结构 2.解析参数,构造predictor 3. 启动data_generator,开始预测 4.回掉预测结果到model中进行解析 :param param: 运行的基本参数设置 :param data_set_reader: 运行的基本参数设置 :param model_class: 使用的是哪个model"""
self.data_set_reader ... | the_stack_v2_python_sparse | NLP/DuSQL-Baseline/text2sql/framework/predictor.py | ajayvbabu/Research | train | 0 |
02cc9a2c15805850a6778259704c666ff77620a6 | [
"super(DLGMLayer, self).__init__()\nif issubclass(type(pouts), list):\n self.out_module = nn.ModuleList()\n self.cov_module = nn.ModuleList()\n for pout in pouts:\n self.out_module.append(nn.Linear(pins['dim'], pout['dim']))\n init_module(self.out_module, 'Linear')\n self.cov_module.ap... | <|body_start_0|>
super(DLGMLayer, self).__init__()
if issubclass(type(pouts), list):
self.out_module = nn.ModuleList()
self.cov_module = nn.ModuleList()
for pout in pouts:
self.out_module.append(nn.Linear(pins['dim'], pout['dim']))
init... | DLGMLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DLGMLayer:
def __init__(self, pins, pouts, nn_lin=MLP_DEFAULT_NNLIN, name='', **kwargs):
""":param pins: parameters of the above layer :type pins: dict :param pouts: parameters of the ouput distribution :type pouts: dict :param phidden: parameters of the hidden layer(s) :type phidden: di... | stack_v2_sparse_classes_75kplus_train_069917 | 15,390 | no_license | [
{
"docstring": ":param pins: parameters of the above layer :type pins: dict :param pouts: parameters of the ouput distribution :type pouts: dict :param phidden: parameters of the hidden layer(s) :type phidden: dict :param nn_lin: non-linearity name :type nn_lin: str :param name: name of module :type name: str",... | 2 | stack_v2_sparse_classes_30k_train_022989 | Implement the Python class `DLGMLayer` described below.
Class description:
Implement the DLGMLayer class.
Method signatures and docstrings:
- def __init__(self, pins, pouts, nn_lin=MLP_DEFAULT_NNLIN, name='', **kwargs): :param pins: parameters of the above layer :type pins: dict :param pouts: parameters of the ouput ... | Implement the Python class `DLGMLayer` described below.
Class description:
Implement the DLGMLayer class.
Method signatures and docstrings:
- def __init__(self, pins, pouts, nn_lin=MLP_DEFAULT_NNLIN, name='', **kwargs): :param pins: parameters of the above layer :type pins: dict :param pouts: parameters of the ouput ... | 93da0ef4b8ef6694fd240f8e8823f9c51bd310a4 | <|skeleton|>
class DLGMLayer:
def __init__(self, pins, pouts, nn_lin=MLP_DEFAULT_NNLIN, name='', **kwargs):
""":param pins: parameters of the above layer :type pins: dict :param pouts: parameters of the ouput distribution :type pouts: dict :param phidden: parameters of the hidden layer(s) :type phidden: di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DLGMLayer:
def __init__(self, pins, pouts, nn_lin=MLP_DEFAULT_NNLIN, name='', **kwargs):
""":param pins: parameters of the above layer :type pins: dict :param pouts: parameters of the ouput distribution :type pouts: dict :param phidden: parameters of the hidden layer(s) :type phidden: dict :param nn_l... | the_stack_v2_python_sparse | modules/modules_bottleneck.py | domkirke/vschaos | train | 5 | |
c4821051bed10bafbd27f08aee0bc2c0fe3d6053 | [
"super().__init__(interlocking_time, tau, dead_time)\nself._last_state = 4\nself._switching_table = np.array([[0, 5, 7, 4, 4, 5, 4, 7, 8], [5, 1, 4, 8, 4, 5, 4, 7, 8], [7, 4, 2, 6, 4, 4, 6, 7, 4], [4, 8, 6, 3, 4, 4, 6, 4, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 4, 4, 4, 5, 4, 7, 8], [4, 4, 2, 3, 4, 4, 6, 7, 8], [0,... | <|body_start_0|>
super().__init__(interlocking_time, tau, dead_time)
self._last_state = 4
self._switching_table = np.array([[0, 5, 7, 4, 4, 5, 4, 7, 8], [5, 1, 4, 8, 4, 5, 4, 7, 8], [7, 4, 2, 6, 4, 4, 6, 7, 4], [4, 8, 6, 3, 4, 4, 6, 4, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 4, 4, 4, 5, 4, 7, 8]... | 4QC, consisting of two parallel half bridges The state space of the converter is larger, because it includes also the cases, when only one or no transistor is conducting. The definition of the states is given below. '1' means conducting and '0' is switched of. The first four (0-3) states are the actions of the action s... | DiscreteFourQuadrantConverter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteFourQuadrantConverter:
"""4QC, consisting of two parallel half bridges The state space of the converter is larger, because it includes also the cases, when only one or no transistor is conducting. The definition of the states is given below. '1' means conducting and '0' is switched of. Th... | stack_v2_sparse_classes_75kplus_train_069918 | 18,548 | permissive | [
{
"docstring": "Initialisation of the discrete 4QC is special because further transformation matrices to consider the interlocking time needs to be setup. More details can be found in the init of the base class. Args: interlocking_time: Interlocking time of the Converter between the switches of the Transistors ... | 2 | stack_v2_sparse_classes_30k_train_048466 | Implement the Python class `DiscreteFourQuadrantConverter` described below.
Class description:
4QC, consisting of two parallel half bridges The state space of the converter is larger, because it includes also the cases, when only one or no transistor is conducting. The definition of the states is given below. '1' mean... | Implement the Python class `DiscreteFourQuadrantConverter` described below.
Class description:
4QC, consisting of two parallel half bridges The state space of the converter is larger, because it includes also the cases, when only one or no transistor is conducting. The definition of the states is given below. '1' mean... | 48a0232edf3474e441453126df0f52dc391aed11 | <|skeleton|>
class DiscreteFourQuadrantConverter:
"""4QC, consisting of two parallel half bridges The state space of the converter is larger, because it includes also the cases, when only one or no transistor is conducting. The definition of the states is given below. '1' means conducting and '0' is switched of. Th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiscreteFourQuadrantConverter:
"""4QC, consisting of two parallel half bridges The state space of the converter is larger, because it includes also the cases, when only one or no transistor is conducting. The definition of the states is given below. '1' means conducting and '0' is switched of. The first four ... | the_stack_v2_python_sparse | gym_electric_motor/envs/gym_dcm/models/converter_models.py | zizai/gym-electric-motor | train | 0 |
20c547d6fe672eedcb1623a1f21bcae5540bd168 | [
"super(UsedLimitsClient, self).__init__(serialize_format, deserialize_format)\nself.auth_token = auth_token\nself.default_headers['X-Auth-Token'] = auth_token\nct = 'application/{0}'.format(self.serialize_format)\naccept = 'application/{0}'.format(self.serialize_format)\nself.default_headers['Content-Type'] = ct\ns... | <|body_start_0|>
super(UsedLimitsClient, self).__init__(serialize_format, deserialize_format)
self.auth_token = auth_token
self.default_headers['X-Auth-Token'] = auth_token
ct = 'application/{0}'.format(self.serialize_format)
accept = 'application/{0}'.format(self.serialize_forma... | UsedLimitsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsedLimitsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for ... | stack_v2_sparse_classes_75kplus_train_069919 | 2,382 | permissive | [
{
"docstring": "@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for serializing requests @type serialize_format: String @param deserialize_format: Format for de-serializing responses... | 2 | stack_v2_sparse_classes_30k_test_000737 | Implement the Python class `UsedLimitsClient` described below.
Class description:
Implement the UsedLimitsClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @param url: Base URL for the compute service @type url: String @param auth_to... | Implement the Python class `UsedLimitsClient` described below.
Class description:
Implement the UsedLimitsClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @param url: Base URL for the compute service @type url: String @param auth_to... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class UsedLimitsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsedLimitsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for serializing re... | the_stack_v2_python_sparse | cloudcafe/compute/extensions/used_limits/client.py | kurhula/cloudcafe | train | 0 | |
c65202139a2349f4634690195a93f3f433673a1d | [
"import_info.pop(CONF_MONITORED_CONDITIONS, None)\nimport_info.pop(CONF_NICS, None)\nimport_info.pop(CONF_DRIVES, None)\nimport_info.pop(CONF_VOLUMES, None)\nreturn await self.async_step_user(import_info)",
"errors = {}\nif user_input is not None:\n host = user_input[CONF_HOST]\n protocol = 'https' if user_... | <|body_start_0|>
import_info.pop(CONF_MONITORED_CONDITIONS, None)
import_info.pop(CONF_NICS, None)
import_info.pop(CONF_DRIVES, None)
import_info.pop(CONF_VOLUMES, None)
return await self.async_step_user(import_info)
<|end_body_0|>
<|body_start_1|>
errors = {}
if... | Qnap configuration flow. | QnapConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QnapConfigFlow:
"""Qnap configuration flow."""
async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult:
"""Set the config entry up from yaml."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
... | stack_v2_sparse_classes_75kplus_train_069920 | 3,220 | permissive | [
{
"docstring": "Set the config entry up from yaml.",
"name": "async_step_import",
"signature": "async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult"
},
{
"docstring": "Handle a flow initialized by the user.",
"name": "async_step_user",
"signature": "async def asy... | 2 | stack_v2_sparse_classes_30k_train_019809 | Implement the Python class `QnapConfigFlow` described below.
Class description:
Qnap configuration flow.
Method signatures and docstrings:
- async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: Set the config entry up from yaml.
- async def async_step_user(self, user_input: dict[str, Any] | N... | Implement the Python class `QnapConfigFlow` described below.
Class description:
Qnap configuration flow.
Method signatures and docstrings:
- async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: Set the config entry up from yaml.
- async def async_step_user(self, user_input: dict[str, Any] | N... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class QnapConfigFlow:
"""Qnap configuration flow."""
async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult:
"""Set the config entry up from yaml."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QnapConfigFlow:
"""Qnap configuration flow."""
async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult:
"""Set the config entry up from yaml."""
import_info.pop(CONF_MONITORED_CONDITIONS, None)
import_info.pop(CONF_NICS, None)
import_info.pop(CONF_DRIV... | the_stack_v2_python_sparse | homeassistant/components/qnap/config_flow.py | home-assistant/core | train | 35,501 |
b4bb5e8cc6c6d05a396eef2f84976670f8f1abcf | [
"super(GAT, self).__init__()\nif sparse:\n attention_layer = SparseGraphAttentionLayer\nelse:\n attention_layer = GraphAttentionLayer\nself.attentions = nn.ModuleList()\nfor _ in range(num_heads):\n self.attentions.append(attention_layer(input_dim, hidden_dim, dropout, alpha, True))\nself.elu = nn.ELU(inpl... | <|body_start_0|>
super(GAT, self).__init__()
if sparse:
attention_layer = SparseGraphAttentionLayer
else:
attention_layer = GraphAttentionLayer
self.attentions = nn.ModuleList()
for _ in range(num_heads):
self.attentions.append(attention_layer(... | 定义GAT网络 | GAT | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAT:
"""定义GAT网络"""
def __init__(self, input_dim, hidden_dim, output_dim, num_heads, dropout, alpha, sparse=False):
"""定义GAT网络 Inputs: ------- input_dim: int, 输入维度 hidden_dim: int, 隐层维度 outut_dim: int, 输出维度 num_heads: int, 多头注意力个数 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜... | stack_v2_sparse_classes_75kplus_train_069921 | 1,887 | permissive | [
{
"docstring": "定义GAT网络 Inputs: ------- input_dim: int, 输入维度 hidden_dim: int, 隐层维度 outut_dim: int, 输出维度 num_heads: int, 多头注意力个数 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 sparse: boolean, 是否使用稀疏数据",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, output_dim, num_... | 2 | stack_v2_sparse_classes_30k_train_022886 | Implement the Python class `GAT` described below.
Class description:
定义GAT网络
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim, num_heads, dropout, alpha, sparse=False): 定义GAT网络 Inputs: ------- input_dim: int, 输入维度 hidden_dim: int, 隐层维度 outut_dim: int, 输出维度 num_heads: int, 多头注意力... | Implement the Python class `GAT` described below.
Class description:
定义GAT网络
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim, num_heads, dropout, alpha, sparse=False): 定义GAT网络 Inputs: ------- input_dim: int, 输入维度 hidden_dim: int, 隐层维度 outut_dim: int, 输出维度 num_heads: int, 多头注意力... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class GAT:
"""定义GAT网络"""
def __init__(self, input_dim, hidden_dim, output_dim, num_heads, dropout, alpha, sparse=False):
"""定义GAT网络 Inputs: ------- input_dim: int, 输入维度 hidden_dim: int, 隐层维度 outut_dim: int, 输出维度 num_heads: int, 多头注意力个数 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GAT:
"""定义GAT网络"""
def __init__(self, input_dim, hidden_dim, output_dim, num_heads, dropout, alpha, sparse=False):
"""定义GAT网络 Inputs: ------- input_dim: int, 输入维度 hidden_dim: int, 隐层维度 outut_dim: int, 输出维度 num_heads: int, 多头注意力个数 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 sparse: boo... | the_stack_v2_python_sparse | Node/GAT/script/model.py | robbinc91/GNN-Pytorch | train | 0 |
75d251962a60ccebcc0d30c545efe51a64b6ed85 | [
"super().__init__()\nvgg_pretrained_features = torchvision.models.vgg19(pretrained=True).eval().features\nself.slice1 = torch.nn.Sequential()\nself.slice2 = torch.nn.Sequential()\nself.slice3 = torch.nn.Sequential()\nself.slice4 = torch.nn.Sequential()\nself.slice5 = torch.nn.Sequential()\nfor x in range(2):\n s... | <|body_start_0|>
super().__init__()
vgg_pretrained_features = torchvision.models.vgg19(pretrained=True).eval().features
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
... | VGG19 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG19:
def __init__(self, requires_grad=False):
"""VGG19 perceptual loss. Uses the following feature layers: [ "input_1", "block1_conv2", "block2_conv2", "block3_conv2", "block4_conv2", "block5_conv2" ] Parameters ---------- torch : [type] [description] requires_grad : bool, optional if ... | stack_v2_sparse_classes_75kplus_train_069922 | 7,347 | permissive | [
{
"docstring": "VGG19 perceptual loss. Uses the following feature layers: [ \"input_1\", \"block1_conv2\", \"block2_conv2\", \"block3_conv2\", \"block4_conv2\", \"block5_conv2\" ] Parameters ---------- torch : [type] [description] requires_grad : bool, optional if True, will also train VGG layers, by default Fa... | 3 | null | Implement the Python class `VGG19` described below.
Class description:
Implement the VGG19 class.
Method signatures and docstrings:
- def __init__(self, requires_grad=False): VGG19 perceptual loss. Uses the following feature layers: [ "input_1", "block1_conv2", "block2_conv2", "block3_conv2", "block4_conv2", "block5_... | Implement the Python class `VGG19` described below.
Class description:
Implement the VGG19 class.
Method signatures and docstrings:
- def __init__(self, requires_grad=False): VGG19 perceptual loss. Uses the following feature layers: [ "input_1", "block1_conv2", "block2_conv2", "block3_conv2", "block4_conv2", "block5_... | 9fff8275278ff26caff50da86109c25d276bb30b | <|skeleton|>
class VGG19:
def __init__(self, requires_grad=False):
"""VGG19 perceptual loss. Uses the following feature layers: [ "input_1", "block1_conv2", "block2_conv2", "block3_conv2", "block4_conv2", "block5_conv2" ] Parameters ---------- torch : [type] [description] requires_grad : bool, optional if ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VGG19:
def __init__(self, requires_grad=False):
"""VGG19 perceptual loss. Uses the following feature layers: [ "input_1", "block1_conv2", "block2_conv2", "block3_conv2", "block4_conv2", "block5_conv2" ] Parameters ---------- torch : [type] [description] requires_grad : bool, optional if True, will als... | the_stack_v2_python_sparse | supermariopy/ptutils/losses.py | hustzxd/supermariopy | train | 0 | |
3eb30b96aedebe0c424000bf5c963a1d74096b4b | [
"if verbose:\n print('SQL Database type %s verbose=%s' % (db_dict, verbose))\nsuper(SQLPreviousScansTable, self).__init__(db_dict, dbtype, verbose)\nself.connection = None",
"try:\n print('Database characteristics')\n for key in self.db_dict:\n print('%s: %s' % key, self.db_dict[key])\nexcept Val... | <|body_start_0|>
if verbose:
print('SQL Database type %s verbose=%s' % (db_dict, verbose))
super(SQLPreviousScansTable, self).__init__(db_dict, dbtype, verbose)
self.connection = None
<|end_body_0|>
<|body_start_1|>
try:
print('Database characteristics')
... | " Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized. | SQLPreviousScansTable | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLPreviousScansTable:
"""" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(... | stack_v2_sparse_classes_75kplus_train_069923 | 5,186 | permissive | [
{
"docstring": "Pass through to SQL",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Display the db info and Return info on the database used as a dictionary.",
"name": "db_info",
"signature": "def db_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001861 | Implement the Python class `SQLPreviousScansTable` described below.
Class description:
" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pa... | Implement the Python class `SQLPreviousScansTable` described below.
Class description:
" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pa... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class SQLPreviousScansTable:
"""" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SQLPreviousScansTable:
"""" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
if verbose:
print('SQL Databa... | the_stack_v2_python_sparse | smipyping/_previousscanstable.py | KSchopmeyer/smipyping | train | 0 |
c03f60a45a26b16fd0ba163d1bf9dd43a53c21b1 | [
"self.value = value\nself.next = next_cell\nself.prev = prev_cell",
"print(self.value, end=' ')\nif self.next != None:\n self.next.__print_without_iterator_forward()\nelse:\n print()",
"print(self.value, end=' ')\nif self.prev != None:\n self.prev.__print_without_iterator_reversed()\nelse:\n print()... | <|body_start_0|>
self.value = value
self.next = next_cell
self.prev = prev_cell
<|end_body_0|>
<|body_start_1|>
print(self.value, end=' ')
if self.next != None:
self.next.__print_without_iterator_forward()
else:
print()
<|end_body_1|>
<|body_star... | Double-linked cells | Cell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cell:
"""Double-linked cells"""
def __init__(self, value, next_cell, prev_cell):
"""Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None... | stack_v2_sparse_classes_75kplus_train_069924 | 10,145 | no_license | [
{
"docstring": "Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None otherwise :type next_cell: Cell :param prev_cell: The predecessor of this cell, if any or None ... | 3 | stack_v2_sparse_classes_30k_train_033679 | Implement the Python class `Cell` described below.
Class description:
Double-linked cells
Method signatures and docstrings:
- def __init__(self, value, next_cell, prev_cell): Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :pa... | Implement the Python class `Cell` described below.
Class description:
Double-linked cells
Method signatures and docstrings:
- def __init__(self, value, next_cell, prev_cell): Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :pa... | 753e6cf2ddc6e95265b1c2ab5c8b3685c36d29e7 | <|skeleton|>
class Cell:
"""Double-linked cells"""
def __init__(self, value, next_cell, prev_cell):
"""Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cell:
"""Double-linked cells"""
def __init__(self, value, next_cell, prev_cell):
"""Creates a new cell with the specified values, and the links to the next and previous cells (if any). :param value: A value :type value: Any :param next_cell: The successor of this cell, if any or None otherwise :t... | the_stack_v2_python_sparse | L2/Algo structure de données/TP3/src/listiterator.py | BenjaminDOUCHET/Travail-FIL | train | 0 |
eaf295d4ae67329376c82f8fc095b4ad682bfa2e | [
"test = \"5\\nIAO'15\\nIAO'2015\\nIAO'1\\nIAO'9\\nIAO'0\"\nd = Olymp(test)\nself.assertEqual(d.n, 5)\nself.assertEqual(d.nums[0:2], ['15', '2015'])\nself.assertEqual(Olymp(test).calculate(), '2015\\n12015\\n1991\\n1989\\n1990')\ntest = \"4\\nIAO'9\\nIAO'99\\nIAO'999\\nIAO'9999\"\nself.assertEqual(Olymp(test).calcul... | <|body_start_0|>
test = "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0"
d = Olymp(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.nums[0:2], ['15', '2015'])
self.assertEqual(Olymp(test).calculate(), '2015\n12015\n1991\n1989\n1990')
test = "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Olymp class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0"
d = Olymp(tes... | stack_v2_sparse_classes_75kplus_train_069925 | 3,747 | permissive | [
{
"docstring": "Olymp class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036073 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Olymp class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Olymp class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Olymp class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class unitTests:
def test_single_test(self):
"""Olymp class testing"""
test = "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0"
d = Olymp(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.nums[0:2], ['15', '2015'])
self.assertEqual(Olymp(test).calculate(), '2015\n12015\n1991... | the_stack_v2_python_sparse | codeforces/664C_olymp.py | snsokolov/contests | train | 1 | |
986b27ecd3188def636acd8d3dca2b517b53693d | [
"self.name = name\nself.international = international\nself.emoji = emoji",
"tag = session.query(Tag).get(name)\nif tag and emoji:\n tag.emoji = True\n if tag.international is True:\n tag.international = False\nif tag and (not international) and tag.international:\n tag.international = False\nif t... | <|body_start_0|>
self.name = name
self.international = international
self.emoji = emoji
<|end_body_0|>
<|body_start_1|>
tag = session.query(Tag).get(name)
if tag and emoji:
tag.emoji = True
if tag.international is True:
tag.international =... | The model for a sticker. | Tag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
<|body_0|>
def get_or_create(session, name, international, emoji=False):
"""Get or create a new sticker."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_069926 | 1,813 | permissive | [
{
"docstring": "Create a new sticker.",
"name": "__init__",
"signature": "def __init__(self, name, international, emoji)"
},
{
"docstring": "Get or create a new sticker.",
"name": "get_or_create",
"signature": "def get_or_create(session, name, international, emoji=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036827 | Implement the Python class `Tag` described below.
Class description:
The model for a sticker.
Method signatures and docstrings:
- def __init__(self, name, international, emoji): Create a new sticker.
- def get_or_create(session, name, international, emoji=False): Get or create a new sticker. | Implement the Python class `Tag` described below.
Class description:
The model for a sticker.
Method signatures and docstrings:
- def __init__(self, name, international, emoji): Create a new sticker.
- def get_or_create(session, name, international, emoji=False): Get or create a new sticker.
<|skeleton|>
class Tag:
... | 873468f8de26cc32d1de9b688140569b8086ab5b | <|skeleton|>
class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
<|body_0|>
def get_or_create(session, name, international, emoji=False):
"""Get or create a new sticker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
self.name = name
self.international = international
self.emoji = emoji
def get_or_create(session, name, international, emoji=False):
"""Get or creat... | the_stack_v2_python_sparse | stickerfinder/models/tag.py | arlessweschler/sticker-finder | train | 0 |
9649de1fa39eeba6ff22ee66fe7f8285b650c110 | [
"if not args_lateral:\n args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}\nif not args_longitudinal:\n args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}\nself.node = node\nself._lon_controller = PIDLongitudinalController(**args_longitudinal)\nself._lat_controller = PIDLateralController(**args_lateral... | <|body_start_0|>
if not args_lateral:
args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
if not args_longitudinal:
args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
self.node = node
self._lon_controller = PIDLongitudinalController(**args_longitudinal)
... | VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side | VehiclePIDController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to ... | stack_v2_sparse_classes_75kplus_train_069927 | 6,324 | permissive | [
{
"docstring": ":param vehicle: actor to apply to local planner logic onto :param args_lateral: dictionary of arguments to set the lateral PID controller using the following semantics: K_P -- Proportional term K_D -- Differential term K_I -- Integral term :param args_longitudinal: dictionary of arguments to set... | 2 | stack_v2_sparse_classes_30k_train_017372 | Implement the Python class `VehiclePIDController` described below.
Class description:
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
Method signatures and docstrings:
- def __init__(self, node, args_lateral=None, ar... | Implement the Python class `VehiclePIDController` described below.
Class description:
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
Method signatures and docstrings:
- def __init__(self, node, args_lateral=None, ar... | e9063d97ff5a724f76adbb1b852dc71da1dcfeec | <|skeleton|>
class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to local planner... | the_stack_v2_python_sparse | carla_ad_agent/src/carla_ad_agent/vehicle_pid_controller.py | carla-simulator/ros-bridge | train | 448 |
3ca99638fd53b2c490f3746aa6047d723ad0ac71 | [
"self.target_means = target_means\nself.target_stds = target_stds\nself.num_rpn_deltas = num_rpn_deltas\nself.positive_fraction = positive_fraction\nself.pos_iou_thr = pos_iou_thr\nself.neg_iou_thr = neg_iou_thr",
"rpn_labels = []\nrpn_label_weights = []\nrpn_delta_targets = []\nrpn_delta_weights = []\nnum_imgs =... | <|body_start_0|>
self.target_means = target_means
self.target_stds = target_stds
self.num_rpn_deltas = num_rpn_deltas
self.positive_fraction = positive_fraction
self.pos_iou_thr = pos_iou_thr
self.neg_iou_thr = neg_iou_thr
<|end_body_0|>
<|body_start_1|>
rpn_labe... | AnchorTarget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnchorTarget:
def __init__(self, target_means=(0.0, 0.0, 0.0, 0.0), target_stds=(0.1, 0.1, 0.2, 0.2), num_rpn_deltas=256, positive_fraction=0.5, pos_iou_thr=0.7, neg_iou_thr=0.3):
"""Compute regression and classification targets for anchors. Attributes --- target_means: [4]. Bounding box... | stack_v2_sparse_classes_75kplus_train_069928 | 7,820 | permissive | [
{
"docstring": "Compute regression and classification targets for anchors. Attributes --- target_means: [4]. Bounding box refinement mean for RPN. target_stds: [4]. Bounding box refinement standard deviation for RPN. num_rpn_deltas: int. Maximal number of Anchors per image to feed to rpn heads. positive_fractio... | 3 | stack_v2_sparse_classes_30k_train_033036 | Implement the Python class `AnchorTarget` described below.
Class description:
Implement the AnchorTarget class.
Method signatures and docstrings:
- def __init__(self, target_means=(0.0, 0.0, 0.0, 0.0), target_stds=(0.1, 0.1, 0.2, 0.2), num_rpn_deltas=256, positive_fraction=0.5, pos_iou_thr=0.7, neg_iou_thr=0.3): Comp... | Implement the Python class `AnchorTarget` described below.
Class description:
Implement the AnchorTarget class.
Method signatures and docstrings:
- def __init__(self, target_means=(0.0, 0.0, 0.0, 0.0), target_stds=(0.1, 0.1, 0.2, 0.2), num_rpn_deltas=256, positive_fraction=0.5, pos_iou_thr=0.7, neg_iou_thr=0.3): Comp... | f756b811ab31c9dab2a8f8afe68f46465422f64b | <|skeleton|>
class AnchorTarget:
def __init__(self, target_means=(0.0, 0.0, 0.0, 0.0), target_stds=(0.1, 0.1, 0.2, 0.2), num_rpn_deltas=256, positive_fraction=0.5, pos_iou_thr=0.7, neg_iou_thr=0.3):
"""Compute regression and classification targets for anchors. Attributes --- target_means: [4]. Bounding box... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnchorTarget:
def __init__(self, target_means=(0.0, 0.0, 0.0, 0.0), target_stds=(0.1, 0.1, 0.2, 0.2), num_rpn_deltas=256, positive_fraction=0.5, pos_iou_thr=0.7, neg_iou_thr=0.3):
"""Compute regression and classification targets for anchors. Attributes --- target_means: [4]. Bounding box refinement me... | the_stack_v2_python_sparse | detection/core/anchor/anchor_target.py | HirataYurina/cascade-rcnn-tf2.2 | train | 1 | |
b32b9bb6ae144e053048dc688108b08bdb28b91e | [
"super(StationsDataRequest, self).__init__(client)\nif distance_range and event_locations:\n self.event_locations = list((loc[1] for loc in event_locations))\n self.distance_range = distance_range\n try:\n combined_locations = get_combined_locations(self.event_locations, self.distance_range['maxdist... | <|body_start_0|>
super(StationsDataRequest, self).__init__(client)
if distance_range and event_locations:
self.event_locations = list((loc[1] for loc in event_locations))
self.distance_range = distance_range
try:
combined_locations = get_combined_locat... | StationsDataRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationsDataRequest:
def __init__(self, client, base_options, distance_range, event_locations):
""":param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :... | stack_v2_sparse_classes_75kplus_train_069929 | 7,532 | no_license | [
{
"docstring": ":param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :param event_locations: a list of selected event locations if querying by distance from events",
"name":... | 3 | stack_v2_sparse_classes_30k_train_036418 | Implement the Python class `StationsDataRequest` described below.
Class description:
Implement the StationsDataRequest class.
Method signatures and docstrings:
- def __init__(self, client, base_options, distance_range, event_locations): :param client: an ObsPy FDSN client :param base_options: the basic query options ... | Implement the Python class `StationsDataRequest` described below.
Class description:
Implement the StationsDataRequest class.
Method signatures and docstrings:
- def __init__(self, client, base_options, distance_range, event_locations): :param client: an ObsPy FDSN client :param base_options: the basic query options ... | 1a1faf5daabfc697172e72856e3fa089df038673 | <|skeleton|>
class StationsDataRequest:
def __init__(self, client, base_options, distance_range, event_locations):
""":param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StationsDataRequest:
def __init__(self, client, base_options, distance_range, event_locations):
""":param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :param event_lo... | the_stack_v2_python_sparse | venv/Lib/site-packages/pyweed/stations_handler.py | wenyali/Decoding_code | train | 0 | |
8feb52d641afd47a860b4eb667bf0a82674b7429 | [
"two_node = Graph()\ntwo_node.add_node()\ntwo_node.add_node()\ntwo_node.add_edge(0, 1)\nself.assertEqual(two_node.neighbors, [{1}, {0}])\nself.assertEqual(two_node.node_uids, [0, 1])\nself.assertEqual(two_node.uid_to_index[0], 0)\nself.assertEqual(two_node.uid_to_index[1], 1)\nself.assertEqual(two_node.node_count()... | <|body_start_0|>
two_node = Graph()
two_node.add_node()
two_node.add_node()
two_node.add_edge(0, 1)
self.assertEqual(two_node.neighbors, [{1}, {0}])
self.assertEqual(two_node.node_uids, [0, 1])
self.assertEqual(two_node.uid_to_index[0], 0)
self.assertEqual... | GraphTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphTest:
def test_two_node_graph(self):
"""Build a graph with two nodes and one edge"""
<|body_0|>
def test_ring(self):
"""Build a ring of 8 nodes and test path finding"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
two_node = Graph()
two... | stack_v2_sparse_classes_75kplus_train_069930 | 3,766 | permissive | [
{
"docstring": "Build a graph with two nodes and one edge",
"name": "test_two_node_graph",
"signature": "def test_two_node_graph(self)"
},
{
"docstring": "Build a ring of 8 nodes and test path finding",
"name": "test_ring",
"signature": "def test_ring(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010074 | Implement the Python class `GraphTest` described below.
Class description:
Implement the GraphTest class.
Method signatures and docstrings:
- def test_two_node_graph(self): Build a graph with two nodes and one edge
- def test_ring(self): Build a ring of 8 nodes and test path finding | Implement the Python class `GraphTest` described below.
Class description:
Implement the GraphTest class.
Method signatures and docstrings:
- def test_two_node_graph(self): Build a graph with two nodes and one edge
- def test_ring(self): Build a ring of 8 nodes and test path finding
<|skeleton|>
class GraphTest:
... | 9aef7d5a912ebe759a2877c8aea5754a4db93543 | <|skeleton|>
class GraphTest:
def test_two_node_graph(self):
"""Build a graph with two nodes and one edge"""
<|body_0|>
def test_ring(self):
"""Build a ring of 8 nodes and test path finding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphTest:
def test_two_node_graph(self):
"""Build a graph with two nodes and one edge"""
two_node = Graph()
two_node.add_node()
two_node.add_node()
two_node.add_edge(0, 1)
self.assertEqual(two_node.neighbors, [{1}, {0}])
self.assertEqual(two_node.node_u... | the_stack_v2_python_sparse | src/fermilib/circuits/_graph_test.py | ProjectQ-Framework/FermiLib | train | 105 | |
b2dfb344bc998a6efe47f4e5b1bd0d9b93f76a67 | [
"tree = {}\nif obj.inferred_freq is not None:\n tree['freq'] = obj.inferred_freq\nelse:\n tree['values'] = obj.values.astype(np.int64)\ntree['start'] = obj[0]\ntree['end'] = obj[-1]\ntree['min'] = obj.min()\ntree['max'] = obj.max()\nreturn tree",
"if 'freq' in node:\n return pd.timedelta_range(start=node... | <|body_start_0|>
tree = {}
if obj.inferred_freq is not None:
tree['freq'] = obj.inferred_freq
else:
tree['values'] = obj.values.astype(np.int64)
tree['start'] = obj[0]
tree['end'] = obj[-1]
tree['min'] = obj.min()
tree['max'] = obj.max()
... | A simple implementation of serializing pandas TimedeltaIndex. | TimedeltaIndexConverter | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimedeltaIndexConverter:
"""A simple implementation of serializing pandas TimedeltaIndex."""
def to_yaml_tree(self, obj: pd.TimedeltaIndex, tag: str, ctx) -> dict:
"""Convert to python dict."""
<|body_0|>
def from_yaml_tree(self, node: dict, tag: str, ctx):
"""Co... | stack_v2_sparse_classes_75kplus_train_069931 | 1,646 | permissive | [
{
"docstring": "Convert to python dict.",
"name": "to_yaml_tree",
"signature": "def to_yaml_tree(self, obj: pd.TimedeltaIndex, tag: str, ctx) -> dict"
},
{
"docstring": "Construct TimedeltaIndex from tree.",
"name": "from_yaml_tree",
"signature": "def from_yaml_tree(self, node: dict, tag... | 3 | null | Implement the Python class `TimedeltaIndexConverter` described below.
Class description:
A simple implementation of serializing pandas TimedeltaIndex.
Method signatures and docstrings:
- def to_yaml_tree(self, obj: pd.TimedeltaIndex, tag: str, ctx) -> dict: Convert to python dict.
- def from_yaml_tree(self, node: dic... | Implement the Python class `TimedeltaIndexConverter` described below.
Class description:
A simple implementation of serializing pandas TimedeltaIndex.
Method signatures and docstrings:
- def to_yaml_tree(self, obj: pd.TimedeltaIndex, tag: str, ctx) -> dict: Convert to python dict.
- def from_yaml_tree(self, node: dic... | 7bc16a196ee669822f3663f3c7a08f6bbd0c76d5 | <|skeleton|>
class TimedeltaIndexConverter:
"""A simple implementation of serializing pandas TimedeltaIndex."""
def to_yaml_tree(self, obj: pd.TimedeltaIndex, tag: str, ctx) -> dict:
"""Convert to python dict."""
<|body_0|>
def from_yaml_tree(self, node: dict, tag: str, ctx):
"""Co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimedeltaIndexConverter:
"""A simple implementation of serializing pandas TimedeltaIndex."""
def to_yaml_tree(self, obj: pd.TimedeltaIndex, tag: str, ctx) -> dict:
"""Convert to python dict."""
tree = {}
if obj.inferred_freq is not None:
tree['freq'] = obj.inferred_fre... | the_stack_v2_python_sparse | weldx/tags/time/timedeltaindex.py | BAMWelDX/weldx | train | 20 |
80d17fabdbbef990390626fb7ca8a3857609e53d | [
"if Assignment.objects.filter(id=pk).exists():\n assignment = Assignment.objects.select_related('manager', 'assignee').prefetch_related('comment_set').get(id=pk)\n task_data = get_assignment_data(assignment)\n return Response(task_data, status=200)\nreturn Response({'msg': 'Assignment not found!'}, status=... | <|body_start_0|>
if Assignment.objects.filter(id=pk).exists():
assignment = Assignment.objects.select_related('manager', 'assignee').prefetch_related('comment_set').get(id=pk)
task_data = get_assignment_data(assignment)
return Response(task_data, status=200)
return Re... | AssignmentViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignmentViewSet:
def retrieve(self, request, pk, format=None):
"""Sample response: --- { 'title': 'texts...', 'description': 'texts...', 'manager': 22, 'assignee_list': [12, 13], 'status': 2, // (1, Remaining), (2, In progress),(3, Complete),(4, Cancelled), 'org': 222, 'deadline': "201... | stack_v2_sparse_classes_75kplus_train_069932 | 9,299 | no_license | [
{
"docstring": "Sample response: --- { 'title': 'texts...', 'description': 'texts...', 'manager': 22, 'assignee_list': [12, 13], 'status': 2, // (1, Remaining), (2, In progress),(3, Complete),(4, Cancelled), 'org': 222, 'deadline': \"2019-03-11T07:07:24.000000+00:00\", 'custom_fields': {json field}, 'comment_li... | 4 | stack_v2_sparse_classes_30k_train_016622 | Implement the Python class `AssignmentViewSet` described below.
Class description:
Implement the AssignmentViewSet class.
Method signatures and docstrings:
- def retrieve(self, request, pk, format=None): Sample response: --- { 'title': 'texts...', 'description': 'texts...', 'manager': 22, 'assignee_list': [12, 13], '... | Implement the Python class `AssignmentViewSet` described below.
Class description:
Implement the AssignmentViewSet class.
Method signatures and docstrings:
- def retrieve(self, request, pk, format=None): Sample response: --- { 'title': 'texts...', 'description': 'texts...', 'manager': 22, 'assignee_list': [12, 13], '... | 11be165f85cda0ffe7a237d011de562d3dc64135 | <|skeleton|>
class AssignmentViewSet:
def retrieve(self, request, pk, format=None):
"""Sample response: --- { 'title': 'texts...', 'description': 'texts...', 'manager': 22, 'assignee_list': [12, 13], 'status': 2, // (1, Remaining), (2, In progress),(3, Complete),(4, Cancelled), 'org': 222, 'deadline': "201... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssignmentViewSet:
def retrieve(self, request, pk, format=None):
"""Sample response: --- { 'title': 'texts...', 'description': 'texts...', 'manager': 22, 'assignee_list': [12, 13], 'status': 2, // (1, Remaining), (2, In progress),(3, Complete),(4, Cancelled), 'org': 222, 'deadline': "2019-03-11T07:07:... | the_stack_v2_python_sparse | apps/assignment/views.py | ash018/FFTracker | train | 0 | |
2a793dad8a047ed5bf32b4ccfa5bc9dc0f6441e3 | [
"if not preorder or not inorder:\n return None\nval = preorder.pop(0)\nroot_node = TreeNode(val)\nroot_index = inorder.index(val)\nleft_pre = preorder[:root_index]\nleft_in = inorder[:root_index]\nright_pre = preorder[root_index:]\nright_in = inorder[root_index + 1:]\nroot_node.left = self.buildTree(left_pre, le... | <|body_start_0|>
if not preorder or not inorder:
return None
val = preorder.pop(0)
root_node = TreeNode(val)
root_index = inorder.index(val)
left_pre = preorder[:root_index]
left_in = inorder[:root_index]
right_pre = preorder[root_index:]
right... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
"""先确定根节点:根节点是前序遍历的第一个元素 再在中序遍历中确定左右子树的个数:根节点左边是左子树,根节点右边是右子树 递归这个过程 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree1(self, preorder, inorder):
"""力扣官方解法 :type preorder:... | stack_v2_sparse_classes_75kplus_train_069933 | 3,589 | no_license | [
{
"docstring": "先确定根节点:根节点是前序遍历的第一个元素 再在中序遍历中确定左右子树的个数:根节点左边是左子树,根节点右边是右子树 递归这个过程 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": "力扣官方解法 :type preorder: List[int] :type inorder: Li... | 2 | stack_v2_sparse_classes_30k_train_010814 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): 先确定根节点:根节点是前序遍历的第一个元素 再在中序遍历中确定左右子树的个数:根节点左边是左子树,根节点右边是右子树 递归这个过程 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): 先确定根节点:根节点是前序遍历的第一个元素 再在中序遍历中确定左右子树的个数:根节点左边是左子树,根节点右边是右子树 递归这个过程 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- de... | a3a1556abc5adb9325de54d64f9814e64b96db0f | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
"""先确定根节点:根节点是前序遍历的第一个元素 再在中序遍历中确定左右子树的个数:根节点左边是左子树,根节点右边是右子树 递归这个过程 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree1(self, preorder, inorder):
"""力扣官方解法 :type preorder:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def buildTree(self, preorder, inorder):
"""先确定根节点:根节点是前序遍历的第一个元素 再在中序遍历中确定左右子树的个数:根节点左边是左子树,根节点右边是右子树 递归这个过程 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
if not preorder or not inorder:
return None
val = preorder.pop(0)
root_node ... | the_stack_v2_python_sparse | leetcode/tree/buildTree.py | BigerWANG/geek_algorithm | train | 0 | |
c6880af19233a48abb697f13caf1fbedc4ae6fb5 | [
"if not request.user.id:\n return BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_NOT_LOGIN_ERR).to_response()\nrequest.user.update_wechat_mobile()\ndata = UserSerializer(request.user).data\nreturn BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_NORMAL, data=data).to_response()",
... | <|body_start_0|>
if not request.user.id:
return BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_NOT_LOGIN_ERR).to_response()
request.user.update_wechat_mobile()
data = UserSerializer(request.user).data
return BackstageHTTPResponse(code=BackstageHTTPResponse.API... | UserCurrentAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCurrentAPI:
def get(self, request, *args, **kwargs):
"""获取当前用户信息 ---"""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""修改当前用户 --- parameters: - name: head_img description: 图片 type: file paramType: form required: false - name: display_name description: 昵... | stack_v2_sparse_classes_75kplus_train_069934 | 18,230 | no_license | [
{
"docstring": "获取当前用户信息 ---",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "修改当前用户 --- parameters: - name: head_img description: 图片 type: file paramType: form required: false - name: display_name description: 昵称 type: string paramType: form required: f... | 2 | null | Implement the Python class `UserCurrentAPI` described below.
Class description:
Implement the UserCurrentAPI class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取当前用户信息 ---
- def patch(self, request, *args, **kwargs): 修改当前用户 --- parameters: - name: head_img description: 图片 type: file ... | Implement the Python class `UserCurrentAPI` described below.
Class description:
Implement the UserCurrentAPI class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取当前用户信息 ---
- def patch(self, request, *args, **kwargs): 修改当前用户 --- parameters: - name: head_img description: 图片 type: file ... | c50def8cde58fd4663032b860eb058302cbac6da | <|skeleton|>
class UserCurrentAPI:
def get(self, request, *args, **kwargs):
"""获取当前用户信息 ---"""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""修改当前用户 --- parameters: - name: head_img description: 图片 type: file paramType: form required: false - name: display_name description: 昵... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserCurrentAPI:
def get(self, request, *args, **kwargs):
"""获取当前用户信息 ---"""
if not request.user.id:
return BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_NOT_LOGIN_ERR).to_response()
request.user.update_wechat_mobile()
data = UserSerializer(request.u... | the_stack_v2_python_sparse | src/api/user/views.py | fan1018wen/Alpha | train | 0 | |
3dbf3b0592cc6ba568d8b47cbbd7ab01a06d2917 | [
"if not text1 or not text2:\n return 0\nm = len(text1)\nn = len(text2)\ndp = []\nfor i in range(m + 1):\n dp.append([0] * (n + 1))\nfor i in range(m):\n for j in range(n):\n '\\n To Understand this -\\n Consider the example\\n a = \"aabcde\"\\n ... | <|body_start_0|>
if not text1 or not text2:
return 0
m = len(text1)
n = len(text2)
dp = []
for i in range(m + 1):
dp.append([0] * (n + 1))
for i in range(m):
for j in range(n):
'\n To Understand this -\n ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonSubsequence1(self, text1, text2):
"""Time: O(n2) Space: O(n2)"""
<|body_0|>
def longestCommonSubsequence2(self, text1, text2):
"""Time: O(nlogn) Space: O(n+m)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not text1 or... | stack_v2_sparse_classes_75kplus_train_069935 | 2,978 | no_license | [
{
"docstring": "Time: O(n2) Space: O(n2)",
"name": "longestCommonSubsequence1",
"signature": "def longestCommonSubsequence1(self, text1, text2)"
},
{
"docstring": "Time: O(nlogn) Space: O(n+m)",
"name": "longestCommonSubsequence2",
"signature": "def longestCommonSubsequence2(self, text1,... | 2 | stack_v2_sparse_classes_30k_train_037593 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence1(self, text1, text2): Time: O(n2) Space: O(n2)
- def longestCommonSubsequence2(self, text1, text2): Time: O(nlogn) Space: O(n+m) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence1(self, text1, text2): Time: O(n2) Space: O(n2)
- def longestCommonSubsequence2(self, text1, text2): Time: O(nlogn) Space: O(n+m)
<|skeleton|>
class ... | 340868ee1d16b8b933436ca55828671d8203c0c0 | <|skeleton|>
class Solution:
def longestCommonSubsequence1(self, text1, text2):
"""Time: O(n2) Space: O(n2)"""
<|body_0|>
def longestCommonSubsequence2(self, text1, text2):
"""Time: O(nlogn) Space: O(n+m)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonSubsequence1(self, text1, text2):
"""Time: O(n2) Space: O(n2)"""
if not text1 or not text2:
return 0
m = len(text1)
n = len(text2)
dp = []
for i in range(m + 1):
dp.append([0] * (n + 1))
for i in range(m... | the_stack_v2_python_sparse | OnlineAssessmentQuestions/N15_L_1143_LCS.py | anuragpatil94/Python-Practice | train | 1 | |
1add89f6d75d682d73063b0dc570c2c76dfe9c52 | [
"super(GPRegressionModel, self).__init__(X, y, likelihood)\nbatch_dim = y.size(0)\nself.mean_module = gpytorch.means.ConstantMean(batch_shape=torch.Size([batch_dim]))\nbase_kernel = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel(ard_num_dims=embedim, batch_shape=torch.Size([batch_dim])), batch_shape=torch.... | <|body_start_0|>
super(GPRegressionModel, self).__init__(X, y, likelihood)
batch_dim = y.size(0)
self.mean_module = gpytorch.means.ConstantMean(batch_shape=torch.Size([batch_dim]))
base_kernel = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel(ard_num_dims=embedim, batch_shape=tor... | DKL GPR module | GPRegressionModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPRegressionModel:
"""DKL GPR module"""
def __init__(self, X: torch.Tensor, y: torch.Tensor, likelihood: Type[gpytorch.likelihoods.Likelihood], feature_extractor: Type[torch.nn.Module], embedim: int, grid_size: int=50) -> None:
"""Initializes DKL GP module"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_069936 | 5,867 | permissive | [
{
"docstring": "Initializes DKL GP module",
"name": "__init__",
"signature": "def __init__(self, X: torch.Tensor, y: torch.Tensor, likelihood: Type[gpytorch.likelihoods.Likelihood], feature_extractor: Type[torch.nn.Module], embedim: int, grid_size: int=50) -> None"
},
{
"docstring": "Forward pas... | 2 | stack_v2_sparse_classes_30k_train_003578 | Implement the Python class `GPRegressionModel` described below.
Class description:
DKL GPR module
Method signatures and docstrings:
- def __init__(self, X: torch.Tensor, y: torch.Tensor, likelihood: Type[gpytorch.likelihoods.Likelihood], feature_extractor: Type[torch.nn.Module], embedim: int, grid_size: int=50) -> No... | Implement the Python class `GPRegressionModel` described below.
Class description:
DKL GPR module
Method signatures and docstrings:
- def __init__(self, X: torch.Tensor, y: torch.Tensor, likelihood: Type[gpytorch.likelihoods.Likelihood], feature_extractor: Type[torch.nn.Module], embedim: int, grid_size: int=50) -> No... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class GPRegressionModel:
"""DKL GPR module"""
def __init__(self, X: torch.Tensor, y: torch.Tensor, likelihood: Type[gpytorch.likelihoods.Likelihood], feature_extractor: Type[torch.nn.Module], embedim: int, grid_size: int=50) -> None:
"""Initializes DKL GP module"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GPRegressionModel:
"""DKL GPR module"""
def __init__(self, X: torch.Tensor, y: torch.Tensor, likelihood: Type[gpytorch.likelihoods.Likelihood], feature_extractor: Type[torch.nn.Module], embedim: int, grid_size: int=50) -> None:
"""Initializes DKL GP module"""
super(GPRegressionModel, self... | the_stack_v2_python_sparse | atomai/nets/gp.py | pycroscopy/atomai | train | 157 |
8f42eb8d9d3d6c628d52930e874ac5f67242d578 | [
"db = DatabaseConnection()\nconn = db.getconnection()\ntry:\n with conn.cursor() as cursor:\n sql = \"SELECT A.user_pref, AST.assertion_type, A.parameters FROM assertions A LEFT JOIN assertions_types AST ON A.assertion_type = AST.id WHERE A.user_pref = '\" + user_pref + \"' ORDER BY A.assertion_type\"\n ... | <|body_start_0|>
db = DatabaseConnection()
conn = db.getconnection()
try:
with conn.cursor() as cursor:
sql = "SELECT A.user_pref, AST.assertion_type, A.parameters FROM assertions A LEFT JOIN assertions_types AST ON A.assertion_type = AST.id WHERE A.user_pref = '" + u... | AssertionModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssertionModel:
def getAssertionByUserPreference(self, user_pref):
""":param user_pref: :returns the assertions by user preference:"""
<|body_0|>
def getLikedPagesAndEvents(self):
""":returns list of LikedPagesAndEvents object:"""
<|body_1|>
def getAsser... | stack_v2_sparse_classes_75kplus_train_069937 | 4,087 | no_license | [
{
"docstring": ":param user_pref: :returns the assertions by user preference:",
"name": "getAssertionByUserPreference",
"signature": "def getAssertionByUserPreference(self, user_pref)"
},
{
"docstring": ":returns list of LikedPagesAndEvents object:",
"name": "getLikedPagesAndEvents",
"si... | 4 | stack_v2_sparse_classes_30k_train_038240 | Implement the Python class `AssertionModel` described below.
Class description:
Implement the AssertionModel class.
Method signatures and docstrings:
- def getAssertionByUserPreference(self, user_pref): :param user_pref: :returns the assertions by user preference:
- def getLikedPagesAndEvents(self): :returns list of ... | Implement the Python class `AssertionModel` described below.
Class description:
Implement the AssertionModel class.
Method signatures and docstrings:
- def getAssertionByUserPreference(self, user_pref): :param user_pref: :returns the assertions by user preference:
- def getLikedPagesAndEvents(self): :returns list of ... | 44a7dc53f33cb342b087d3c62149437eb655a3c7 | <|skeleton|>
class AssertionModel:
def getAssertionByUserPreference(self, user_pref):
""":param user_pref: :returns the assertions by user preference:"""
<|body_0|>
def getLikedPagesAndEvents(self):
""":returns list of LikedPagesAndEvents object:"""
<|body_1|>
def getAsser... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssertionModel:
def getAssertionByUserPreference(self, user_pref):
""":param user_pref: :returns the assertions by user preference:"""
db = DatabaseConnection()
conn = db.getconnection()
try:
with conn.cursor() as cursor:
sql = "SELECT A.user_pref, A... | the_stack_v2_python_sparse | StoryGenerator/storygenappv2/storygen/models/AssertionModel.py | hbrosas/Persona-Based-Life-Story-Generation | train | 0 | |
c334f852f8a3b7afbe81b50b8169428554f6ed98 | [
"self.tags = tags\nself.attributes = attributes\nself.styles = styles\nself.protocols = protocols\nself.strip = strip\nself.strip_comments = strip_comments\nself.bleach_params = dict(strip=self.strip, strip_comments=self.strip_comments)\nif self.tags:\n self.bleach_params['tags'] = self.tags\nif self.attributes:... | <|body_start_0|>
self.tags = tags
self.attributes = attributes
self.styles = styles
self.protocols = protocols
self.strip = strip
self.strip_comments = strip_comments
self.bleach_params = dict(strip=self.strip, strip_comments=self.strip_comments)
if self.t... | Bleach filter Sanitizes incoming untrusted HTML based on an allowed attributes list. Can be used to escape or strip markup and attributes on content coming from untrusted sources. This is for sanitizing in HTML-context only. It is not safe to use bleach output outside of such content, e.g. in javascript or html attribu... | Bleach | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bleach:
"""Bleach filter Sanitizes incoming untrusted HTML based on an allowed attributes list. Can be used to escape or strip markup and attributes on content coming from untrusted sources. This is for sanitizing in HTML-context only. It is not safe to use bleach output outside of such content, ... | stack_v2_sparse_classes_75kplus_train_069938 | 3,033 | permissive | [
{
"docstring": "Initialize the filter and set bleach config options :param tags: allowed tag list :param attributes: allowed attributes list, dict or callable :param styles: allowed styles :param protocols: allowed protocols for links :param strip: strip disallowed elements? :param strip_comments: strip comment... | 2 | stack_v2_sparse_classes_30k_train_006765 | Implement the Python class `Bleach` described below.
Class description:
Bleach filter Sanitizes incoming untrusted HTML based on an allowed attributes list. Can be used to escape or strip markup and attributes on content coming from untrusted sources. This is for sanitizing in HTML-context only. It is not safe to use ... | Implement the Python class `Bleach` described below.
Class description:
Bleach filter Sanitizes incoming untrusted HTML based on an allowed attributes list. Can be used to escape or strip markup and attributes on content coming from untrusted sources. This is for sanitizing in HTML-context only. It is not safe to use ... | c598d1af5df40fae65cf3878b8f67accbcd059b7 | <|skeleton|>
class Bleach:
"""Bleach filter Sanitizes incoming untrusted HTML based on an allowed attributes list. Can be used to escape or strip markup and attributes on content coming from untrusted sources. This is for sanitizing in HTML-context only. It is not safe to use bleach output outside of such content, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bleach:
"""Bleach filter Sanitizes incoming untrusted HTML based on an allowed attributes list. Can be used to escape or strip markup and attributes on content coming from untrusted sources. This is for sanitizing in HTML-context only. It is not safe to use bleach output outside of such content, e.g. in javas... | the_stack_v2_python_sparse | shiftschema/filters/bleach.py | projectshift/shift-schema | train | 2 |
83d8934243fca224c7e1a80afeeea578b846d601 | [
"self.random_init = cacgmm is None\nself.obs = np.einsum('mft->fmt', norm_observation(obs, axis=0))\nF, M, T = self.obs.shape\nlogger.info(f'CACGMM instance: F = {F:d}, T = {T:}, M = {M}')\nif self.random_init:\n if cgmm_init and num_classes == 2:\n cacg = CacgDistribution()\n covar = np.stack([np.... | <|body_start_0|>
self.random_init = cacgmm is None
self.obs = np.einsum('mft->fmt', norm_observation(obs, axis=0))
F, M, T = self.obs.shape
logger.info(f'CACGMM instance: F = {F:d}, T = {T:}, M = {M}')
if self.random_init:
if cgmm_init and num_classes == 2:
... | Cacgmm Trainer | CacgmmTrainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CacgmmTrainer:
"""Cacgmm Trainer"""
def __init__(self, obs, num_classes, gamma=None, cacgmm=None, cgmm_init=False):
"""Arguments: obs: mixture observation, M x F x T num_classes: number of the cluster gamma: initial gamma, K x F x T cgmm_init: init like cgmm papers"""
<|body_... | stack_v2_sparse_classes_75kplus_train_069939 | 16,663 | permissive | [
{
"docstring": "Arguments: obs: mixture observation, M x F x T num_classes: number of the cluster gamma: initial gamma, K x F x T cgmm_init: init like cgmm papers",
"name": "__init__",
"signature": "def __init__(self, obs, num_classes, gamma=None, cacgmm=None, cgmm_init=False)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_022161 | Implement the Python class `CacgmmTrainer` described below.
Class description:
Cacgmm Trainer
Method signatures and docstrings:
- def __init__(self, obs, num_classes, gamma=None, cacgmm=None, cgmm_init=False): Arguments: obs: mixture observation, M x F x T num_classes: number of the cluster gamma: initial gamma, K x ... | Implement the Python class `CacgmmTrainer` described below.
Class description:
Cacgmm Trainer
Method signatures and docstrings:
- def __init__(self, obs, num_classes, gamma=None, cacgmm=None, cgmm_init=False): Arguments: obs: mixture observation, M x F x T num_classes: number of the cluster gamma: initial gamma, K x ... | e9fd899c50e266e7101c41da646982c4d0777dce | <|skeleton|>
class CacgmmTrainer:
"""Cacgmm Trainer"""
def __init__(self, obs, num_classes, gamma=None, cacgmm=None, cgmm_init=False):
"""Arguments: obs: mixture observation, M x F x T num_classes: number of the cluster gamma: initial gamma, K x F x T cgmm_init: init like cgmm papers"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CacgmmTrainer:
"""Cacgmm Trainer"""
def __init__(self, obs, num_classes, gamma=None, cacgmm=None, cgmm_init=False):
"""Arguments: obs: mixture observation, M x F x T num_classes: number of the cluster gamma: initial gamma, K x F x T cgmm_init: init like cgmm papers"""
self.random_init = c... | the_stack_v2_python_sparse | scripts/sptk/libs/cluster.py | JusperLee/setk | train | 1 |
f6b374509921d8d7cf9269496d60af8171e82fd9 | [
"Parametre.__init__(self, 'lister', 'list')\nself.schema = ''\nself.aide_courte = 'Liste les joueurs à valider.'\nself.aide_longue = \"Cette commande liste les joueurs en attente d'une validation de description. Si la demande a été pris en charge par un autre administrateur, elle n'apparaîtra normalement pas.\"",
... | <|body_start_0|>
Parametre.__init__(self, 'lister', 'list')
self.schema = ''
self.aide_courte = 'Liste les joueurs à valider.'
self.aide_longue = "Cette commande liste les joueurs en attente d'une validation de description. Si la demande a été pris en charge par un autre administrateur, ... | Commande 'valider voir'. | PrmLister | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmLister:
"""Commande 'valider voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Para... | stack_v2_sparse_classes_75kplus_train_069940 | 3,012 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmLister` described below.
Class description:
Commande 'valider voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande | Implement the Python class `PrmLister` described below.
Class description:
Commande 'valider voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande
<|skeleton|>
class PrmLister:
"""Commande 'v... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmLister:
"""Commande 'valider voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmLister:
"""Commande 'valider voir'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'lister', 'list')
self.schema = ''
self.aide_courte = 'Liste les joueurs à valider.'
self.aide_longue = "Cette commande liste les joueurs en atten... | the_stack_v2_python_sparse | src/primaires/joueur/commandes/valider/lister.py | vincent-lg/tsunami | train | 5 |
33b6c6f27bcc2cea48c3537844e64223486a258d | [
"opens = '([{'\ncloses = ')]}'\nparstack = Stack()\nbalance = True\nfor each in s:\n if each in '([{':\n parstack.push(each)\n elif parstack.isEmpty():\n balance = False\n else:\n top = parstack.pop()\n if opens.index(top) != closes.index(each):\n balance = False\nif ... | <|body_start_0|>
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
parstack.push(each)
elif parstack.isEmpty():
balance = False
else:
top = parstack.p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def isValid_similar(self, s):
"""time O(n) space O(n) :param s: :return:"""
<|body_2|>
<|en... | stack_v2_sparse_classes_75kplus_train_069941 | 1,928 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid_stack",
"signature": "def isValid_stack(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
},
{
"docstring": "time O(n) space O(n) :param s: :return:",
"n... | 3 | stack_v2_sparse_classes_30k_train_008050 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid_stack(self, s): :type s: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool
- def isValid_similar(self, s): time O(n) space O(n) :param s: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid_stack(self, s): :type s: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool
- def isValid_similar(self, s): time O(n) space O(n) :param s: :return:
<... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
def isValid_similar(self, s):
"""time O(n) space O(n) :param s: :return:"""
<|body_2|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
parstack.push(each)
elif parstack.isEmpty():
... | the_stack_v2_python_sparse | LeetCode/Stack/20_Stack_valid_parentheses.py | XyK0907/for_work | train | 0 | |
8606406f32f0194483f0e46218dafa1d1b72e9b2 | [
"for i1, n1 in enumerate(nums):\n for i2, n2 in enumerate(nums):\n if i1 == i2:\n continue\n if n1 + n2 == target:\n return (i1, i2)",
"d = defaultdict(list)\nfor i, n in enumerate(nums):\n d[n].append(i)\nfor n, i in d.iteritems():\n i1 = i[0]\n n2 = target - n\n ... | <|body_start_0|>
for i1, n1 in enumerate(nums):
for i2, n2 in enumerate(nums):
if i1 == i2:
continue
if n1 + n2 == target:
return (i1, i2)
<|end_body_0|>
<|body_start_1|>
d = defaultdict(list)
for i, n in enumer... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_BruteForce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_HashTwoPass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def two... | stack_v2_sparse_classes_75kplus_train_069942 | 1,423 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_BruteForce",
"signature": "def twoSum_BruteForce(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_HashTwoPass",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_034136 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_BruteForce(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_HashTwoPass(self, nums, target): :type nums: List[int] :type tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_BruteForce(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_HashTwoPass(self, nums, target): :type nums: List[int] :type tar... | 5c2473f859da5efec73120256faad06ab8e0e359 | <|skeleton|>
class Solution:
def twoSum_BruteForce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_HashTwoPass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def two... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_BruteForce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i1, n1 in enumerate(nums):
for i2, n2 in enumerate(nums):
if i1 == i2:
continue
if n1 + n2 == target:
... | the_stack_v2_python_sparse | leetcode/two_sum.py | chlos/exercises_in_futility | train | 0 | |
07c40ebdfa980644c00d58e3702a0c330d417d7e | [
"params = dict(name='foo', kind=['english'])\nform = TeaSearchForm(params)\nself.assertEqual(form.is_valid(), True, form.errors.as_text())",
"params = dict()\nform = TeaSearchForm(params)\nself.assertEqual(form.is_valid(), False, form.errors.as_text())",
"params = dict(name='foo')\nform = TeaSearchForm(params)\... | <|body_start_0|>
params = dict(name='foo', kind=['english'])
form = TeaSearchForm(params)
self.assertEqual(form.is_valid(), True, form.errors.as_text())
<|end_body_0|>
<|body_start_1|>
params = dict()
form = TeaSearchForm(params)
self.assertEqual(form.is_valid(), False, ... | TeaSearchFormTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeaSearchFormTest:
def test_valid(self):
"""检查输入正常时是否会报错"""
<|body_0|>
def test_either1(self):
"""检查名称和种类都无输入时是否会报错"""
<|body_1|>
def test_either2(self):
"""检查输入名称后是否会报错"""
<|body_2|>
def test_either3(self):
"""检查输入种类后是否会报错""... | stack_v2_sparse_classes_75kplus_train_069943 | 1,779 | no_license | [
{
"docstring": "检查输入正常时是否会报错",
"name": "test_valid",
"signature": "def test_valid(self)"
},
{
"docstring": "检查名称和种类都无输入时是否会报错",
"name": "test_either1",
"signature": "def test_either1(self)"
},
{
"docstring": "检查输入名称后是否会报错",
"name": "test_either2",
"signature": "def test_e... | 4 | stack_v2_sparse_classes_30k_train_039855 | Implement the Python class `TeaSearchFormTest` described below.
Class description:
Implement the TeaSearchFormTest class.
Method signatures and docstrings:
- def test_valid(self): 检查输入正常时是否会报错
- def test_either1(self): 检查名称和种类都无输入时是否会报错
- def test_either2(self): 检查输入名称后是否会报错
- def test_either3(self): 检查输入种类后是否会报错 | Implement the Python class `TeaSearchFormTest` described below.
Class description:
Implement the TeaSearchFormTest class.
Method signatures and docstrings:
- def test_valid(self): 检查输入正常时是否会报错
- def test_either1(self): 检查名称和种类都无输入时是否会报错
- def test_either2(self): 检查输入名称后是否会报错
- def test_either3(self): 检查输入种类后是否会报错
<|... | 7bf061c0de4521601b91a85a3691dd47bd466d5c | <|skeleton|>
class TeaSearchFormTest:
def test_valid(self):
"""检查输入正常时是否会报错"""
<|body_0|>
def test_either1(self):
"""检查名称和种类都无输入时是否会报错"""
<|body_1|>
def test_either2(self):
"""检查输入名称后是否会报错"""
<|body_2|>
def test_either3(self):
"""检查输入种类后是否会报错""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeaSearchFormTest:
def test_valid(self):
"""检查输入正常时是否会报错"""
params = dict(name='foo', kind=['english'])
form = TeaSearchForm(params)
self.assertEqual(form.is_valid(), True, form.errors.as_text())
def test_either1(self):
"""检查名称和种类都无输入时是否会报错"""
params = dict... | the_stack_v2_python_sparse | src_code/10.用Jenkins持续集成/LIST10.08_cafe_apps_menu_tests.py | caiyunze/web | train | 0 | |
f9dac898269dc633b45c6f4ad48ae788b1e7d195 | [
"if not query:\n return ''\nsearch_query = '%{0}%'.format(query)\nsearch_chain = (cls.name.ilike(search_query), cls.description.ilike(search_query))\nreturn or_(*search_chain)",
"product = cls()\nform.populate_obj(product)\nproduct.business_id = business_id\nproduct.save()\nreturn True",
"form.populate_obj(s... | <|body_start_0|>
if not query:
return ''
search_query = '%{0}%'.format(query)
search_chain = (cls.name.ilike(search_query), cls.description.ilike(search_query))
return or_(*search_chain)
<|end_body_0|>
<|body_start_1|>
product = cls()
form.populate_obj(produc... | Product | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Product:
def search(cls, query):
"""Search a resource by 1 or more fields. :param query: Search query :type query: str :return: SQLAlchemy filter"""
<|body_0|>
def create_from_form(cls, business_id, form):
"""Return whether or not the product was created successfully... | stack_v2_sparse_classes_75kplus_train_069944 | 29,734 | no_license | [
{
"docstring": "Search a resource by 1 or more fields. :param query: Search query :type query: str :return: SQLAlchemy filter",
"name": "search",
"signature": "def search(cls, query)"
},
{
"docstring": "Return whether or not the product was created successfully. :return: bool",
"name": "crea... | 3 | stack_v2_sparse_classes_30k_train_004630 | Implement the Python class `Product` described below.
Class description:
Implement the Product class.
Method signatures and docstrings:
- def search(cls, query): Search a resource by 1 or more fields. :param query: Search query :type query: str :return: SQLAlchemy filter
- def create_from_form(cls, business_id, form)... | Implement the Python class `Product` described below.
Class description:
Implement the Product class.
Method signatures and docstrings:
- def search(cls, query): Search a resource by 1 or more fields. :param query: Search query :type query: str :return: SQLAlchemy filter
- def create_from_form(cls, business_id, form)... | 5e149f7a970252d37e5a1c4f68da5ecf2ced0d26 | <|skeleton|>
class Product:
def search(cls, query):
"""Search a resource by 1 or more fields. :param query: Search query :type query: str :return: SQLAlchemy filter"""
<|body_0|>
def create_from_form(cls, business_id, form):
"""Return whether or not the product was created successfully... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Product:
def search(cls, query):
"""Search a resource by 1 or more fields. :param query: Search query :type query: str :return: SQLAlchemy filter"""
if not query:
return ''
search_query = '%{0}%'.format(query)
search_chain = (cls.name.ilike(search_query), cls.descri... | the_stack_v2_python_sparse | lyfeshoppe/blueprints/business/models/business.py | himudianda/lyfeshoppe | train | 0 | |
54c4f3520d5d633aec41806b924b17ff1faf61a8 | [
"QtWidgets.QDialog.__init__(self)\nself.resize(1000, 700)\nself.topicList = QtWidgets.QListWidget()\nself.topicList.setFixedWidth(200)\nself.topicList.addItem('General Use')\nself.topicList.addItem('File Menu')\nself.topicList.addItem('Operations')\nself.topicList.currentItemChanged.connect(self.displayHelp)\nself.... | <|body_start_0|>
QtWidgets.QDialog.__init__(self)
self.resize(1000, 700)
self.topicList = QtWidgets.QListWidget()
self.topicList.setFixedWidth(200)
self.topicList.addItem('General Use')
self.topicList.addItem('File Menu')
self.topicList.addItem('Operations')
... | A help wiki to teach the user about the program and how to use it. | HelpModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpModel:
"""A help wiki to teach the user about the program and how to use it."""
def __init__(self, parent=None):
"""Initializes the UI and sets the properties."""
<|body_0|>
def help(self, parent=None):
"""Present knowledge to the user"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_069945 | 29,548 | no_license | [
{
"docstring": "Initializes the UI and sets the properties.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Present knowledge to the user",
"name": "help",
"signature": "def help(self, parent=None)"
},
{
"docstring": "Gets active selection ... | 3 | stack_v2_sparse_classes_30k_train_021955 | Implement the Python class `HelpModel` described below.
Class description:
A help wiki to teach the user about the program and how to use it.
Method signatures and docstrings:
- def __init__(self, parent=None): Initializes the UI and sets the properties.
- def help(self, parent=None): Present knowledge to the user
- ... | Implement the Python class `HelpModel` described below.
Class description:
A help wiki to teach the user about the program and how to use it.
Method signatures and docstrings:
- def __init__(self, parent=None): Initializes the UI and sets the properties.
- def help(self, parent=None): Present knowledge to the user
- ... | 1a3c5ad967472faf66236a311cc07a5128f5f911 | <|skeleton|>
class HelpModel:
"""A help wiki to teach the user about the program and how to use it."""
def __init__(self, parent=None):
"""Initializes the UI and sets the properties."""
<|body_0|>
def help(self, parent=None):
"""Present knowledge to the user"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HelpModel:
"""A help wiki to teach the user about the program and how to use it."""
def __init__(self, parent=None):
"""Initializes the UI and sets the properties."""
QtWidgets.QDialog.__init__(self)
self.resize(1000, 700)
self.topicList = QtWidgets.QListWidget()
s... | the_stack_v2_python_sparse | datatool/gui/Model.py | scottawalton/datatool | train | 0 |
953b784439b97b4ad06572397a978d7cee35867b | [
"people.sort(key=lambda x: (-x[0], x[1]))\noutput = []\nfor p in people:\n output.insert(p[1], p)\nreturn output",
"output = [people[0]]\nfor p in people[1:]:\n index = 0\n count = p[1]\n while index < len(output):\n if p[1] == 0 and p[0] < output[index][0]:\n break\n if p[0] ... | <|body_start_0|>
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
<|end_body_0|>
<|body_start_1|>
output = [people[0]]
for p in people[1:]:
index = 0
count = p[1]
wh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def reconstructQueue_failed(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_069946 | 1,891 | no_license | [
{
"docstring": ":type people: List[List[int]] :rtype: List[List[int]]",
"name": "reconstructQueue",
"signature": "def reconstructQueue(self, people)"
},
{
"docstring": ":type people: List[List[int]] :rtype: List[List[int]]",
"name": "reconstructQueue_failed",
"signature": "def reconstruc... | 2 | stack_v2_sparse_classes_30k_train_037907 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[int]]
- def reconstructQueue_failed(self, people): :type people: List[List[int]] :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[int]]
- def reconstructQueue_failed(self, people): :type people: List[List[int]] :rtype: List[... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def reconstructQueue_failed(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
def reconstructQueue_failed(self, people... | the_stack_v2_python_sparse | src/lt_406.py | oxhead/CodingYourWay | train | 0 | |
ee5d565fff69ae732bc18fc77aff830b29e453ad | [
"dic = {}\nfor n in nums:\n if n not in dic:\n dic[n] = 1\n else:\n dic[n] += 1\nres = []\nfor k, v in dic.iteritems():\n if v == 1:\n res.append(k)\nreturn res",
"nums.sort()\nres = []\ni = 0\nwhile i < len(nums) - 2:\n if nums[i] != nums[i + 1]:\n res.append(nums[i])\n ... | <|body_start_0|>
dic = {}
for n in nums:
if n not in dic:
dic[n] = 1
else:
dic[n] += 1
res = []
for k, v in dic.iteritems():
if v == 1:
res.append(k)
return res
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dic = {}
for n in nums... | stack_v2_sparse_classes_75kplus_train_069947 | 1,346 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038616 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: List[int]
- def singleNumber2(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: List[int]
- def singleNumber2(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: List[int]"""
dic = {}
for n in nums:
if n not in dic:
dic[n] = 1
else:
dic[n] += 1
res = []
for k, v in dic.iteritems():
if v == ... | the_stack_v2_python_sparse | prob260_single_number3.py | Hu-Wenchao/leetcode | train | 0 | |
d6e88c9cb2688261c61a4b8e3cbb353216084560 | [
"if not matrix:\n return False\nm = len(matrix)\nn = len(matrix[0])\nfor i in range(m):\n if target <= matrix[i][n - 1]:\n for j in range(n):\n if target == matrix[i][j]:\n return True\n break\nreturn False",
"if not matrix:\n return False\nm = len(matrix)\nn = len... | <|body_start_0|>
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
for i in range(m):
if target <= matrix[i][n - 1]:
for j in range(n):
if target == matrix[i][j]:
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_069948 | 1,371 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def search... | 2 | stack_v2_sparse_classes_30k_train_046257 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | 8d83f6f1f4123c61a2be7c369ffa964f382f6bda | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
for i in range(m):
if target <= matrix[i][n - 1]:
... | the_stack_v2_python_sparse | leetcode/74_search_2d_matrix.py | shoumu/HuntingJobPractice | train | 0 | |
f273cd69b5a75728a05c0bbf6687568db9542dd3 | [
"self.to_run = cmd_list[:]\nself.running = {}\nself.N = N\nself.cwd = cwd\nself.env = env",
"if self.N == 0:\n return True\nif len(self.running) < self.N:\n return True\nreturn False",
"while len(self.to_run) > 0 and self.under_process_limit():\n LOGGER.info('%d left to run', len(self.to_run))\n cmd... | <|body_start_0|>
self.to_run = cmd_list[:]
self.running = {}
self.N = N
self.cwd = cwd
self.env = env
<|end_body_0|>
<|body_start_1|>
if self.N == 0:
return True
if len(self.running) < self.N:
return True
return False
<|end_body_1|... | Queue up N commands from cmd_list, launching more jobs as the first finish. | QueueCommands | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueueCommands:
"""Queue up N commands from cmd_list, launching more jobs as the first finish."""
def __init__(self, cmd_list, N=0, cwd=None, env=None):
"""cmd_list is a list of elements suitable for subprocess N is the number of simultanious processes to run. 0 is all of them. WARNIN... | stack_v2_sparse_classes_75kplus_train_069949 | 3,232 | permissive | [
{
"docstring": "cmd_list is a list of elements suitable for subprocess N is the number of simultanious processes to run. 0 is all of them. WARNING: this will not work on windows (It depends on being able to pass local file descriptors to the select call with isn't supported by the Win32 API)",
"name": "__in... | 4 | stack_v2_sparse_classes_30k_val_000419 | Implement the Python class `QueueCommands` described below.
Class description:
Queue up N commands from cmd_list, launching more jobs as the first finish.
Method signatures and docstrings:
- def __init__(self, cmd_list, N=0, cwd=None, env=None): cmd_list is a list of elements suitable for subprocess N is the number o... | Implement the Python class `QueueCommands` described below.
Class description:
Queue up N commands from cmd_list, launching more jobs as the first finish.
Method signatures and docstrings:
- def __init__(self, cmd_list, N=0, cwd=None, env=None): cmd_list is a list of elements suitable for subprocess N is the number o... | e1a246dcee157b7294030683f2d50ca0405f7095 | <|skeleton|>
class QueueCommands:
"""Queue up N commands from cmd_list, launching more jobs as the first finish."""
def __init__(self, cmd_list, N=0, cwd=None, env=None):
"""cmd_list is a list of elements suitable for subprocess N is the number of simultanious processes to run. 0 is all of them. WARNIN... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QueueCommands:
"""Queue up N commands from cmd_list, launching more jobs as the first finish."""
def __init__(self, cmd_list, N=0, cwd=None, env=None):
"""cmd_list is a list of elements suitable for subprocess N is the number of simultanious processes to run. 0 is all of them. WARNING: this will ... | the_stack_v2_python_sparse | htsworkflow/util/queuecommands.py | detrout/htsworkflow | train | 0 |
bcfbde64ce11edec887e623888b7b8fb092c26a4 | [
"inputs = tf.placeholder(dtype=tf.float32, shape=[None, None, 100])\nencoder = UnidirectionalRNNEncoder()\n_, _ = encoder(inputs)\nself.assertEqual(len(encoder.trainable_variables), 2)\nhparams = {'rnn_cell': {'dropout': {'input_keep_prob': 0.5}}}\nencoder = UnidirectionalRNNEncoder(hparams=hparams)\n_, _ = encoder... | <|body_start_0|>
inputs = tf.placeholder(dtype=tf.float32, shape=[None, None, 100])
encoder = UnidirectionalRNNEncoder()
_, _ = encoder(inputs)
self.assertEqual(len(encoder.trainable_variables), 2)
hparams = {'rnn_cell': {'dropout': {'input_keep_prob': 0.5}}}
encoder = Un... | Tests :class:`~texar.tf.modules.UnidirectionalRNNEncoder` class. | UnidirectionalRNNEncoderTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnidirectionalRNNEncoderTest:
"""Tests :class:`~texar.tf.modules.UnidirectionalRNNEncoder` class."""
def test_trainable_variables(self):
"""Tests the functionality of automatically collecting trainable variables."""
<|body_0|>
def test_encode(self):
"""Tests enco... | stack_v2_sparse_classes_75kplus_train_069950 | 9,397 | permissive | [
{
"docstring": "Tests the functionality of automatically collecting trainable variables.",
"name": "test_trainable_variables",
"signature": "def test_trainable_variables(self)"
},
{
"docstring": "Tests encoding.",
"name": "test_encode",
"signature": "def test_encode(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_043452 | Implement the Python class `UnidirectionalRNNEncoderTest` described below.
Class description:
Tests :class:`~texar.tf.modules.UnidirectionalRNNEncoder` class.
Method signatures and docstrings:
- def test_trainable_variables(self): Tests the functionality of automatically collecting trainable variables.
- def test_enc... | Implement the Python class `UnidirectionalRNNEncoderTest` described below.
Class description:
Tests :class:`~texar.tf.modules.UnidirectionalRNNEncoder` class.
Method signatures and docstrings:
- def test_trainable_variables(self): Tests the functionality of automatically collecting trainable variables.
- def test_enc... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class UnidirectionalRNNEncoderTest:
"""Tests :class:`~texar.tf.modules.UnidirectionalRNNEncoder` class."""
def test_trainable_variables(self):
"""Tests the functionality of automatically collecting trainable variables."""
<|body_0|>
def test_encode(self):
"""Tests enco... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnidirectionalRNNEncoderTest:
"""Tests :class:`~texar.tf.modules.UnidirectionalRNNEncoder` class."""
def test_trainable_variables(self):
"""Tests the functionality of automatically collecting trainable variables."""
inputs = tf.placeholder(dtype=tf.float32, shape=[None, None, 100])
... | the_stack_v2_python_sparse | texar/tf/modules/encoders/rnn_encoders_test.py | arita37/texar | train | 2 |
87229d65565a028807e3a2632061d49782d05626 | [
"if root == None:\n return ''\nreturn 'X'.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])",
"s = collections.deque(data.split('X'))\n\ndef helper(datalist: collections.deque()) -> TreeNode:\n val = datalist.popleft()\n if val == '':\n return None\n root = TreeNode(i... | <|body_start_0|>
if root == None:
return ''
return 'X'.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
<|end_body_0|>
<|body_start_1|>
s = collections.deque(data.split('X'))
def helper(datalist: collections.deque()) -> TreeNode:
val ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root == Non... | stack_v2_sparse_classes_75kplus_train_069951 | 4,258 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 647fea5d2c8122468a1c018c6829b1c08717d86a | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if root == None:
return ''
return 'X'.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
def deserialize(self, data: str) -> TreeNode:
"""Decod... | the_stack_v2_python_sparse | LeetCode/monthly_challenges/october_2020/9_serialize_and_deserialize_bst.py | jinurajan/Datastructures | train | 0 | |
9b6082ffd3f049160eaef8211dc4adb4422dfcb1 | [
"super(self.__class__, self).__init__(parent)\nself.setupUi(self)\nself.abstractDb = abstractDb\nself.dBLineEdit.setText(dbName)\nself.dBLineEdit.setReadOnly(True)\nself.viewTypeDict = {0: 'VIEW', 1: 'MATERIALIZED VIEW'}\nself.inheritanceType = {0: 'FROM ONLY', 1: 'FROM'}",
"createViewClause = self.viewTypeDict[s... | <|body_start_0|>
super(self.__class__, self).__init__(parent)
self.setupUi(self)
self.abstractDb = abstractDb
self.dBLineEdit.setText(dbName)
self.dBLineEdit.setReadOnly(True)
self.viewTypeDict = {0: 'VIEW', 1: 'MATERIALIZED VIEW'}
self.inheritanceType = {0: 'FROM... | CreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateView:
def __init__(self, abstractDb, dbName, parent=None):
"""Constructor"""
<|body_0|>
def on_buttonBox_accepted(self):
"""Creates view with resolved domain values"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(self.__class__, self).__... | stack_v2_sparse_classes_75kplus_train_069952 | 3,084 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, abstractDb, dbName, parent=None)"
},
{
"docstring": "Creates view with resolved domain values",
"name": "on_buttonBox_accepted",
"signature": "def on_buttonBox_accepted(self)"
}
] | 2 | null | Implement the Python class `CreateView` described below.
Class description:
Implement the CreateView class.
Method signatures and docstrings:
- def __init__(self, abstractDb, dbName, parent=None): Constructor
- def on_buttonBox_accepted(self): Creates view with resolved domain values | Implement the Python class `CreateView` described below.
Class description:
Implement the CreateView class.
Method signatures and docstrings:
- def __init__(self, abstractDb, dbName, parent=None): Constructor
- def on_buttonBox_accepted(self): Creates view with resolved domain values
<|skeleton|>
class CreateView:
... | edff378f356db3c0577ce34e618c5ae493d296ba | <|skeleton|>
class CreateView:
def __init__(self, abstractDb, dbName, parent=None):
"""Constructor"""
<|body_0|>
def on_buttonBox_accepted(self):
"""Creates view with resolved domain values"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateView:
def __init__(self, abstractDb, dbName, parent=None):
"""Constructor"""
super(self.__class__, self).__init__(parent)
self.setupUi(self)
self.abstractDb = abstractDb
self.dBLineEdit.setText(dbName)
self.dBLineEdit.setReadOnly(True)
self.viewTyp... | the_stack_v2_python_sparse | ServerTools/createView.py | euriconicacio/DsgTools | train | 0 | |
7c17d30c4143a4114fb3b82a14a6c6f6c6818b94 | [
"url = reverse('api:log-list')\ndata = {'message': 'Anon test', 'severity': 0, 'category': 'test'}\nresponse = self.client.post(url, data)\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nentry = LogEntry.objects.filter(user__isnull=True)[0]\nself.assertEqual(entry.message, data['message'])\nself.a... | <|body_start_0|>
url = reverse('api:log-list')
data = {'message': 'Anon test', 'severity': 0, 'category': 'test'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
entry = LogEntry.objects.filter(user__isnull=True)[0]
s... | LoggerTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggerTestCase:
def test_anonymous(self):
"""Anonymous users are allowed to write, but not view, log entries."""
<|body_0|>
def test_regular_user(self):
"""Regular users can write and view their own log entries."""
<|body_1|>
def test_admin_user(self):
... | stack_v2_sparse_classes_75kplus_train_069953 | 3,603 | permissive | [
{
"docstring": "Anonymous users are allowed to write, but not view, log entries.",
"name": "test_anonymous",
"signature": "def test_anonymous(self)"
},
{
"docstring": "Regular users can write and view their own log entries.",
"name": "test_regular_user",
"signature": "def test_regular_us... | 3 | stack_v2_sparse_classes_30k_test_001705 | Implement the Python class `LoggerTestCase` described below.
Class description:
Implement the LoggerTestCase class.
Method signatures and docstrings:
- def test_anonymous(self): Anonymous users are allowed to write, but not view, log entries.
- def test_regular_user(self): Regular users can write and view their own l... | Implement the Python class `LoggerTestCase` described below.
Class description:
Implement the LoggerTestCase class.
Method signatures and docstrings:
- def test_anonymous(self): Anonymous users are allowed to write, but not view, log entries.
- def test_regular_user(self): Regular users can write and view their own l... | 9baa530f2f3405322f74ccc145641148f253341b | <|skeleton|>
class LoggerTestCase:
def test_anonymous(self):
"""Anonymous users are allowed to write, but not view, log entries."""
<|body_0|>
def test_regular_user(self):
"""Regular users can write and view their own log entries."""
<|body_1|>
def test_admin_user(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoggerTestCase:
def test_anonymous(self):
"""Anonymous users are allowed to write, but not view, log entries."""
url = reverse('api:log-list')
data = {'message': 'Anon test', 'severity': 0, 'category': 'test'}
response = self.client.post(url, data)
self.assertEqual(resp... | the_stack_v2_python_sparse | logger/tests.py | City-of-Turku/munpalvelut_backend | train | 0 | |
bc7590102fdf816dfca5e4929e990bdee48b6857 | [
"if not isinstance(config_files, list):\n config_files = [config_files]\nself.config_files = config_files\nself.parser = parser\nself.config = config\nself._config = None",
"if isinstance(self.config, type):\n self._config = self.config()\nelse:\n self._config = self.config\nif not self.config_files:\n ... | <|body_start_0|>
if not isinstance(config_files, list):
config_files = [config_files]
self.config_files = config_files
self.parser = parser
self.config = config
self._config = None
<|end_body_0|>
<|body_start_1|>
if isinstance(self.config, type):
... | Lazily load the config when requested. | ConfigLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigLoader:
"""Lazily load the config when requested."""
def __init__(self, config_files, config=Config, parser=Parser()):
""":param config Config The config instance or class to load data into. Must support update which accepts an iterable of (key, value). :param parser Parser The... | stack_v2_sparse_classes_75kplus_train_069954 | 11,045 | no_license | [
{
"docstring": ":param config Config The config instance or class to load data into. Must support update which accepts an iterable of (key, value). :param parser Parser The parser to use to parse the config files. Must be a callable and return an iterable of (key, value). :param config_files list<string> A list... | 3 | null | Implement the Python class `ConfigLoader` described below.
Class description:
Lazily load the config when requested.
Method signatures and docstrings:
- def __init__(self, config_files, config=Config, parser=Parser()): :param config Config The config instance or class to load data into. Must support update which acce... | Implement the Python class `ConfigLoader` described below.
Class description:
Lazily load the config when requested.
Method signatures and docstrings:
- def __init__(self, config_files, config=Config, parser=Parser()): :param config Config The config instance or class to load data into. Must support update which acce... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class ConfigLoader:
"""Lazily load the config when requested."""
def __init__(self, config_files, config=Config, parser=Parser()):
""":param config Config The config instance or class to load data into. Must support update which accepts an iterable of (key, value). :param parser Parser The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigLoader:
"""Lazily load the config when requested."""
def __init__(self, config_files, config=Config, parser=Parser()):
""":param config Config The config instance or class to load data into. Must support update which accepts an iterable of (key, value). :param parser Parser The parser to us... | the_stack_v2_python_sparse | Products/ZenUtils/config.py | zenoss/zenoss-prodbin | train | 27 |
dc2d6b4697dc3f5cd3f5cedd307052254563004a | [
"self.approach = approach\nself.axis = axis\nself.top = top\nself.bottom = bottom\nself.height = height\nself.width = width\nself.offsets = offsets\nself.binormal = cross(approach, axis) if binormal is None else binormal\nself.center = 0.5 * bottom + 0.5 * top\nself.fingerNormals = (self.binormal, -self.binormal)\n... | <|body_start_0|>
self.approach = approach
self.axis = axis
self.top = top
self.bottom = bottom
self.height = height
self.width = width
self.offsets = offsets
self.binormal = cross(approach, axis) if binormal is None else binormal
self.center = 0.5 ... | Grasp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grasp:
def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None):
"""Creates a Grasp object with everything needed."""
<|body_0|>
def Flip(self):
"""Creates a new grasp flipped 180 degrees about the approach direct... | stack_v2_sparse_classes_75kplus_train_069955 | 1,492 | permissive | [
{
"docstring": "Creates a Grasp object with everything needed.",
"name": "__init__",
"signature": "def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None)"
},
{
"docstring": "Creates a new grasp flipped 180 degrees about the approach directi... | 2 | stack_v2_sparse_classes_30k_train_001413 | Implement the Python class `Grasp` described below.
Class description:
Implement the Grasp class.
Method signatures and docstrings:
- def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None): Creates a Grasp object with everything needed.
- def Flip(self): Creates... | Implement the Python class `Grasp` described below.
Class description:
Implement the Grasp class.
Method signatures and docstrings:
- def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None): Creates a Grasp object with everything needed.
- def Flip(self): Creates... | 15cdf2a6d5a255ecb78488ca75657af559d0c2da | <|skeleton|>
class Grasp:
def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None):
"""Creates a Grasp object with everything needed."""
<|body_0|>
def Flip(self):
"""Creates a new grasp flipped 180 degrees about the approach direct... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grasp:
def __init__(self, approach, axis, top, bottom, height, width, offsets, binormal=None, score=None, image=None):
"""Creates a Grasp object with everything needed."""
self.approach = approach
self.axis = axis
self.top = top
self.bottom = bottom
self.height ... | the_stack_v2_python_sparse | simulation/python2/grasp.py | mgualti/PickAndPlace | train | 14 | |
9975bbfd79aed9e53294e6a95fd827ede96cfb5c | [
"self.surface = surface\nself.pos = 0\nself.own_surface = None",
"surface_width, surface_height = surface.get_size()\nif self.own_surface is None:\n layer_width, layer_height = self.surface.get_size()\n self.own_surface = pg.Surface((ceil(surface_width / layer_width) * layer_width, layer_height))\n self.... | <|body_start_0|>
self.surface = surface
self.pos = 0
self.own_surface = None
<|end_body_0|>
<|body_start_1|>
surface_width, surface_height = surface.get_size()
if self.own_surface is None:
layer_width, layer_height = self.surface.get_size()
self.own_surfa... | Class for the parallax scrolling of a single layer. | ParallaxScrollingLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallaxScrollingLayer:
"""Class for the parallax scrolling of a single layer."""
def __init__(self, surface):
"""@param surface: the sprite of the layer. @type surface: pygame.Surface @rtype: None"""
<|body_0|>
def draw(self, surface, dx, per_mvm):
"""Draw a sin... | stack_v2_sparse_classes_75kplus_train_069956 | 18,482 | no_license | [
{
"docstring": "@param surface: the sprite of the layer. @type surface: pygame.Surface @rtype: None",
"name": "__init__",
"signature": "def __init__(self, surface)"
},
{
"docstring": "Draw a single layer on the surface. @param surface: The surface the layer will be displayed on. @type surface: p... | 2 | stack_v2_sparse_classes_30k_train_045029 | Implement the Python class `ParallaxScrollingLayer` described below.
Class description:
Class for the parallax scrolling of a single layer.
Method signatures and docstrings:
- def __init__(self, surface): @param surface: the sprite of the layer. @type surface: pygame.Surface @rtype: None
- def draw(self, surface, dx,... | Implement the Python class `ParallaxScrollingLayer` described below.
Class description:
Class for the parallax scrolling of a single layer.
Method signatures and docstrings:
- def __init__(self, surface): @param surface: the sprite of the layer. @type surface: pygame.Surface @rtype: None
- def draw(self, surface, dx,... | 37b6e20d0343d53162b7174b18437ad9d9b04d26 | <|skeleton|>
class ParallaxScrollingLayer:
"""Class for the parallax scrolling of a single layer."""
def __init__(self, surface):
"""@param surface: the sprite of the layer. @type surface: pygame.Surface @rtype: None"""
<|body_0|>
def draw(self, surface, dx, per_mvm):
"""Draw a sin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParallaxScrollingLayer:
"""Class for the parallax scrolling of a single layer."""
def __init__(self, surface):
"""@param surface: the sprite of the layer. @type surface: pygame.Surface @rtype: None"""
self.surface = surface
self.pos = 0
self.own_surface = None
def dra... | the_stack_v2_python_sparse | src/map.py | charlie-j/MPRI-SE-Click-Run | train | 0 |
112d1f530a36304b0cef209e0c516f7be15b7911 | [
"ra = self._NewRunAttributes()\nwith self.assertRaises(AssertionError):\n ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET)\nra.RegisterBoardAttrs(self.BOARD, self.TARGET)\nself.assertFalse(ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET))\nra.SetBoardParallel(self.BATTR, 'TheValue', self.BOARD, s... | <|body_start_0|>
ra = self._NewRunAttributes()
with self.assertRaises(AssertionError):
ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET)
ra.RegisterBoardAttrs(self.BOARD, self.TARGET)
self.assertFalse(ra.HasBoardParallel(self.BATTR, self.BOARD, self.TARGET))
ra... | Test the RunAttributes class. | RunAttributesTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunAttributesTest:
"""Test the RunAttributes class."""
def testRegisterBoardTarget(self):
"""Test behavior of attributes before and after registering board target."""
<|body_0|>
def testSetGet(self):
"""Test simple set/get of regular and parallel run attributes."... | stack_v2_sparse_classes_75kplus_train_069957 | 24,848 | permissive | [
{
"docstring": "Test behavior of attributes before and after registering board target.",
"name": "testRegisterBoardTarget",
"signature": "def testRegisterBoardTarget(self)"
},
{
"docstring": "Test simple set/get of regular and parallel run attributes.",
"name": "testSetGet",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_006917 | Implement the Python class `RunAttributesTest` described below.
Class description:
Test the RunAttributes class.
Method signatures and docstrings:
- def testRegisterBoardTarget(self): Test behavior of attributes before and after registering board target.
- def testSetGet(self): Test simple set/get of regular and para... | Implement the Python class `RunAttributesTest` described below.
Class description:
Test the RunAttributes class.
Method signatures and docstrings:
- def testRegisterBoardTarget(self): Test behavior of attributes before and after registering board target.
- def testSetGet(self): Test simple set/get of regular and para... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class RunAttributesTest:
"""Test the RunAttributes class."""
def testRegisterBoardTarget(self):
"""Test behavior of attributes before and after registering board target."""
<|body_0|>
def testSetGet(self):
"""Test simple set/get of regular and parallel run attributes."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunAttributesTest:
"""Test the RunAttributes class."""
def testRegisterBoardTarget(self):
"""Test behavior of attributes before and after registering board target."""
ra = self._NewRunAttributes()
with self.assertRaises(AssertionError):
ra.HasBoardParallel(self.BATTR, ... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/cbuildbot_run_unittest.py | metux/chromium-suckless | train | 5 |
dcb6183f960faaf186f21ccad580cba644c5a288 | [
"obj = Invoice.objects.select_for_update().filter(slug=slug).first()\nif obj is None:\n raise Http404()\nclient_ip, is_routable = get_client_ip(self.request)\nself.check_object_permissions(request, obj)\nserializer = InvoiceRetrieveUpdateSerializer(obj, many=False)\nreturn Response(data=serializer.data, status=s... | <|body_start_0|>
obj = Invoice.objects.select_for_update().filter(slug=slug).first()
if obj is None:
raise Http404()
client_ip, is_routable = get_client_ip(self.request)
self.check_object_permissions(request, obj)
serializer = InvoiceRetrieveUpdateSerializer(obj, many... | InvoiceRetrieveDestroyAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = Invoice.objects.select_for_update().filter(slug=slug).first(... | stack_v2_sparse_classes_75kplus_train_069958 | 7,213 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, slug=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040959 | Implement the Python class `InvoiceRetrieveDestroyAPIView` described below.
Class description:
Implement the InvoiceRetrieveDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, pk=None): Update | Implement the Python class `InvoiceRetrieveDestroyAPIView` described below.
Class description:
Implement the InvoiceRetrieveDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, pk=None): Update
<|skeleton|>
class InvoiceRetrieveDestroyAPIView:... | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | <|skeleton|>
class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
obj = Invoice.objects.select_for_update().filter(slug=slug).first()
if obj is None:
raise Http404()
client_ip, is_routable = get_client_ip(self.request)
self.check_object_permis... | the_stack_v2_python_sparse | mikaponics/ecommerce/views/resources/invoice_views.py | mikaponics/mikaponics-back | train | 4 | |
5841a7d19df584cd34445c179ae5405c77b636af | [
"self.root_depth = p['root_depth']\nself.fine_radius = p['fine_radius']\nself.root_cond = p['root_cond']\nself.RAI = p['RAI_LAI_multiplier'] * LAImax\nself.rad = self.RAI * RootDistribution(p['beta'], dz_soil, p['root_depth'])\nself.ix = np.where(np.isfinite(self.rad))\nself.dz = dz_soil[self.ix]\nself.h_root = 0.0... | <|body_start_0|>
self.root_depth = p['root_depth']
self.fine_radius = p['fine_radius']
self.root_cond = p['root_cond']
self.RAI = p['RAI_LAI_multiplier'] * LAImax
self.rad = self.RAI * RootDistribution(p['beta'], dz_soil, p['root_depth'])
self.ix = np.where(np.isfinite(se... | Describes roots of planttype. | RootUptake | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootUptake:
"""Describes roots of planttype."""
def __init__(self, p, dz_soil, LAImax):
"""Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root a... | stack_v2_sparse_classes_75kplus_train_069959 | 3,776 | no_license | [
{
"docstring": "Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root area index (RAI = 2*LAImax) 'fine_radius': fine root radius [m] 'radial_K': maximum bulk root membrane c... | 2 | stack_v2_sparse_classes_30k_train_010234 | Implement the Python class `RootUptake` described below.
Class description:
Describes roots of planttype.
Method signatures and docstrings:
- def __init__(self, p, dz_soil, LAImax): Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution mod... | Implement the Python class `RootUptake` described below.
Class description:
Describes roots of planttype.
Method signatures and docstrings:
- def __init__(self, p, dz_soil, LAImax): Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution mod... | c662ad355af798b5036c3b080dafcb39728b969c | <|skeleton|>
class RootUptake:
"""Describes roots of planttype."""
def __init__(self, p, dz_soil, LAImax):
"""Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RootUptake:
"""Describes roots of planttype."""
def __init__(self, p, dz_soil, LAImax):
"""Initializes rootuptake object. Args: p (dict): 'root_depth': depth of rooting zone [m] 'beta': shape parameter for root distribution model 'RAI_LAI_multiplier': multiplier for total fine root area index (RA... | the_stack_v2_python_sparse | canopy/planttype/rootzone.py | zmoon/pyAPES_skeleton | train | 0 |
1f7dd256ca46d9c9296e36d7aca43081699616f8 | [
"self.wode.LaunchTopic()\nself.common.waitUntilNotPresent(By.NAME, '加载中…', timeout=60)\nself.wode.deleteTopics()\nself.common.back()\nsleep(2)\nself.common.back()\nself.sendTopic.launch()\nself.driver.find_element_by_class_name('android.widget.EditText').send_keys('测试请勿回复')\nself.common.touchText('选择主题:')\nself.com... | <|body_start_0|>
self.wode.LaunchTopic()
self.common.waitUntilNotPresent(By.NAME, '加载中…', timeout=60)
self.wode.deleteTopics()
self.common.back()
sleep(2)
self.common.back()
self.sendTopic.launch()
self.driver.find_element_by_class_name('android.widget.Edi... | 发话题测试 | SendTopicTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendTopicTest:
"""发话题测试"""
def test_sendTopic1(self):
"""普通话题"""
<|body_0|>
def test_sendTopic2(self):
"""发车型投票"""
<|body_1|>
def test_sendTopic3(self):
"""发车款投票"""
<|body_2|>
def test_sendTopic4(self):
"""发观点投票"""
... | stack_v2_sparse_classes_75kplus_train_069960 | 6,960 | no_license | [
{
"docstring": "普通话题",
"name": "test_sendTopic1",
"signature": "def test_sendTopic1(self)"
},
{
"docstring": "发车型投票",
"name": "test_sendTopic2",
"signature": "def test_sendTopic2(self)"
},
{
"docstring": "发车款投票",
"name": "test_sendTopic3",
"signature": "def test_sendTopic... | 4 | null | Implement the Python class `SendTopicTest` described below.
Class description:
发话题测试
Method signatures and docstrings:
- def test_sendTopic1(self): 普通话题
- def test_sendTopic2(self): 发车型投票
- def test_sendTopic3(self): 发车款投票
- def test_sendTopic4(self): 发观点投票 | Implement the Python class `SendTopicTest` described below.
Class description:
发话题测试
Method signatures and docstrings:
- def test_sendTopic1(self): 普通话题
- def test_sendTopic2(self): 发车型投票
- def test_sendTopic3(self): 发车款投票
- def test_sendTopic4(self): 发观点投票
<|skeleton|>
class SendTopicTest:
"""发话题测试"""
def ... | 3de7f300f8984aeff87632325afecd7d145e50aa | <|skeleton|>
class SendTopicTest:
"""发话题测试"""
def test_sendTopic1(self):
"""普通话题"""
<|body_0|>
def test_sendTopic2(self):
"""发车型投票"""
<|body_1|>
def test_sendTopic3(self):
"""发车款投票"""
<|body_2|>
def test_sendTopic4(self):
"""发观点投票"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendTopicTest:
"""发话题测试"""
def test_sendTopic1(self):
"""普通话题"""
self.wode.LaunchTopic()
self.common.waitUntilNotPresent(By.NAME, '加载中…', timeout=60)
self.wode.deleteTopics()
self.common.back()
sleep(2)
self.common.back()
self.sendTopic.laun... | the_stack_v2_python_sparse | src/script/test_sendTopic.py | xulishuang/qichebaojiadaquan | train | 0 |
362027481ab0c88f1cdaee5515780ced0dabd4b0 | [
"self.wordDict = {}\nfor i, w in enumerate(words):\n if w in self.wordDict:\n self.wordDict[w].append(i)\n else:\n self.wordDict[w] = [i]",
"index1 = self.wordDict[word1]\nindex2 = self.wordDict[word2]\ni = j = 0\nminDist = sys.maxsize\nwhile i < len(index1) and j < len(index2):\n idx1 = in... | <|body_start_0|>
self.wordDict = {}
for i, w in enumerate(words):
if w in self.wordDict:
self.wordDict[w].append(i)
else:
self.wordDict[w] = [i]
<|end_body_0|>
<|body_start_1|>
index1 = self.wordDict[word1]
index2 = self.wordDict[w... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wordDict = {}
for i, w i... | stack_v2_sparse_classes_75kplus_train_069961 | 2,135 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032142 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 7a459e9742958e63be8886874904e5ab2489411a | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.wordDict = {}
for i, w in enumerate(words):
if w in self.wordDict:
self.wordDict[w].append(i)
else:
self.wordDict[w] = [i]
def shortest(self, word1, w... | the_stack_v2_python_sparse | Medium/244.py | Hellofafar/Leetcode | train | 6 | |
d92d1335ab81547b0d46628f25d7083d1349cda3 | [
"super().__init__()\nassert kernel_size == 3 or kernel_size == 5\nself.in_channels = in_channels\nself.hidden_channels = hidden_channels\nkernel_size = (kernel_size, kernel_size)\nsame_padding = tuple([size // 2 for size in kernel_size])\nself.l = L\nself.gammma_x = nn.Conv2d(in_channels, out_channels=32, kernel_si... | <|body_start_0|>
super().__init__()
assert kernel_size == 3 or kernel_size == 5
self.in_channels = in_channels
self.hidden_channels = hidden_channels
kernel_size = (kernel_size, kernel_size)
same_padding = tuple([size // 2 for size in kernel_size])
self.l = L
... | TrajGRUCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrajGRUCell:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int=5, L: int=5):
"""具体看论文吧"""
<|body_0|>
def __flow_generator(self, x: Tensor, h: Tensor) -> Tensor:
""":param x: :param h: :return:"""
<|body_1|>
def forward(self, x: ... | stack_v2_sparse_classes_75kplus_train_069962 | 6,931 | permissive | [
{
"docstring": "具体看论文吧",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int=5, L: int=5)"
},
{
"docstring": ":param x: :param h: :return:",
"name": "__flow_generator",
"signature": "def __flow_generator(self, x: Tensor, h: Tensor... | 3 | stack_v2_sparse_classes_30k_train_011592 | Implement the Python class `TrajGRUCell` described below.
Class description:
Implement the TrajGRUCell class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int=5, L: int=5): 具体看论文吧
- def __flow_generator(self, x: Tensor, h: Tensor) -> Tensor: :param x: :pa... | Implement the Python class `TrajGRUCell` described below.
Class description:
Implement the TrajGRUCell class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int=5, L: int=5): 具体看论文吧
- def __flow_generator(self, x: Tensor, h: Tensor) -> Tensor: :param x: :pa... | d8079d6ceb3a41a06552bb3d88298327d0645d57 | <|skeleton|>
class TrajGRUCell:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int=5, L: int=5):
"""具体看论文吧"""
<|body_0|>
def __flow_generator(self, x: Tensor, h: Tensor) -> Tensor:
""":param x: :param h: :return:"""
<|body_1|>
def forward(self, x: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrajGRUCell:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int=5, L: int=5):
"""具体看论文吧"""
super().__init__()
assert kernel_size == 3 or kernel_size == 5
self.in_channels = in_channels
self.hidden_channels = hidden_channels
kernel_size =... | the_stack_v2_python_sparse | study/models/TrajGRU/TrajGRUCell.py | hechentao/STudy | train | 0 | |
8744f8038739ffe44e1a7e22b5f73e71354f9929 | [
"if self._async_current_entries():\n return self.async_abort(reason='single_instance_allowed')\nerrors = {}\nfields = OrderedDict()\nfields[vol.Required(CONF_USB_PATH)] = str\nfields[vol.Optional(CONF_RADIO_TYPE, default='ezsp')] = vol.In(RadioType.list())\nif user_input is not None:\n database = os.path.join... | <|body_start_0|>
if self._async_current_entries():
return self.async_abort(reason='single_instance_allowed')
errors = {}
fields = OrderedDict()
fields[vol.Required(CONF_USB_PATH)] = str
fields[vol.Optional(CONF_RADIO_TYPE, default='ezsp')] = vol.In(RadioType.list())
... | Handle a config flow. | ZhaFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZhaFlowHandler:
"""Handle a config flow."""
async def async_step_user(self, user_input=None):
"""Handle a zha config flow start."""
<|body_0|>
async def async_step_import(self, import_info):
"""Handle a zha config import."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_069963 | 2,521 | permissive | [
{
"docstring": "Handle a zha config flow start.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Handle a zha config import.",
"name": "async_step_import",
"signature": "async def async_step_import(self, import_info)"
}
] | 2 | null | Implement the Python class `ZhaFlowHandler` described below.
Class description:
Handle a config flow.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a zha config flow start.
- async def async_step_import(self, import_info): Handle a zha config import. | Implement the Python class `ZhaFlowHandler` described below.
Class description:
Handle a config flow.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a zha config flow start.
- async def async_step_import(self, import_info): Handle a zha config import.
<|skeleton|>
class ... | 10dd34f62248ee822b941ce7c707b774bbdff378 | <|skeleton|>
class ZhaFlowHandler:
"""Handle a config flow."""
async def async_step_user(self, user_input=None):
"""Handle a zha config flow start."""
<|body_0|>
async def async_step_import(self, import_info):
"""Handle a zha config import."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZhaFlowHandler:
"""Handle a config flow."""
async def async_step_user(self, user_input=None):
"""Handle a zha config flow start."""
if self._async_current_entries():
return self.async_abort(reason='single_instance_allowed')
errors = {}
fields = OrderedDict()
... | the_stack_v2_python_sparse | homeassistant/components/zha/config_flow.py | peternijssen/home-assistant | train | 2 |
5fbd68af984389002bff9781159e716886918b07 | [
"self.width = width\nself.height = height\nself.letter_count = letter_count\nself.bytes_per_letter = (floor((self.height - 1) / 8) + 1) * self.width\nself.letters = bytearray(self.bytes_per_letter * self.letter_count)\nself.__load_xglcd_font(bitmap)",
"bytes_per_letter = self.bytes_per_letter\nself.letters = byte... | <|body_start_0|>
self.width = width
self.height = height
self.letter_count = letter_count
self.bytes_per_letter = (floor((self.height - 1) / 8) + 1) * self.width
self.letters = bytearray(self.bytes_per_letter * self.letter_count)
self.__load_xglcd_font(bitmap)
<|end_body_... | Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprises letter height Note: Font files can be generated with the free version of Mi... | BitmapFont | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitmapFont:
"""Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprises letter height Note: Font files can be... | stack_v2_sparse_classes_75kplus_train_069964 | 4,491 | no_license | [
{
"docstring": "Constructor for X-GLCD Font object. Args: path (string): Full path of font file width (int): Maximum width in pixels of each letter height (int): Height in pixels of each letter start_letter (int): First ACII letter. Default is 32. letter_count (int): Total number of letters. Default is 96.",
... | 4 | stack_v2_sparse_classes_30k_train_010254 | Implement the Python class `BitmapFont` described below.
Class description:
Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprise... | Implement the Python class `BitmapFont` described below.
Class description:
Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprise... | 70332b522ad9d71fb0e50be81c2b648fa8ceef8f | <|skeleton|>
class BitmapFont:
"""Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprises letter height Note: Font files can be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BitmapFont:
"""Font data in X-GLCD format. Attributes: letters: A bytearray of letters (columns consist of bytes) width: Maximum pixel width of font height: Pixel height of font start_letter: ASCII number of first letter height_bytes: How many bytes comprises letter height Note: Font files can be generated wi... | the_stack_v2_python_sparse | old_tv/bitmap_font.py | hsxsix/ESP-Project | train | 1 |
b51a0cd5c2ca9ea26f070d89aa81212fc2d6b2ba | [
"cls.driver = browser(switch=MyConfig('browser').config)\ncls.wait = MyConfig('page_loading_wait').config\ncls.sql = MyDB()\ncls.log = Logger()\nif cls.RE_LOGIN:\n account = cls.LOGIN_INFO['account']\n password = cls.LOGIN_INFO['password']\n company = cls.LOGIN_INFO['company']\n if account and password:... | <|body_start_0|>
cls.driver = browser(switch=MyConfig('browser').config)
cls.wait = MyConfig('page_loading_wait').config
cls.sql = MyDB()
cls.log = Logger()
if cls.RE_LOGIN:
account = cls.LOGIN_INFO['account']
password = cls.LOGIN_INFO['password']
... | UnitTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTests:
def setUpClass(cls):
"""判断类下面是否需要重新请求账号登录"""
<|body_0|>
def tearDownClass(cls):
"""清除配置文件中的token"""
<|body_1|>
def setUp(self):
"""用例初始化"""
<|body_2|>
def tearDown(self):
"""用例结束"""
<|body_3|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_069965 | 3,426 | no_license | [
{
"docstring": "判断类下面是否需要重新请求账号登录",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "清除配置文件中的token",
"name": "tearDownClass",
"signature": "def tearDownClass(cls)"
},
{
"docstring": "用例初始化",
"name": "setUp",
"signature": "def setUp(self)"
},
... | 4 | null | Implement the Python class `UnitTests` described below.
Class description:
Implement the UnitTests class.
Method signatures and docstrings:
- def setUpClass(cls): 判断类下面是否需要重新请求账号登录
- def tearDownClass(cls): 清除配置文件中的token
- def setUp(self): 用例初始化
- def tearDown(self): 用例结束 | Implement the Python class `UnitTests` described below.
Class description:
Implement the UnitTests class.
Method signatures and docstrings:
- def setUpClass(cls): 判断类下面是否需要重新请求账号登录
- def tearDownClass(cls): 清除配置文件中的token
- def setUp(self): 用例初始化
- def tearDown(self): 用例结束
<|skeleton|>
class UnitTests:
def setUp... | 86bb051e62abdf2ed5bbdbea4c9008a6c1f49060 | <|skeleton|>
class UnitTests:
def setUpClass(cls):
"""判断类下面是否需要重新请求账号登录"""
<|body_0|>
def tearDownClass(cls):
"""清除配置文件中的token"""
<|body_1|>
def setUp(self):
"""用例初始化"""
<|body_2|>
def tearDown(self):
"""用例结束"""
<|body_3|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnitTests:
def setUpClass(cls):
"""判断类下面是否需要重新请求账号登录"""
cls.driver = browser(switch=MyConfig('browser').config)
cls.wait = MyConfig('page_loading_wait').config
cls.sql = MyDB()
cls.log = Logger()
if cls.RE_LOGIN:
account = cls.LOGIN_INFO['account']
... | the_stack_v2_python_sparse | model/MyUnitTest.py | yushu1987/UI | train | 0 | |
835febc9eb9874ad6a211bfaf1b3205420dc0ac5 | [
"super().__init__(hass, LOGGER, name=f'{valve_controller_uid}_{api_name}', update_interval=DEFAULT_UPDATE_INTERVAL)\nself._api_coro = api_coro\nself._api_lock = api_lock\nself._client = client\nself.config_entry = entry\nself.signal_reboot_requested = SIGNAL_REBOOT_REQUESTED.format(self.config_entry.entry_id)",
"... | <|body_start_0|>
super().__init__(hass, LOGGER, name=f'{valve_controller_uid}_{api_name}', update_interval=DEFAULT_UPDATE_INTERVAL)
self._api_coro = api_coro
self._api_lock = api_lock
self._client = client
self.config_entry = entry
self.signal_reboot_requested = SIGNAL_RE... | Define an extended DataUpdateCoordinator with some Guardian goodies. | GuardianDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuardianDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator with some Guardian goodies."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, client: Client, api_name: str, api_coro: Callable[..., Awaitable], api_lock: asyncio.Lock, valve_controller_uid: str) -> No... | stack_v2_sparse_classes_75kplus_train_069966 | 3,767 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, client: Client, api_name: str, api_coro: Callable[..., Awaitable], api_lock: asyncio.Lock, valve_controller_uid: str) -> None"
},
{
"docstring": "Execute a \"locked\" AP... | 3 | null | Implement the Python class `GuardianDataUpdateCoordinator` described below.
Class description:
Define an extended DataUpdateCoordinator with some Guardian goodies.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, client: Client, api_name: str, api_coro: Callable[..., ... | Implement the Python class `GuardianDataUpdateCoordinator` described below.
Class description:
Define an extended DataUpdateCoordinator with some Guardian goodies.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, client: Client, api_name: str, api_coro: Callable[..., ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class GuardianDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator with some Guardian goodies."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, client: Client, api_name: str, api_coro: Callable[..., Awaitable], api_lock: asyncio.Lock, valve_controller_uid: str) -> No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GuardianDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator with some Guardian goodies."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, client: Client, api_name: str, api_coro: Callable[..., Awaitable], api_lock: asyncio.Lock, valve_controller_uid: str) -> None:
"... | the_stack_v2_python_sparse | homeassistant/components/guardian/util.py | home-assistant/core | train | 35,501 |
fe562d7ac4da2a2da9688a3d2e4a78a790565a36 | [
"if not isinstance(other, Tag):\n return -1\nif other.name != self.name:\n return cmp(self.name, other.name)\nif other.attributes != self.attributes:\n return cmp(self.attributes, other.attributes)\nif other.content != self.content:\n return cmp(self.content, other.content)\nreturn 0",
"fragments = []... | <|body_start_0|>
if not isinstance(other, Tag):
return -1
if other.name != self.name:
return cmp(self.name, other.name)
if other.attributes != self.attributes:
return cmp(self.attributes, other.attributes)
if other.content != self.content:
... | Represents a particular tag within a document | Tag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""Represents a particular tag within a document"""
def __cmp__(self, other):
"""Compare this tag to another"""
<|body_0|>
def __repr__(self):
"""Create a decent representation of this tag"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_75kplus_train_069967 | 2,813 | no_license | [
{
"docstring": "Compare this tag to another",
"name": "__cmp__",
"signature": "def __cmp__(self, other)"
},
{
"docstring": "Create a decent representation of this tag",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036624 | Implement the Python class `Tag` described below.
Class description:
Represents a particular tag within a document
Method signatures and docstrings:
- def __cmp__(self, other): Compare this tag to another
- def __repr__(self): Create a decent representation of this tag | Implement the Python class `Tag` described below.
Class description:
Represents a particular tag within a document
Method signatures and docstrings:
- def __cmp__(self, other): Compare this tag to another
- def __repr__(self): Create a decent representation of this tag
<|skeleton|>
class Tag:
"""Represents a par... | 496fc33954072147c379b8a9a1957bb04fd93670 | <|skeleton|>
class Tag:
"""Represents a particular tag within a document"""
def __cmp__(self, other):
"""Compare this tag to another"""
<|body_0|>
def __repr__(self):
"""Create a decent representation of this tag"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tag:
"""Represents a particular tag within a document"""
def __cmp__(self, other):
"""Compare this tag to another"""
if not isinstance(other, Tag):
return -1
if other.name != self.name:
return cmp(self.name, other.name)
if other.attributes != self.a... | the_stack_v2_python_sparse | basicproperty/xmlencoder.py | eshikvtumane/basicproperty | train | 0 |
81385f597df86e222bdc96960f470c797d9052ab | [
"context = super(AddressListView, self).get_context_data(**kwargs)\naccount = context['view'].request.user.account\ncontext['account'] = account\ncontext['addresses'] = ShippingInfo.objects.filter(resident=account)\nset_basic_context(context, 'account')\nreturn context",
"data = request.POST\naddresses = {}\nfor ... | <|body_start_0|>
context = super(AddressListView, self).get_context_data(**kwargs)
account = context['view'].request.user.account
context['account'] = account
context['addresses'] = ShippingInfo.objects.filter(resident=account)
set_basic_context(context, 'account')
return... | Change your main shipping address. | AddressListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressListView:
"""Change your main shipping address."""
def get_context_data(self, **kwargs):
"""Add context for active page."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Change out main address."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_069968 | 34,812 | permissive | [
{
"docstring": "Add context for active page.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Change out main address.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `AddressListView` described below.
Class description:
Change your main shipping address.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Add context for active page.
- def post(self, request, *args, **kwargs): Change out main address. | Implement the Python class `AddressListView` described below.
Class description:
Change your main shipping address.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Add context for active page.
- def post(self, request, *args, **kwargs): Change out main address.
<|skeleton|>
class AddressLis... | 52f46381eafa9410d8e9c759366ef7490dcb1de9 | <|skeleton|>
class AddressListView:
"""Change your main shipping address."""
def get_context_data(self, **kwargs):
"""Add context for active page."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Change out main address."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressListView:
"""Change your main shipping address."""
def get_context_data(self, **kwargs):
"""Add context for active page."""
context = super(AddressListView, self).get_context_data(**kwargs)
account = context['view'].request.user.account
context['account'] = account
... | the_stack_v2_python_sparse | RVFS/account/views.py | cahudson94/Raven-Valley-Forge-Shop | train | 2 |
9a35afae423209cfec3ae2addeb6094e1e53c32d | [
"album_vote = get_object_or_404(AlbumVote, pk=album_vote_id)\nserializer = AlbumVoteSerializerUpdate(album_vote, data=request.data, context={'request': request}, partial=True)\nif serializer.is_valid():\n serializer.save()\n return Response(AlbumVoteSerializer(serializer.instance).data)\nreturn Response(seria... | <|body_start_0|>
album_vote = get_object_or_404(AlbumVote, pk=album_vote_id)
serializer = AlbumVoteSerializerUpdate(album_vote, data=request.data, context={'request': request}, partial=True)
if serializer.is_valid():
serializer.save()
return Response(AlbumVoteSerializer(s... | AlbumVoteDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbumVoteDetail:
def patch(request, album_vote_id):
"""Update album vote"""
<|body_0|>
def delete(request, album_vote_id):
"""Delete album vote"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
album_vote = get_object_or_404(AlbumVote, pk=album_vote_i... | stack_v2_sparse_classes_75kplus_train_069969 | 1,773 | permissive | [
{
"docstring": "Update album vote",
"name": "patch",
"signature": "def patch(request, album_vote_id)"
},
{
"docstring": "Delete album vote",
"name": "delete",
"signature": "def delete(request, album_vote_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018623 | Implement the Python class `AlbumVoteDetail` described below.
Class description:
Implement the AlbumVoteDetail class.
Method signatures and docstrings:
- def patch(request, album_vote_id): Update album vote
- def delete(request, album_vote_id): Delete album vote | Implement the Python class `AlbumVoteDetail` described below.
Class description:
Implement the AlbumVoteDetail class.
Method signatures and docstrings:
- def patch(request, album_vote_id): Update album vote
- def delete(request, album_vote_id): Delete album vote
<|skeleton|>
class AlbumVoteDetail:
def patch(req... | b93fa2fea8d45df9f19c3c58037e59dad4981921 | <|skeleton|>
class AlbumVoteDetail:
def patch(request, album_vote_id):
"""Update album vote"""
<|body_0|>
def delete(request, album_vote_id):
"""Delete album vote"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlbumVoteDetail:
def patch(request, album_vote_id):
"""Update album vote"""
album_vote = get_object_or_404(AlbumVote, pk=album_vote_id)
serializer = AlbumVoteSerializerUpdate(album_vote, data=request.data, context={'request': request}, partial=True)
if serializer.is_valid():
... | the_stack_v2_python_sparse | v1/votes/views/album_vote.py | lawiz22/PLOUC-Backend-master | train | 0 | |
62c979ba2cda1fbeb0732c7adf42819a5705a442 | [
"import _thread\nimport time\n_thread.start_new_thread(self.run, ())",
"from .spywxpythonthread import WxImageServer\nself.app = WxImageServer(0)\nself.app.MainLoop()",
"from . import spywxpythonthread\nevt = spywxpythonthread.view_imageRequest(rgb, **kwargs)\nspywxpythonthread.wx.PostEvent(self.app.catcher, ev... | <|body_start_0|>
import _thread
import time
_thread.start_new_thread(self.run, ())
<|end_body_0|>
<|body_start_1|>
from .spywxpythonthread import WxImageServer
self.app = WxImageServer(0)
self.app.MainLoop()
<|end_body_1|>
<|body_start_2|>
from . import spywxpyt... | SpyWxPythonThreadStarter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpyWxPythonThreadStarter:
def start(self):
"""Starts the GUI thread."""
<|body_0|>
def run(self):
"""This is the first function executed in the wxWindows thread. It creates the wxApp and starts the main event loop."""
<|body_1|>
def view(self, rgb, **kwa... | stack_v2_sparse_classes_75kplus_train_069970 | 1,790 | permissive | [
{
"docstring": "Starts the GUI thread.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "This is the first function executed in the wxWindows thread. It creates the wxApp and starts the main event loop.",
"name": "run",
"signature": "def run(self)"
},
{
"docstr... | 3 | null | Implement the Python class `SpyWxPythonThreadStarter` described below.
Class description:
Implement the SpyWxPythonThreadStarter class.
Method signatures and docstrings:
- def start(self): Starts the GUI thread.
- def run(self): This is the first function executed in the wxWindows thread. It creates the wxApp and sta... | Implement the Python class `SpyWxPythonThreadStarter` described below.
Class description:
Implement the SpyWxPythonThreadStarter class.
Method signatures and docstrings:
- def start(self): Starts the GUI thread.
- def run(self): This is the first function executed in the wxWindows thread. It creates the wxApp and sta... | 0659ee71614455d99a80ffd4f5f5edd8d032608c | <|skeleton|>
class SpyWxPythonThreadStarter:
def start(self):
"""Starts the GUI thread."""
<|body_0|>
def run(self):
"""This is the first function executed in the wxWindows thread. It creates the wxApp and starts the main event loop."""
<|body_1|>
def view(self, rgb, **kwa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpyWxPythonThreadStarter:
def start(self):
"""Starts the GUI thread."""
import _thread
import time
_thread.start_new_thread(self.run, ())
def run(self):
"""This is the first function executed in the wxWindows thread. It creates the wxApp and starts the main event l... | the_stack_v2_python_sparse | spectral/graphics/spywxpython.py | spectralpython/spectral | train | 527 | |
fb3a66e34d2f97babe8ba58218caaf57c5d6d188 | [
"self.root = root\nself.st = []\nself.cur = root",
"while self.cur:\n self.st.append(self.cur)\n self.cur = self.cur.left\ncur = self.st.pop()\nself.cur = cur.right\nreturn cur.val",
"if len(self.st) or self.cur:\n return True\nelse:\n return False"
] | <|body_start_0|>
self.root = root
self.st = []
self.cur = root
<|end_body_0|>
<|body_start_1|>
while self.cur:
self.st.append(self.cur)
self.cur = self.cur.left
cur = self.st.pop()
self.cur = cur.right
return cur.val
<|end_body_1|>
<|body... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def next(self):
"""@return the next smallest number :rtype: int"""
<|body_1|>
def hasNext(self):
"""@return whether we have a next smallest number :rtype: bool"""
... | stack_v2_sparse_classes_75kplus_train_069971 | 1,346 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": "@return the next smallest number :rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": "@return whether we have a next smallest number :rt... | 3 | null | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def next(self): @return the next smallest number :rtype: int
- def hasNext(self): @return whether we have a next smallest n... | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def next(self): @return the next smallest number :rtype: int
- def hasNext(self): @return whether we have a next smallest n... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def next(self):
"""@return the next smallest number :rtype: int"""
<|body_1|>
def hasNext(self):
"""@return whether we have a next smallest number :rtype: bool"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.root = root
self.st = []
self.cur = root
def next(self):
"""@return the next smallest number :rtype: int"""
while self.cur:
self.st.append(self.cur)
self.cur = se... | the_stack_v2_python_sparse | leetcode/173.py | liuweilin17/algorithm | train | 3 | |
012d9539c0cf3c67689a6d5a07d111799e2f62c5 | [
"obj = self.new_obj\nteacher_id = obj.teacher_id\ncourse_id = obj.course_id\ncourse = Courses.objects.get(id=course_id)\nteacher = Teacher.objects.get(id=teacher_id)\nteacher.total_money -= course.teacher_money\nteacher.total_hour -= course.total_time\nobj.save()\nteacher.save()",
"obj = self.obj\nteacher_id = ob... | <|body_start_0|>
obj = self.new_obj
teacher_id = obj.teacher_id
course_id = obj.course_id
course = Courses.objects.get(id=course_id)
teacher = Teacher.objects.get(id=teacher_id)
teacher.total_money -= course.teacher_money
teacher.total_hour -= course.total_time
... | TeacherAbsencesAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeacherAbsencesAdmin:
def save_model(self):
"""重写save_models根据缺勤更新学生的课时和课时费"""
<|body_0|>
def delete_model(self):
"""重写delete_model根据缺勤更新教师的课时和课时费"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = self.new_obj
teacher_id = obj.teacher_id... | stack_v2_sparse_classes_75kplus_train_069972 | 1,462 | no_license | [
{
"docstring": "重写save_models根据缺勤更新学生的课时和课时费",
"name": "save_model",
"signature": "def save_model(self)"
},
{
"docstring": "重写delete_model根据缺勤更新教师的课时和课时费",
"name": "delete_model",
"signature": "def delete_model(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014832 | Implement the Python class `TeacherAbsencesAdmin` described below.
Class description:
Implement the TeacherAbsencesAdmin class.
Method signatures and docstrings:
- def save_model(self): 重写save_models根据缺勤更新学生的课时和课时费
- def delete_model(self): 重写delete_model根据缺勤更新教师的课时和课时费 | Implement the Python class `TeacherAbsencesAdmin` described below.
Class description:
Implement the TeacherAbsencesAdmin class.
Method signatures and docstrings:
- def save_model(self): 重写save_models根据缺勤更新学生的课时和课时费
- def delete_model(self): 重写delete_model根据缺勤更新教师的课时和课时费
<|skeleton|>
class TeacherAbsencesAdmin:
... | 8471ad19d6f766c1415e5dd74d7a5a277d1b7ee2 | <|skeleton|>
class TeacherAbsencesAdmin:
def save_model(self):
"""重写save_models根据缺勤更新学生的课时和课时费"""
<|body_0|>
def delete_model(self):
"""重写delete_model根据缺勤更新教师的课时和课时费"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeacherAbsencesAdmin:
def save_model(self):
"""重写save_models根据缺勤更新学生的课时和课时费"""
obj = self.new_obj
teacher_id = obj.teacher_id
course_id = obj.course_id
course = Courses.objects.get(id=course_id)
teacher = Teacher.objects.get(id=teacher_id)
teacher.total_... | the_stack_v2_python_sparse | man_sys/absteachers/adminx.py | arvinyuan1991/stu_man_sys | train | 4 | |
15ad9302add3d0cf4531d040dcad5d673035a237 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceComplianceUserOverview()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'configurationVersion': lambda n: setattr(self, 'configuration_version', n.get_int_value()), 'errorCo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceComplianceUserOverview()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'configurationVer... | DeviceComplianceUserOverview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceComplianceUserOverview:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceUserOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value... | stack_v2_sparse_classes_75kplus_train_069973 | 3,535 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DeviceComplianceUserOverview",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | stack_v2_sparse_classes_30k_train_048310 | Implement the Python class `DeviceComplianceUserOverview` described below.
Class description:
Implement the DeviceComplianceUserOverview class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceUserOverview: Creates a new instance of the a... | Implement the Python class `DeviceComplianceUserOverview` described below.
Class description:
Implement the DeviceComplianceUserOverview class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceUserOverview: Creates a new instance of the a... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceComplianceUserOverview:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceUserOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceComplianceUserOverview:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceComplianceUserOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | the_stack_v2_python_sparse | msgraph/generated/models/device_compliance_user_overview.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a0eb22135144e0779e936792db0055b39baafd37 | [
"params = base.get_params(None, locals())\nrequest = http.Request('GET', self.get_url(), params)\nreturn (request, parsers.parse_json)",
"params = base.get_params(None, locals())\nurl = '{0}/sort'.format(self.get_url())\nrequest = http.Request('PUT', url, params)\nreturn (request, parsers.parse_json)"
] | <|body_start_0|>
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_params(None, locals())
url = '{0}/sort'.format(self.get_url())
request =... | SupportQueues | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportQueues:
def get(self, page=None, per_page=None):
"""Fetch all the support queues. :var page: Where should paging start. If left as `None`, the first page is returned. :vartype page: int :var per_page: How many objects sould be returned. If left as `None`, 10 objects are returned. ... | stack_v2_sparse_classes_75kplus_train_069974 | 1,315 | permissive | [
{
"docstring": "Fetch all the support queues. :var page: Where should paging start. If left as `None`, the first page is returned. :vartype page: int :var per_page: How many objects sould be returned. If left as `None`, 10 objects are returned. :vartype per_page: int",
"name": "get",
"signature": "def g... | 2 | null | Implement the Python class `SupportQueues` described below.
Class description:
Implement the SupportQueues class.
Method signatures and docstrings:
- def get(self, page=None, per_page=None): Fetch all the support queues. :var page: Where should paging start. If left as `None`, the first page is returned. :vartype pag... | Implement the Python class `SupportQueues` described below.
Class description:
Implement the SupportQueues class.
Method signatures and docstrings:
- def get(self, page=None, per_page=None): Fetch all the support queues. :var page: Where should paging start. If left as `None`, the first page is returned. :vartype pag... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class SupportQueues:
def get(self, page=None, per_page=None):
"""Fetch all the support queues. :var page: Where should paging start. If left as `None`, the first page is returned. :vartype page: int :var per_page: How many objects sould be returned. If left as `None`, 10 objects are returned. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SupportQueues:
def get(self, page=None, per_page=None):
"""Fetch all the support queues. :var page: Where should paging start. If left as `None`, the first page is returned. :vartype page: int :var per_page: How many objects sould be returned. If left as `None`, 10 objects are returned. :vartype per_p... | the_stack_v2_python_sparse | libsaas/services/uservoice/support_queues.py | piplcom/libsaas | train | 1 | |
ce0051d6d7d1be360862cda89b738f7f972c66a6 | [
"widget = self._widget\nif not widget:\n return self._default_size\nreturn widget.GetMaxSize()",
"if self._widget is not widget:\n self.Clear(deleteWindows=False)\n old = self._widget\n if old:\n old.Hide()\n self._widget = widget\n if widget:\n widget.Show()\n res = super(w... | <|body_start_0|>
widget = self._widget
if not widget:
return self._default_size
return widget.GetMaxSize()
<|end_body_0|>
<|body_start_1|>
if self._widget is not widget:
self.Clear(deleteWindows=False)
old = self._widget
if old:
... | A custom wx Sizer for sizing a single child widget. There can only be one widget in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed). | wxSingleWidgetSizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wxSingleWidgetSizer:
"""A custom wx Sizer for sizing a single child widget. There can only be one widget in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed)."""
def CalcMax(self):
"""A method to compute ... | stack_v2_sparse_classes_75kplus_train_069975 | 2,025 | permissive | [
{
"docstring": "A method to compute the maximum size allowed by the sizer. This is not a native wx sizer method, but is included for convenience.",
"name": "CalcMax",
"signature": "def CalcMax(self)"
},
{
"docstring": "Adds the given widget to the sizer, removing the old widget if present. The o... | 4 | stack_v2_sparse_classes_30k_train_004963 | Implement the Python class `wxSingleWidgetSizer` described below.
Class description:
A custom wx Sizer for sizing a single child widget. There can only be one widget in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed).
Method signatures ... | Implement the Python class `wxSingleWidgetSizer` described below.
Class description:
A custom wx Sizer for sizing a single child widget. There can only be one widget in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed).
Method signatures ... | 15c20b035a73187e8e66fa20a43c3a4372d008bd | <|skeleton|>
class wxSingleWidgetSizer:
"""A custom wx Sizer for sizing a single child widget. There can only be one widget in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed)."""
def CalcMax(self):
"""A method to compute ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class wxSingleWidgetSizer:
"""A custom wx Sizer for sizing a single child widget. There can only be one widget in this sizer at a time and it should be added via the .Add(...) method. Old items will be removed automatically (but not destroyed)."""
def CalcMax(self):
"""A method to compute the maximum s... | the_stack_v2_python_sparse | enaml/wx/wx_single_widget_sizer.py | ContinuumIO/enaml | train | 2 |
1303bd42bcca07856cde5011e0d5af7d052a9990 | [
"if n <= 0:\n return False\nfrom math import log10\nreturn log10(n) / log10(3) % 1 == 0",
"if n <= 0:\n return False\nwhile n % 3 == 0:\n n /= 3\nreturn n == 1"
] | <|body_start_0|>
if n <= 0:
return False
from math import log10
return log10(n) / log10(3) % 1 == 0
<|end_body_0|>
<|body_start_1|>
if n <= 0:
return False
while n % 3 == 0:
n /= 3
return n == 1
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfThree(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfThreeLoop(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n <= 0:
return False
from math imp... | stack_v2_sparse_classes_75kplus_train_069976 | 581 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfThree",
"signature": "def isPowerOfThree(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfThreeLoop",
"signature": "def isPowerOfThreeLoop(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004385 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfThree(self, n): :type n: int :rtype: bool
- def isPowerOfThreeLoop(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfThree(self, n): :type n: int :rtype: bool
- def isPowerOfThreeLoop(self, n): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isPowerOfThree(self, n)... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def isPowerOfThree(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfThreeLoop(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPowerOfThree(self, n):
""":type n: int :rtype: bool"""
if n <= 0:
return False
from math import log10
return log10(n) / log10(3) % 1 == 0
def isPowerOfThreeLoop(self, n):
""":type n: int :rtype: bool"""
if n <= 0:
ret... | the_stack_v2_python_sparse | top_interview_questions/easy_collection/math/power_of_three.py | hwc1824/LeetCodeSolution | train | 0 | |
e36813df0dbe438c99c81ca98fe8de64f91a4025 | [
"data = dict(hash=self.hash, parent=self.parent, kind=self.kind.value)\ndb.hset(join(ARTEFACTS, self.hash), mapping=data)\nhash_save(db, self.hash)",
"pipe: Pipeline = db.pipeline(transaction=False)\npipe.exists(join(ARTEFACTS, hash))\npipe.hgetall(join(ARTEFACTS, hash))\nexists, data = pipe.execute()\nif not exi... | <|body_start_0|>
data = dict(hash=self.hash, parent=self.parent, kind=self.kind.value)
db.hset(join(ARTEFACTS, self.hash), mapping=data)
hash_save(db, self.hash)
<|end_body_0|>
<|body_start_1|>
pipe: Pipeline = db.pipeline(transaction=False)
pipe.exists(join(ARTEFACTS, hash))
... | Artefacts are the main data structure. | Artefact | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Artefact:
"""Artefacts are the main data structure."""
def put(self: Artefact[Any], db: Redis[bytes]) -> None:
"""Save an artefact to Redis."""
<|body_0|>
def grab(cls: Type[Artefact[T]], db: Redis[bytes], hash: hash_t) -> Artefact[T]:
"""Grab an artefact from th... | stack_v2_sparse_classes_75kplus_train_069977 | 15,760 | permissive | [
{
"docstring": "Save an artefact to Redis.",
"name": "put",
"signature": "def put(self: Artefact[Any], db: Redis[bytes]) -> None"
},
{
"docstring": "Grab an artefact from the Redis store.",
"name": "grab",
"signature": "def grab(cls: Type[Artefact[T]], db: Redis[bytes], hash: hash_t) -> ... | 2 | stack_v2_sparse_classes_30k_train_048099 | Implement the Python class `Artefact` described below.
Class description:
Artefacts are the main data structure.
Method signatures and docstrings:
- def put(self: Artefact[Any], db: Redis[bytes]) -> None: Save an artefact to Redis.
- def grab(cls: Type[Artefact[T]], db: Redis[bytes], hash: hash_t) -> Artefact[T]: Gra... | Implement the Python class `Artefact` described below.
Class description:
Artefacts are the main data structure.
Method signatures and docstrings:
- def put(self: Artefact[Any], db: Redis[bytes]) -> None: Save an artefact to Redis.
- def grab(cls: Type[Artefact[T]], db: Redis[bytes], hash: hash_t) -> Artefact[T]: Gra... | 12656f49420e9062edb9dd4c34aa18bcc94880f1 | <|skeleton|>
class Artefact:
"""Artefacts are the main data structure."""
def put(self: Artefact[Any], db: Redis[bytes]) -> None:
"""Save an artefact to Redis."""
<|body_0|>
def grab(cls: Type[Artefact[T]], db: Redis[bytes], hash: hash_t) -> Artefact[T]:
"""Grab an artefact from th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Artefact:
"""Artefacts are the main data structure."""
def put(self: Artefact[Any], db: Redis[bytes]) -> None:
"""Save an artefact to Redis."""
data = dict(hash=self.hash, parent=self.parent, kind=self.kind.value)
db.hset(join(ARTEFACTS, self.hash), mapping=data)
hash_save... | the_stack_v2_python_sparse | src/funsies/_graph.py | Leticia-maria/funsies | train | 0 |
0956654df916daed62cfaa1b2f71405d263746fb | [
"self._consensus_address = '0x0000000000000000000000000000000000001003'\nself.contract_name = 'Consensus'\nself.gasPrice = 300000000\nself.client = transaction_common.TransactionCommon(self._consensus_address, contract_path, self.contract_name)",
"common.check_nodeId(nodeId)\nfn_name = 'addSealer'\nfn_args = [nod... | <|body_start_0|>
self._consensus_address = '0x0000000000000000000000000000000000001003'
self.contract_name = 'Consensus'
self.gasPrice = 300000000
self.client = transaction_common.TransactionCommon(self._consensus_address, contract_path, self.contract_name)
<|end_body_0|>
<|body_start_1... | implementation of ConsensusPrecompile | ConsensusPrecompile | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsensusPrecompile:
"""implementation of ConsensusPrecompile"""
def __init__(self, contract_path):
"""init the address for Consensus contract"""
<|body_0|>
def addSealer(self, nodeId):
"""addSealer"""
<|body_1|>
def addObserver(self, nodeId):
... | stack_v2_sparse_classes_75kplus_train_069978 | 2,141 | permissive | [
{
"docstring": "init the address for Consensus contract",
"name": "__init__",
"signature": "def __init__(self, contract_path)"
},
{
"docstring": "addSealer",
"name": "addSealer",
"signature": "def addSealer(self, nodeId)"
},
{
"docstring": "addObserver",
"name": "addObserver"... | 4 | stack_v2_sparse_classes_30k_train_053849 | Implement the Python class `ConsensusPrecompile` described below.
Class description:
implementation of ConsensusPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for Consensus contract
- def addSealer(self, nodeId): addSealer
- def addObserver(self, nodeId): addObserve... | Implement the Python class `ConsensusPrecompile` described below.
Class description:
implementation of ConsensusPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for Consensus contract
- def addSealer(self, nodeId): addSealer
- def addObserver(self, nodeId): addObserve... | 5fa6cc416b604de4bbd0d2407f36ed286d67a792 | <|skeleton|>
class ConsensusPrecompile:
"""implementation of ConsensusPrecompile"""
def __init__(self, contract_path):
"""init the address for Consensus contract"""
<|body_0|>
def addSealer(self, nodeId):
"""addSealer"""
<|body_1|>
def addObserver(self, nodeId):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsensusPrecompile:
"""implementation of ConsensusPrecompile"""
def __init__(self, contract_path):
"""init the address for Consensus contract"""
self._consensus_address = '0x0000000000000000000000000000000000001003'
self.contract_name = 'Consensus'
self.gasPrice = 3000000... | the_stack_v2_python_sparse | client/precompile/consensus/consensus_precompile.py | FISCO-BCOS/python-sdk | train | 68 |
fbc4c32688e15ca7b992f2096e5184ec6874175d | [
"File_content = ''\nFile_path = os.path.join(temp_file_dir, file_name)\ntry:\n Request_response = get(url, stream=True)\n if os.path.isdir(temp_file_dir):\n with open(File_path, 'wb') as File_obj:\n for File_chunk in Request_response.iter_content(chunk_size=128):\n File_obj.wr... | <|body_start_0|>
File_content = ''
File_path = os.path.join(temp_file_dir, file_name)
try:
Request_response = get(url, stream=True)
if os.path.isdir(temp_file_dir):
with open(File_path, 'wb') as File_obj:
for File_chunk in Request_respo... | wrapper class for file functions using http requests | Requests_Filling_Wrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requests_Filling_Wrapper:
"""wrapper class for file functions using http requests"""
def stream_read_file(self, url, temp_file_dir, file_name):
"""read a file by streaming it from a url, save to a temporary file,read into a memory and delete the file Args :param url: url to the json ... | stack_v2_sparse_classes_75kplus_train_069979 | 9,923 | no_license | [
{
"docstring": "read a file by streaming it from a url, save to a temporary file,read into a memory and delete the file Args :param url: url to the json file :param temp_file_dir: path to the temporay file directory :param file_name: name.ext of the file Returns: :rtype string|byte: string or byte content of th... | 2 | stack_v2_sparse_classes_30k_train_035291 | Implement the Python class `Requests_Filling_Wrapper` described below.
Class description:
wrapper class for file functions using http requests
Method signatures and docstrings:
- def stream_read_file(self, url, temp_file_dir, file_name): read a file by streaming it from a url, save to a temporary file,read into a mem... | Implement the Python class `Requests_Filling_Wrapper` described below.
Class description:
wrapper class for file functions using http requests
Method signatures and docstrings:
- def stream_read_file(self, url, temp_file_dir, file_name): read a file by streaming it from a url, save to a temporary file,read into a mem... | eb8c55a4279b9c3f08e7f7af468731e7007450b0 | <|skeleton|>
class Requests_Filling_Wrapper:
"""wrapper class for file functions using http requests"""
def stream_read_file(self, url, temp_file_dir, file_name):
"""read a file by streaming it from a url, save to a temporary file,read into a memory and delete the file Args :param url: url to the json ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Requests_Filling_Wrapper:
"""wrapper class for file functions using http requests"""
def stream_read_file(self, url, temp_file_dir, file_name):
"""read a file by streaming it from a url, save to a temporary file,read into a memory and delete the file Args :param url: url to the json file :param t... | the_stack_v2_python_sparse | libs/utils/core_util_filling.py | Baronchibuikem/HealthInsuredbackend | train | 0 |
fe4e6bf449c1fe5dc2ba80f6102ab13fe10fbeaf | [
"super().__init__(self.PARAMS, parameters)\nself.column_name = parameters['column_name']\nself.remove_values = parameters['remove_values']",
"df_new = df.copy()\nif self.column_name not in df_new.columns:\n return df_new\nfor value in self.remove_values:\n df_new = df_new.loc[df_new[self.column_name] != val... | <|body_start_0|>
super().__init__(self.PARAMS, parameters)
self.column_name = parameters['column_name']
self.remove_values = parameters['remove_values']
<|end_body_0|>
<|body_start_1|>
df_new = df.copy()
if self.column_name not in df_new.columns:
return df_new
... | Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values** (*list*): The values to test for row removal. | RemoveRowsOp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveRowsOp:
"""Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values** (*list*): The values to test for row removal."""
def __init__(self, parameters):
"""Constructor for remove rows operation.... | stack_v2_sparse_classes_75kplus_train_069980 | 1,988 | permissive | [
{
"docstring": "Constructor for remove rows operation. Parameters: parameters (dict): Dictionary with the parameter values for required and optional parameters. :raises KeyError: - If a required parameter is missing. - If an unexpected parameter is provided. :raises TypeError: - If a parameter has the wrong typ... | 2 | null | Implement the Python class `RemoveRowsOp` described below.
Class description:
Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values** (*list*): The values to test for row removal.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `RemoveRowsOp` described below.
Class description:
Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values** (*list*): The values to test for row removal.
Method signatures and docstrings:
- def __init__(... | b871cae44bdf0ee68c688562c3b0af50b93343f5 | <|skeleton|>
class RemoveRowsOp:
"""Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values** (*list*): The values to test for row removal."""
def __init__(self, parameters):
"""Constructor for remove rows operation.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoveRowsOp:
"""Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values** (*list*): The values to test for row removal."""
def __init__(self, parameters):
"""Constructor for remove rows operation. Parameters: ... | the_stack_v2_python_sparse | hed/tools/remodeling/operations/remove_rows_op.py | hed-standard/hed-python | train | 5 |
444c933da2aa8a9ba07727fc24653096bed66861 | [
"self.device = device\nself.conn_cmd = conn_cmd\nself.device.conn_cmd = conn_cmd",
"bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])\ntry:\n result = self.device.expect(['assword:', 'ser2net.*\\r\\n', 'OpenGear Serial Server', 'to access the port escape menu'])\ne... | <|body_start_0|>
self.device = device
self.conn_cmd = conn_cmd
self.device.conn_cmd = conn_cmd
<|end_body_0|>
<|body_start_1|>
bft_pexpect_helper.spawn.__init__(self.device, command='/bin/bash', args=['-c', self.conn_cmd])
try:
result = self.device.expect(['assword:'... | The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board. | Ser2NetConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ser2NetConnection:
"""The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board."""
def __init__(self, device=None, conn_cmd=None, **kwarg... | stack_v2_sparse_classes_75kplus_train_069981 | 2,190 | permissive | [
{
"docstring": "This method initializes the class instance to open a pexpect session. :param device: device to connect, defaults to None :type device: object :param conn_cmd: conn_cmd to connect to device, defaults to None :type conn_cmd: string :param **kwargs: args to be used :type **kwargs: dict",
"name"... | 3 | stack_v2_sparse_classes_30k_train_031031 | Implement the Python class `Ser2NetConnection` described below.
Class description:
The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.
Method signatures and ... | Implement the Python class `Ser2NetConnection` described below.
Class description:
The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board.
Method signatures and ... | 100521fde1fb67536682cafecc2f91a6e2e8a6f8 | <|skeleton|>
class Ser2NetConnection:
"""The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board."""
def __init__(self, device=None, conn_cmd=None, **kwarg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ser2NetConnection:
"""The ser2net daemon allows telnet and tcp sessions to be established with a unit's serial ports. If a board is connected serially to a server running ser2net daemon, this class can be used to connect to the board."""
def __init__(self, device=None, conn_cmd=None, **kwargs):
"... | the_stack_v2_python_sparse | boardfarm/devices/ser2net_connection.py | mattsm/boardfarm | train | 45 |
532241318986147adab5052bda0bb2a276486b01 | [
"self.num_points = num_points\n'the all ran-walk is start with(0,0)'\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_direction = choice([1, -1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([1, -1])\n ... | <|body_start_0|>
self.num_points = num_points
'the all ran-walk is start with(0,0)'
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1... | a class to create random walk data | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""a class to create random walk data"""
def __init__(self, num_points=5000):
"""initialization random walk attributes"""
<|body_0|>
def fill_walk(self):
"""count all of the ran-walk points"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069982 | 1,271 | no_license | [
{
"docstring": "initialization random walk attributes",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "count all of the ran-walk points",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | null | Implement the Python class `RandomWalk` described below.
Class description:
a class to create random walk data
Method signatures and docstrings:
- def __init__(self, num_points=5000): initialization random walk attributes
- def fill_walk(self): count all of the ran-walk points | Implement the Python class `RandomWalk` described below.
Class description:
a class to create random walk data
Method signatures and docstrings:
- def __init__(self, num_points=5000): initialization random walk attributes
- def fill_walk(self): count all of the ran-walk points
<|skeleton|>
class RandomWalk:
"""a... | abc40ff14168115aa774a60521e00a69f266f7b3 | <|skeleton|>
class RandomWalk:
"""a class to create random walk data"""
def __init__(self, num_points=5000):
"""initialization random walk attributes"""
<|body_0|>
def fill_walk(self):
"""count all of the ran-walk points"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalk:
"""a class to create random walk data"""
def __init__(self, num_points=5000):
"""initialization random walk attributes"""
self.num_points = num_points
'the all ran-walk is start with(0,0)'
self.x_values = [0]
self.y_values = [0]
def fill_walk(self)... | the_stack_v2_python_sparse | Data_visualization/random_walk.py | Lee7goal/lee7_2019 | train | 1 |
1c9177b8478834bb631d9aa8d15c69caabdce0b9 | [
"orchestrate(obj=self, config=stencil_factory.config.dace_config)\ngrid_indexing = stencil_factory.grid_indexing\nself._del6_u = damping_coefficients.del6_u\nself._del6_v = damping_coefficients.del6_v\nself._rarea = rarea\nself._fx = quantity_factory.zeros(dims=[X_INTERFACE_DIM, Y_DIM, Z_DIM], units='undefined')\ns... | <|body_start_0|>
orchestrate(obj=self, config=stencil_factory.config.dace_config)
grid_indexing = stencil_factory.grid_indexing
self._del6_u = damping_coefficients.del6_u
self._del6_v = damping_coefficients.del6_v
self._rarea = rarea
self._fx = quantity_factory.zeros(dims... | Fortran name is del2_cubed | HyperdiffusionDamping | [
"Apache-2.0",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperdiffusionDamping:
"""Fortran name is del2_cubed"""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea, nmax: int):
"""Args: grid: fv3core grid object"""
<|body_0|>
def __c... | stack_v2_sparse_classes_75kplus_train_069983 | 7,280 | permissive | [
{
"docstring": "Args: grid: fv3core grid object",
"name": "__init__",
"signature": "def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea, nmax: int)"
},
{
"docstring": "Perform hyperdiffusion damping/fil... | 2 | stack_v2_sparse_classes_30k_train_000973 | Implement the Python class `HyperdiffusionDamping` described below.
Class description:
Fortran name is del2_cubed
Method signatures and docstrings:
- def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea, nmax: int): Args: gri... | Implement the Python class `HyperdiffusionDamping` described below.
Class description:
Fortran name is del2_cubed
Method signatures and docstrings:
- def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea, nmax: int): Args: gri... | c543e8ec478d46d88b48cdd3beaaa1717a95b935 | <|skeleton|>
class HyperdiffusionDamping:
"""Fortran name is del2_cubed"""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea, nmax: int):
"""Args: grid: fv3core grid object"""
<|body_0|>
def __c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HyperdiffusionDamping:
"""Fortran name is del2_cubed"""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea, nmax: int):
"""Args: grid: fv3core grid object"""
orchestrate(obj=self, config=stencil... | the_stack_v2_python_sparse | fv3core/pace/fv3core/stencils/del2cubed.py | ai2cm/pace | train | 27 |
5b9bfe011757afcb195a85e06598ec11020388e1 | [
"n = len(ranges)\nif none_keys_output != None:\n outputs.append(none_keys_output)\n self.__ignore_none = False\nelse:\n self.__ignore_none = True\nsuper().__init__(inputs=[inputs], outputs=outputs, input_count=1, output_count=n + 1 if self.__ignore_none else n + 2)\nself.__key = key\nself.__side = side\nse... | <|body_start_0|>
n = len(ranges)
if none_keys_output != None:
outputs.append(none_keys_output)
self.__ignore_none = False
else:
self.__ignore_none = True
super().__init__(inputs=[inputs], outputs=outputs, input_count=1, output_count=n + 1 if self.__ign... | Splits a Stream based on the value range of a numerical field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the possible value ranges are, plus one for the atoms that do not have the given key, if enabled. The indexes will be treated as: 0 for the left-most interval (less than r1), 1 for ... | SplitFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitFilter:
"""Splits a Stream based on the value range of a numerical field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the possible value ranges are, plus one for the atoms that do not have the given key, if enabled. The indexes will be treated as: 0 for the le... | stack_v2_sparse_classes_75kplus_train_069984 | 7,770 | no_license | [
{
"docstring": "Parameters: input : str A single stream name. output : str The output streams names. Must have the same length as the number of ranges + 1. The contents of those streams depends on the 'side': eg. let side = 'left' and n = len(ranges) output[0] will contain values <= ranges[0] output[1] will con... | 3 | stack_v2_sparse_classes_30k_val_000911 | Implement the Python class `SplitFilter` described below.
Class description:
Splits a Stream based on the value range of a numerical field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the possible value ranges are, plus one for the atoms that do not have the given key, if enabled. The i... | Implement the Python class `SplitFilter` described below.
Class description:
Splits a Stream based on the value range of a numerical field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the possible value ranges are, plus one for the atoms that do not have the given key, if enabled. The i... | 5d1fce470eeb31f5cc75cadfc06d9d2908736052 | <|skeleton|>
class SplitFilter:
"""Splits a Stream based on the value range of a numerical field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the possible value ranges are, plus one for the atoms that do not have the given key, if enabled. The indexes will be treated as: 0 for the le... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SplitFilter:
"""Splits a Stream based on the value range of a numerical field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the possible value ranges are, plus one for the atoms that do not have the given key, if enabled. The indexes will be treated as: 0 for the left-most inter... | the_stack_v2_python_sparse | otri/filtering/filters/split_filter.py | OTRI-Unipd/OTRI | train | 0 |
a86b5416fcf166871366c31346d65a4b2056433e | [
"super().__init__()\nself.filedir = os.path.join(filedir, 'iou')\nos.makedirs(self.filedir, exist_ok=True)\nself.gen = generator\nself.save = save\nself.num_classes = self.gen.num_classes\nif self.save:\n self.modelpath = os.path.relpath(os.path.join(self.filedir, '..', 'best_iou_model.h5'))\n self.max_miou =... | <|body_start_0|>
super().__init__()
self.filedir = os.path.join(filedir, 'iou')
os.makedirs(self.filedir, exist_ok=True)
self.gen = generator
self.save = save
self.num_classes = self.gen.num_classes
if self.save:
self.modelpath = os.path.relpath(os.pat... | IoUCallback | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IoUCallback:
def __init__(self, filedir, generator, save=True):
"""Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する"""
<|body_0|>
def calc_confusion(self, gt, pred, key):
"""教師ラベルと予測結果を入力とし、各クラスごとに混同行列の... | stack_v2_sparse_classes_75kplus_train_069985 | 10,174 | no_license | [
{
"docstring": "Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する",
"name": "__init__",
"signature": "def __init__(self, filedir, generator, save=True)"
},
{
"docstring": "教師ラベルと予測結果を入力とし、各クラスごとに混同行列の要素を計算する。 Parameters ---------- g... | 4 | stack_v2_sparse_classes_30k_train_024352 | Implement the Python class `IoUCallback` described below.
Class description:
Implement the IoUCallback class.
Method signatures and docstrings:
- def __init__(self, filedir, generator, save=True): Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する
- def c... | Implement the Python class `IoUCallback` described below.
Class description:
Implement the IoUCallback class.
Method signatures and docstrings:
- def __init__(self, filedir, generator, save=True): Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する
- def c... | aeb163624db5f97ac3353ffd0da87e1ac1e5b0a0 | <|skeleton|>
class IoUCallback:
def __init__(self, filedir, generator, save=True):
"""Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する"""
<|body_0|>
def calc_confusion(self, gt, pred, key):
"""教師ラベルと予測結果を入力とし、各クラスごとに混同行列の... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IoUCallback:
def __init__(self, filedir, generator, save=True):
"""Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する"""
super().__init__()
self.filedir = os.path.join(filedir, 'iou')
os.makedirs(self.filedir, exist... | the_stack_v2_python_sparse | src/utils/tensorflow/tensorflow.py | R1ck29/kaggle-cassava-leaf-disease-classification | train | 0 | |
f33a67fdfde8e4cf4cac95ab408652096b51a5df | [
"id_d = id(d)\nsc = self.manager.displayable_map.get(id_d, None)\nif sc is None:\n d = renpy.easy.displayable(d)\n sc = SpriteCache()\n sc.render = None\n sc.child = d\n sc.st = None\n if d._duplicatable:\n sc.child_copy = d._duplicate(None)\n sc.child_copy._unique()\n else:\n ... | <|body_start_0|>
id_d = id(d)
sc = self.manager.displayable_map.get(id_d, None)
if sc is None:
d = renpy.easy.displayable(d)
sc = SpriteCache()
sc.render = None
sc.child = d
sc.st = None
if d._duplicatable:
s... | :doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a sprite object are: `x`, `y` The x... | Sprite | [
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"IJG",
"WxWindows-exception-3.1",
"Zlib",
"bzip2-1.0.6",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"Artistic-2.0",
"LGPL-2.1-only",
"Python-2.0",
"LicenseRef-scancode-warran... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sprite:
""":doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a... | stack_v2_sparse_classes_75kplus_train_069986 | 18,129 | permissive | [
{
"docstring": ":doc: sprites method Changes the Displayable associated with this sprite to `d`.",
"name": "set_child",
"signature": "def set_child(self, d)"
},
{
"docstring": ":doc: sprites method Destroys this sprite, preventing it from being displayed and removing it from the SpriteManager.",... | 2 | stack_v2_sparse_classes_30k_train_029588 | Implement the Python class `Sprite` described below.
Class description:
:doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:... | Implement the Python class `Sprite` described below.
Class description:
:doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:... | e365b474e7df3f76ccc0853fd1665f6529a59304 | <|skeleton|>
class Sprite:
""":doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sprite:
""":doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a sprite objec... | the_stack_v2_python_sparse | TEST_PROJET-1.0-pc/renpy/display/particle.py | Dune0lyn/otome | train | 0 |
b402fedd165b97de4032cb90d940543aff9f9d3b | [
"def dfs(left, right, n, path, res):\n if left == n and right == n:\n res.append(path)\n return\n if left < n:\n dfs(left + 1, right, n, path + '(', res)\n if right < left:\n dfs(left, right + 1, n, path + ')', res)\nres = []\ndfs(0, 0, n, '', res)\nreturn res",
"if n == 0:\n ... | <|body_start_0|>
def dfs(left, right, n, path, res):
if left == n and right == n:
res.append(path)
return
if left < n:
dfs(left + 1, right, n, path + '(', res)
if right < left:
dfs(left, right + 1, n, path + ')',... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
"""dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis3(self, n):
"""闭合数 看不懂。 :param n: :return:"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus_train_069987 | 2,370 | no_license | [
{
"docstring": "dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": "闭合数 看不懂。 :param n: :return:",
"name": "generateParenthesis3",
... | 3 | stack_v2_sparse_classes_30k_train_046570 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]
- def generateParenthesis3(self, n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]
- def generateParenthesis3(self, n... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
"""dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis3(self, n):
"""闭合数 看不懂。 :param n: :return:"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis(self, n):
"""dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]"""
def dfs(left, right, n, path, res):
if left == n and right == n:
res.append(path)
return
... | the_stack_v2_python_sparse | 22_括号生成.py | lovehhf/LeetCode | train | 0 | |
2da05eb8c77f8fce33c1cd9ec23aa0e657f0baf0 | [
"if isinstance(key, int):\n return BindingUpdateFlag(key)\nreturn BindingUpdateFlag[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nreturn cls(value)"
] | <|body_start_0|>
if isinstance(key, int):
return BindingUpdateFlag(key)
return BindingUpdateFlag[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
return ... | [BindingUpdateFlag] Binding Update Flags | BindingUpdateFlag | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BindingUpdateFlag:
"""[BindingUpdateFlag] Binding Update Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'BindingUpdateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_069988 | 1,774 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'BindingUpdateFlag'"
},
{
"docstring": "Lookup function used when value is not ... | 2 | stack_v2_sparse_classes_30k_train_050425 | Implement the Python class `BindingUpdateFlag` described below.
Class description:
[BindingUpdateFlag] Binding Update Flags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'BindingUpdateFlag': Backport support for original codes. Args: key: Key to get enum item. default: Default va... | Implement the Python class `BindingUpdateFlag` described below.
Class description:
[BindingUpdateFlag] Binding Update Flags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'BindingUpdateFlag': Backport support for original codes. Args: key: Key to get enum item. default: Default va... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class BindingUpdateFlag:
"""[BindingUpdateFlag] Binding Update Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'BindingUpdateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BindingUpdateFlag:
"""[BindingUpdateFlag] Binding Update Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'BindingUpdateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
... | the_stack_v2_python_sparse | pcapkit/const/mh/binding_update_flag.py | JarryShaw/PyPCAPKit | train | 204 |
ec3a6e6d3d394fdad2b088ef368740108424e030 | [
"if database_file is None:\n from wurfl import devices\n self.devices = devices\nelse:\n raise NotImplementedError('TODO')\nself.accuracy_threshold = accuracy_threshold\nself.search = CustomJaroWinkler(self.accuracy_threshold)",
"agent = self.get_user_agent(request)\nif not agent:\n return None\nif ty... | <|body_start_0|>
if database_file is None:
from wurfl import devices
self.devices = devices
else:
raise NotImplementedError('TODO')
self.accuracy_threshold = accuracy_threshold
self.search = CustomJaroWinkler(self.accuracy_threshold)
<|end_body_0|>
<|... | Native Wurlf capabilities are listed here: http://wurfl.sourceforge.net/help_doc.php | WurlfSniffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WurlfSniffer:
"""Native Wurlf capabilities are listed here: http://wurfl.sourceforge.net/help_doc.php"""
def __init__(self, database_file=None, accuracy_threshold=0.5):
"""@param database_file: Path to Wurlf XML file or None to use internal database"""
<|body_0|>
def sni... | stack_v2_sparse_classes_75kplus_train_069989 | 6,554 | no_license | [
{
"docstring": "@param database_file: Path to Wurlf XML file or None to use internal database",
"name": "__init__",
"signature": "def __init__(self, database_file=None, accuracy_threshold=0.5)"
},
{
"docstring": "Look up handset from DeviceAtlas database using HTTP_USER_AGENT as a key",
"nam... | 2 | stack_v2_sparse_classes_30k_test_001182 | Implement the Python class `WurlfSniffer` described below.
Class description:
Native Wurlf capabilities are listed here: http://wurfl.sourceforge.net/help_doc.php
Method signatures and docstrings:
- def __init__(self, database_file=None, accuracy_threshold=0.5): @param database_file: Path to Wurlf XML file or None to... | Implement the Python class `WurlfSniffer` described below.
Class description:
Native Wurlf capabilities are listed here: http://wurfl.sourceforge.net/help_doc.php
Method signatures and docstrings:
- def __init__(self, database_file=None, accuracy_threshold=0.5): @param database_file: Path to Wurlf XML file or None to... | fb982e406972ea230f35607ece51f9e903bd3a4c | <|skeleton|>
class WurlfSniffer:
"""Native Wurlf capabilities are listed here: http://wurfl.sourceforge.net/help_doc.php"""
def __init__(self, database_file=None, accuracy_threshold=0.5):
"""@param database_file: Path to Wurlf XML file or None to use internal database"""
<|body_0|>
def sni... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WurlfSniffer:
"""Native Wurlf capabilities are listed here: http://wurfl.sourceforge.net/help_doc.php"""
def __init__(self, database_file=None, accuracy_threshold=0.5):
"""@param database_file: Path to Wurlf XML file or None to use internal database"""
if database_file is None:
... | the_stack_v2_python_sparse | mobile/sniffer/wurlf/sniffer.py | codiez/mobile.sniffer | train | 2 |
25431300491e13c1f707034cc13176048c0f791f | [
"del dest, default\nself._flag_instance = flag_instance\nflag_names = [self._flag_instance.name]\nif self._flag_instance.short_name:\n flag_names.append(self._flag_instance.short_name)\nself._flag_names = frozenset(flag_names)\nsuper(_BooleanFlagAction, self).__init__(option_strings=option_strings, dest=argparse... | <|body_start_0|>
del dest, default
self._flag_instance = flag_instance
flag_names = [self._flag_instance.name]
if self._flag_instance.short_name:
flag_names.append(self._flag_instance.short_name)
self._flag_names = frozenset(flag_names)
super(_BooleanFlagActio... | Action class for Abseil boolean flags. | _BooleanFlagAction | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BooleanFlagAction:
"""Action class for Abseil boolean flags."""
def __init__(self, option_strings, dest, help, metavar, flag_instance, default=argparse.SUPPRESS):
"""Initializes _BooleanFlagAction. Args: option_strings: See argparse.Action. dest: Ignored. The flag is always defined ... | stack_v2_sparse_classes_75kplus_train_069990 | 14,437 | permissive | [
{
"docstring": "Initializes _BooleanFlagAction. Args: option_strings: See argparse.Action. dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS. help: See argparse.Action. metavar: See argparse.Action. flag_instance: absl.flags.Flag, the absl flag instance. default: Ignored. The flag always use... | 2 | stack_v2_sparse_classes_30k_val_000826 | Implement the Python class `_BooleanFlagAction` described below.
Class description:
Action class for Abseil boolean flags.
Method signatures and docstrings:
- def __init__(self, option_strings, dest, help, metavar, flag_instance, default=argparse.SUPPRESS): Initializes _BooleanFlagAction. Args: option_strings: See ar... | Implement the Python class `_BooleanFlagAction` described below.
Class description:
Action class for Abseil boolean flags.
Method signatures and docstrings:
- def __init__(self, option_strings, dest, help, metavar, flag_instance, default=argparse.SUPPRESS): Initializes _BooleanFlagAction. Args: option_strings: See ar... | 171aae3f9c57b41089e25ec61fc84c35baa3079d | <|skeleton|>
class _BooleanFlagAction:
"""Action class for Abseil boolean flags."""
def __init__(self, option_strings, dest, help, metavar, flag_instance, default=argparse.SUPPRESS):
"""Initializes _BooleanFlagAction. Args: option_strings: See argparse.Action. dest: Ignored. The flag is always defined ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _BooleanFlagAction:
"""Action class for Abseil boolean flags."""
def __init__(self, option_strings, dest, help, metavar, flag_instance, default=argparse.SUPPRESS):
"""Initializes _BooleanFlagAction. Args: option_strings: See argparse.Action. dest: Ignored. The flag is always defined with dest=arg... | the_stack_v2_python_sparse | third_party/py/abseil/absl/flags/argparse_flags.py | bazelbuild/bazel | train | 20,294 |
05d914388d1456892a492c6f3360e23901cdaffc | [
"match = context['request'].resolver_match\nif match.url_name in diffviewer_url_names:\n return 'raw/'\nreturn local_site_reverse('raw-diff', context['request'], kwargs={'review_request_id': context['review_request'].display_id})",
"match = context['request'].resolver_match\nif match.url_name in diffviewer_url... | <|body_start_0|>
match = context['request'].resolver_match
if match.url_name in diffviewer_url_names:
return 'raw/'
return local_site_reverse('raw-diff', context['request'], kwargs={'review_request_id': context['review_request'].display_id})
<|end_body_0|>
<|body_start_1|>
m... | An action for downloading a diff from the review request. | DownloadDiffAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadDiffAction:
"""An action for downloading a diff from the review request."""
def get_url(self, context):
"""Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: unicode: The URL to invoke if this actio... | stack_v2_sparse_classes_75kplus_train_069991 | 9,969 | permissive | [
{
"docstring": "Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: unicode: The URL to invoke if this action is clicked.",
"name": "get_url",
"signature": "def get_url(self, context)"
},
{
"docstring": "Return whether ... | 3 | null | Implement the Python class `DownloadDiffAction` described below.
Class description:
An action for downloading a diff from the review request.
Method signatures and docstrings:
- def get_url(self, context): Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the te... | Implement the Python class `DownloadDiffAction` described below.
Class description:
An action for downloading a diff from the review request.
Method signatures and docstrings:
- def get_url(self, context): Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the te... | 563c1e8d4dfd860f372281dc0f380a0809f6ae15 | <|skeleton|>
class DownloadDiffAction:
"""An action for downloading a diff from the review request."""
def get_url(self, context):
"""Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: unicode: The URL to invoke if this actio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DownloadDiffAction:
"""An action for downloading a diff from the review request."""
def get_url(self, context):
"""Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: unicode: The URL to invoke if this action is clicked.... | the_stack_v2_python_sparse | reviewboard/reviews/default_actions.py | LloydFinch/reviewboard | train | 2 |
930e6c50104642ea0685cfc9c92b284bc07f1141 | [
"if not ender:\n ender = lambda entity, is_last, start: 'done' if is_last else entity.key().id_or_name()\nif not skipper:\n skipper = lambda entity, start: False\nself._request = request\nself._config = config\nself._query = query\nself._starter = starter\nself._ender = ender\nself._skipper = skipper\nself._p... | <|body_start_0|>
if not ender:
ender = lambda entity, is_last, start: 'done' if is_last else entity.key().id_or_name()
if not skipper:
skipper = lambda entity, start: False
self._request = request
self._config = config
self._query = query
self._sta... | Builds a ListContentResponse for lists that are based on a single query. | RawQueryContentResponseBuilder | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawQueryContentResponseBuilder:
"""Builds a ListContentResponse for lists that are based on a single query."""
def __init__(self, request, config, query, starter, ender=None, skipper=None, prefetch=None):
"""Initializes the fields needed to built a response. Args: request: The HTTPRe... | stack_v2_sparse_classes_75kplus_train_069992 | 18,817 | permissive | [
{
"docstring": "Initializes the fields needed to built a response. Args: request: The HTTPRequest containing the request for data. config: The ListConfiguration object. fields: The fields to query on. query: The query object to use. starter: The function used to retrieve the start entity. ender: The function us... | 2 | stack_v2_sparse_classes_30k_test_001752 | Implement the Python class `RawQueryContentResponseBuilder` described below.
Class description:
Builds a ListContentResponse for lists that are based on a single query.
Method signatures and docstrings:
- def __init__(self, request, config, query, starter, ender=None, skipper=None, prefetch=None): Initializes the fie... | Implement the Python class `RawQueryContentResponseBuilder` described below.
Class description:
Builds a ListContentResponse for lists that are based on a single query.
Method signatures and docstrings:
- def __init__(self, request, config, query, starter, ender=None, skipper=None, prefetch=None): Initializes the fie... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class RawQueryContentResponseBuilder:
"""Builds a ListContentResponse for lists that are based on a single query."""
def __init__(self, request, config, query, starter, ender=None, skipper=None, prefetch=None):
"""Initializes the fields needed to built a response. Args: request: The HTTPRe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RawQueryContentResponseBuilder:
"""Builds a ListContentResponse for lists that are based on a single query."""
def __init__(self, request, config, query, starter, ender=None, skipper=None, prefetch=None):
"""Initializes the fields needed to built a response. Args: request: The HTTPRequest contain... | the_stack_v2_python_sparse | app/soc/modules/gsoc/views/helper/lists.py | pombredanne/Melange-1 | train | 0 |
67724d453f89cbb0b5fe17fc2994ddc286e5b980 | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_staff', True)\nextra_fields.setdefault('is_superuser', True)\nextra_fields.set... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
extra_fi... | Custom user model manager where email is the unique identifiers for authentication instead of usernames. | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus_train_069993 | 2,489 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superuser",
"signat... | 2 | stack_v2_sparse_classes_30k_train_023566 | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | 73c480b3d44231acfcc43c0292e0b514654aeb27 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueEr... | the_stack_v2_python_sparse | backend/auth_app/models.py | ahrisagree/AHRIS | train | 0 |
f1ba654e2459649e83ca75d6a4ae75e0c2b6a6f9 | [
"super().__init__()\nif rotate:\n self.rotate = nn.Linear(embedding_size, embedding_size, bias=False)\nelse:\n self.rotate = lambda x: x\nself.softmax = nn.Softmax(dim=1)",
"attn = torch.bmm(query_embs.unsqueeze(1), in_mem_embs).squeeze(1)\nif pad_mask is not None:\n attn[pad_mask] = neginf(attn.dtype)\n... | <|body_start_0|>
super().__init__()
if rotate:
self.rotate = nn.Linear(embedding_size, embedding_size, bias=False)
else:
self.rotate = lambda x: x
self.softmax = nn.Softmax(dim=1)
<|end_body_0|>
<|body_start_1|>
attn = torch.bmm(query_embs.unsqueeze(1), i... | Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the probabilities 4) add the query embe... | Hop | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hop:
"""Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the prob... | stack_v2_sparse_classes_75kplus_train_069994 | 7,626 | permissive | [
{
"docstring": "Initialize linear rotation.",
"name": "__init__",
"signature": "def __init__(self, embedding_size, rotate=True)"
},
{
"docstring": "Compute MemNN Hop step. :param query_embs: (bsz x esz) embedding of queries :param in_mem_embs: bsz list of (num_mems x esz) embedding of memories f... | 2 | stack_v2_sparse_classes_30k_val_001033 | Implement the Python class `Hop` described below.
Class description:
Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum ... | Implement the Python class `Hop` described below.
Class description:
Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum ... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class Hop:
"""Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the prob... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hop:
"""Memory Network hop outputs attention-weighted sum of memory embeddings. 0) rotate the query embeddings 1) compute the dot product between the input vector and each memory vector 2) compute a softmax over the memory scores 3) compute the weighted sum of the memory embeddings using the probabilities 4) ... | the_stack_v2_python_sparse | parlai/agents/memnn/modules.py | facebookresearch/ParlAI | train | 10,943 |
fff7b890da23348a6c8b6afa9e22bb9afec32872 | [
"article = ArticleInst.fetch(slug)\ntry:\n comment = Comment.objects.get(pk=id, article=article)\nexcept Comment.DoesNotExist:\n data = {'error': f'Comment of ID {id} nonexistent'}\n status_ = status.HTTP_404_NOT_FOUND\nelse:\n serializer = self.serializer_class(comment)\n status_ = status.HTTP_200_O... | <|body_start_0|>
article = ArticleInst.fetch(slug)
try:
comment = Comment.objects.get(pk=id, article=article)
except Comment.DoesNotExist:
data = {'error': f'Comment of ID {id} nonexistent'}
status_ = status.HTTP_404_NOT_FOUND
else:
seriali... | Creates, Updates and Deletes a single comment | CommentAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentAPIView:
"""Creates, Updates and Deletes a single comment"""
def get(self, request, slug, id):
"""Fetches a comment on an article"""
<|body_0|>
def update(self, request, slug, id):
"""Updates an existing comment"""
<|body_1|>
def destroy(self,... | stack_v2_sparse_classes_75kplus_train_069995 | 10,918 | permissive | [
{
"docstring": "Fetches a comment on an article",
"name": "get",
"signature": "def get(self, request, slug, id)"
},
{
"docstring": "Updates an existing comment",
"name": "update",
"signature": "def update(self, request, slug, id)"
},
{
"docstring": "Removes a comment from an arti... | 4 | stack_v2_sparse_classes_30k_test_001966 | Implement the Python class `CommentAPIView` described below.
Class description:
Creates, Updates and Deletes a single comment
Method signatures and docstrings:
- def get(self, request, slug, id): Fetches a comment on an article
- def update(self, request, slug, id): Updates an existing comment
- def destroy(self, req... | Implement the Python class `CommentAPIView` described below.
Class description:
Creates, Updates and Deletes a single comment
Method signatures and docstrings:
- def get(self, request, slug, id): Fetches a comment on an article
- def update(self, request, slug, id): Updates an existing comment
- def destroy(self, req... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class CommentAPIView:
"""Creates, Updates and Deletes a single comment"""
def get(self, request, slug, id):
"""Fetches a comment on an article"""
<|body_0|>
def update(self, request, slug, id):
"""Updates an existing comment"""
<|body_1|>
def destroy(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentAPIView:
"""Creates, Updates and Deletes a single comment"""
def get(self, request, slug, id):
"""Fetches a comment on an article"""
article = ArticleInst.fetch(slug)
try:
comment = Comment.objects.get(pk=id, article=article)
except Comment.DoesNotExist:... | the_stack_v2_python_sparse | authors/apps/comments/views.py | deferral/ah-django | train | 1 |
de984d0702fe0b8e205afa8c9d34c4fabb328c66 | [
"from .nputils import deltas_to_offsets\nself.paddings, self.s_deltas = deltas_to_offsets(deltas)\nself.ignore_label = ignore_label",
"d = x.device\nbn, h, w = x.shape\nph1, pw1, ph2, pw2 = self.paddings\nxp = torch.empty((bn, h + ph1 + ph2, w + pw1 + pw2), device=d, dtype=torch.int64)\nvp = torch.zeros((bn, h + ... | <|body_start_0|>
from .nputils import deltas_to_offsets
self.paddings, self.s_deltas = deltas_to_offsets(deltas)
self.ignore_label = ignore_label
<|end_body_0|>
<|body_start_1|>
d = x.device
bn, h, w = x.shape
ph1, pw1, ph2, pw2 = self.paddings
xp = torch.empty((... | Given a [bs x 2D] int array (label), output binary array with size [bs x n x 2D] that tells the inter-pixel affinity: 0 - not same ID, 1 - same ID. ig - one out of two is ignore. | affinity_2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class affinity_2d:
"""Given a [bs x 2D] int array (label), output binary array with size [bs x n x 2D] that tells the inter-pixel affinity: 0 - not same ID, 1 - same ID. ig - one out of two is ignore."""
def __init__(self, deltas=[[-1, 0], [0, 1], [1, 0], [0, -1]], ignore_label=-1):
"""Arg... | stack_v2_sparse_classes_75kplus_train_069996 | 15,122 | no_license | [
{
"docstring": "Args: deltas: [n x 2] array, the delta shift to compute affiliation. ex. [[-1, 0], [0, 1], [1, 0], [0, -1]] is the 'urdl'. ignore_label: int, the ignore label. Result will be reviewed in the output mask matrix.",
"name": "__init__",
"signature": "def __init__(self, deltas=[[-1, 0], [0, 1... | 2 | stack_v2_sparse_classes_30k_train_054507 | Implement the Python class `affinity_2d` described below.
Class description:
Given a [bs x 2D] int array (label), output binary array with size [bs x n x 2D] that tells the inter-pixel affinity: 0 - not same ID, 1 - same ID. ig - one out of two is ignore.
Method signatures and docstrings:
- def __init__(self, deltas=... | Implement the Python class `affinity_2d` described below.
Class description:
Given a [bs x 2D] int array (label), output binary array with size [bs x n x 2D] that tells the inter-pixel affinity: 0 - not same ID, 1 - same ID. ig - one out of two is ignore.
Method signatures and docstrings:
- def __init__(self, deltas=... | f14b1eef7229ec3338b85531958d988ef26c2adc | <|skeleton|>
class affinity_2d:
"""Given a [bs x 2D] int array (label), output binary array with size [bs x n x 2D] that tells the inter-pixel affinity: 0 - not same ID, 1 - same ID. ig - one out of two is ignore."""
def __init__(self, deltas=[[-1, 0], [0, 1], [1, 0], [0, -1]], ignore_label=-1):
"""Arg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class affinity_2d:
"""Given a [bs x 2D] int array (label), output binary array with size [bs x n x 2D] that tells the inter-pixel affinity: 0 - not same ID, 1 - same ID. ig - one out of two is ignore."""
def __init__(self, deltas=[[-1, 0], [0, 1], [1, 0], [0, -1]], ignore_label=-1):
"""Args: deltas: [n... | the_stack_v2_python_sparse | lib/torchutils.py | tanmayj000/Rethinking-Text-Segmentation | train | 0 |
ba969253fa0c7f0b7b7b49de47c99d34f2a63f41 | [
"self.physics_controller = physics_controller\nself.armGearbox = wpimath.system.plant.DCMotor.vex775Pro(2)\nself.armSim = wpilib.simulation.SingleJointedArmSim(self.armGearbox, 600.0, wpilib.simulation.SingleJointedArmSim.estimateMOI(0.762, 5), 0.762, math.radians(-75), math.radians(255), True)\nself.encoderSim = w... | <|body_start_0|>
self.physics_controller = physics_controller
self.armGearbox = wpimath.system.plant.DCMotor.vex775Pro(2)
self.armSim = wpilib.simulation.SingleJointedArmSim(self.armGearbox, 600.0, wpilib.simulation.SingleJointedArmSim.estimateMOI(0.762, 5), 0.762, math.radians(-75), math.radian... | Simulates a 4-wheel robot using Tank Drive joystick control | PhysicsEngine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhysicsEngine:
"""Simulates a 4-wheel robot using Tank Drive joystick control"""
def __init__(self, physics_controller: PhysicsInterface, robot: 'MyRobot'):
""":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to :param robot: your robot... | stack_v2_sparse_classes_75kplus_train_069997 | 3,877 | no_license | [
{
"docstring": ":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to :param robot: your robot object",
"name": "__init__",
"signature": "def __init__(self, physics_controller: PhysicsInterface, robot: 'MyRobot')"
},
{
"docstring": "Called when the s... | 2 | stack_v2_sparse_classes_30k_train_017985 | Implement the Python class `PhysicsEngine` described below.
Class description:
Simulates a 4-wheel robot using Tank Drive joystick control
Method signatures and docstrings:
- def __init__(self, physics_controller: PhysicsInterface, robot: 'MyRobot'): :param physics_controller: `pyfrc.physics.core.Physics` object to c... | Implement the Python class `PhysicsEngine` described below.
Class description:
Simulates a 4-wheel robot using Tank Drive joystick control
Method signatures and docstrings:
- def __init__(self, physics_controller: PhysicsInterface, robot: 'MyRobot'): :param physics_controller: `pyfrc.physics.core.Physics` object to c... | edbaa498ef685bed516f6792089f88be1a5db865 | <|skeleton|>
class PhysicsEngine:
"""Simulates a 4-wheel robot using Tank Drive joystick control"""
def __init__(self, physics_controller: PhysicsInterface, robot: 'MyRobot'):
""":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to :param robot: your robot... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhysicsEngine:
"""Simulates a 4-wheel robot using Tank Drive joystick control"""
def __init__(self, physics_controller: PhysicsInterface, robot: 'MyRobot'):
""":param physics_controller: `pyfrc.physics.core.Physics` object to communicate simulation effects to :param robot: your robot object"""
... | the_stack_v2_python_sparse | arm-simulation/physics.py | robotpy/examples | train | 38 |
e49d095f194e5597c08d14bdf864598ad6a939b7 | [
"self.csvPath = csvPath\nself.cutBarCount = 0\nif not os.path.exists(self.csvPath):\n raise FileNotFoundError(self.csvPath)",
"inputDataDic = OrderedDict()\nwith open(self.csvPath, newline='') as csvfile:\n reader = csv.DictReader(csvfile, dialect='excel', delimiter=';')\n for row in reader:\n if ... | <|body_start_0|>
self.csvPath = csvPath
self.cutBarCount = 0
if not os.path.exists(self.csvPath):
raise FileNotFoundError(self.csvPath)
<|end_body_0|>
<|body_start_1|>
inputDataDic = OrderedDict()
with open(self.csvPath, newline='') as csvfile:
reader = c... | The reader for bar CSV files | BarCsvReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarCsvReader:
"""The reader for bar CSV files"""
def __init__(self, csvPath):
"""Constructor"""
<|body_0|>
def ParseCsv(self, dateCol, lengthCol, barCountCol):
"""The bar CSV parser @return inputDataDic An OrderedDict of {length1, ..., lengthN} indexed by date"""... | stack_v2_sparse_classes_75kplus_train_069998 | 1,390 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, csvPath)"
},
{
"docstring": "The bar CSV parser @return inputDataDic An OrderedDict of {length1, ..., lengthN} indexed by date",
"name": "ParseCsv",
"signature": "def ParseCsv(self, dateCol, lengthCol, bar... | 2 | stack_v2_sparse_classes_30k_train_011097 | Implement the Python class `BarCsvReader` described below.
Class description:
The reader for bar CSV files
Method signatures and docstrings:
- def __init__(self, csvPath): Constructor
- def ParseCsv(self, dateCol, lengthCol, barCountCol): The bar CSV parser @return inputDataDic An OrderedDict of {length1, ..., length... | Implement the Python class `BarCsvReader` described below.
Class description:
The reader for bar CSV files
Method signatures and docstrings:
- def __init__(self, csvPath): Constructor
- def ParseCsv(self, dateCol, lengthCol, barCountCol): The bar CSV parser @return inputDataDic An OrderedDict of {length1, ..., length... | 14f2c8f476fee85e0567fcd0d179b509af1c1c38 | <|skeleton|>
class BarCsvReader:
"""The reader for bar CSV files"""
def __init__(self, csvPath):
"""Constructor"""
<|body_0|>
def ParseCsv(self, dateCol, lengthCol, barCountCol):
"""The bar CSV parser @return inputDataDic An OrderedDict of {length1, ..., lengthN} indexed by date"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BarCsvReader:
"""The reader for bar CSV files"""
def __init__(self, csvPath):
"""Constructor"""
self.csvPath = csvPath
self.cutBarCount = 0
if not os.path.exists(self.csvPath):
raise FileNotFoundError(self.csvPath)
def ParseCsv(self, dateCol, lengthCol, ba... | the_stack_v2_python_sparse | src/CsvManager/BarCsvReader.py | Plouff/BarSupplyOptimizer | train | 0 |
8b090c85807616328655677f860db8276c8c078e | [
"super().__init__(name=name)\nself._loss = loss if loss is not None else tf.keras.losses.BinaryCrossentropy()\nself._ranking_metrics = metrics or []\nself._prediction_metrics = prediction_metrics or []\nself._label_metrics = label_metrics or []\nself._loss_metrics = loss_metrics or []",
"loss = self._loss(y_true=... | <|body_start_0|>
super().__init__(name=name)
self._loss = loss if loss is not None else tf.keras.losses.BinaryCrossentropy()
self._ranking_metrics = metrics or []
self._prediction_metrics = prediction_metrics or []
self._label_metrics = label_metrics or []
self._loss_metr... | A ranking task. Recommender systems are often composed of two components: - a retrieval model, retrieving O(thousands) candidates from a corpus of O(millions) candidates. - a ranker model, scoring the candidates retrieved by the retrieval model to return a ranked shortlist of a few dozen candidates. This task helps wit... | Ranking | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ranking:
"""A ranking task. Recommender systems are often composed of two components: - a retrieval model, retrieving O(thousands) candidates from a corpus of O(millions) candidates. - a ranker model, scoring the candidates retrieved by the retrieval model to return a ranked shortlist of a few do... | stack_v2_sparse_classes_75kplus_train_069999 | 4,074 | permissive | [
{
"docstring": "Initializes the task. Args: loss: Loss function. Defaults to BinaryCrossentropy. metrics: List of Keras metrics to be evaluated. prediction_metrics: List of Keras metrics used to summarize the predictions. label_metrics: List of Keras metrics used to summarize the labels. loss_metrics: List of K... | 2 | stack_v2_sparse_classes_30k_train_017796 | Implement the Python class `Ranking` described below.
Class description:
A ranking task. Recommender systems are often composed of two components: - a retrieval model, retrieving O(thousands) candidates from a corpus of O(millions) candidates. - a ranker model, scoring the candidates retrieved by the retrieval model t... | Implement the Python class `Ranking` described below.
Class description:
A ranking task. Recommender systems are often composed of two components: - a retrieval model, retrieving O(thousands) candidates from a corpus of O(millions) candidates. - a ranker model, scoring the candidates retrieved by the retrieval model t... | f4f42c1a183a262539e21f5ab8d25f0dc3e5621d | <|skeleton|>
class Ranking:
"""A ranking task. Recommender systems are often composed of two components: - a retrieval model, retrieving O(thousands) candidates from a corpus of O(millions) candidates. - a ranker model, scoring the candidates retrieved by the retrieval model to return a ranked shortlist of a few do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ranking:
"""A ranking task. Recommender systems are often composed of two components: - a retrieval model, retrieving O(thousands) candidates from a corpus of O(millions) candidates. - a ranker model, scoring the candidates retrieved by the retrieval model to return a ranked shortlist of a few dozen candidate... | the_stack_v2_python_sparse | tensorflow_recommenders/tasks/ranking.py | tensorflow/recommenders | train | 1,666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.