blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f44765518ce70b7b0adc98269f254e02d652436 | [
"if request.user.has_perm(VIEW_TEAMTYPE):\n group_types = TeamType.objects.all()\n serializer = TeamTypeSerializer(group_types, many=True)\n return Response(serializer.data)\nelse:\n return Response(status=status.HTTP_401_UNAUTHORIZED)",
"if request.user.has_perm(ADD_TEAMTYPE):\n serializer = TeamT... | <|body_start_0|>
if request.user.has_perm(VIEW_TEAMTYPE):
group_types = TeamType.objects.all()
serializer = TeamTypeSerializer(group_types, many=True)
return Response(serializer.data)
else:
return Response(status=status.HTTP_401_UNAUTHORIZED)
<|end_body_0|... | # List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If the request is not valid, send HTTP 400. ... | TeamTypesList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamTypesList:
"""# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If ... | stack_v2_sparse_classes_36k_train_015100 | 6,650 | permissive | [
{
"docstring": "docstring.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "docstring.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021070 | Implement the Python class `TeamTypesList` described below.
Class description:
# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - cre... | Implement the Python class `TeamTypesList` described below.
Class description:
# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - cre... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class TeamTypesList:
"""# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamTypesList:
"""# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If the request i... | the_stack_v2_python_sparse | usersmanagement/views/views_teamtypes.py | Open-CMMS/openCMMS_backend | train | 4 |
b9e2cba9c454e3e86a86e358200315c9b9949078 | [
"if not root:\n return None\nres = TreeNode(root.val)\nif root.children:\n res.left = self.encode(root.children[0])\ncur = res.left\nfor i in range(1, len(root.children)):\n cur.right = self.encode(root.children[i])\n cur = cur.right\nreturn res",
"if not data:\n return None\nres = Node(data.val, [... | <|body_start_0|>
if not root:
return None
res = TreeNode(root.val)
if root.children:
res.left = self.encode(root.children[0])
cur = res.left
for i in range(1, len(root.children)):
cur.right = self.encode(root.children[i])
cur = cur.... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_015101 | 1,961 | no_license | [
{
"docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode",
"name": "encode",
"signature": "def encode(self, root)"
},
{
"docstring": "Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node",
"name": "decode",
"signature": "def decode... | 2 | stack_v2_sparse_classes_30k_train_013089 | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: Tre... | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: Tre... | 3e50f6a936b98ad75c47d7c1719e69163c648235 | <|skeleton|>
class Codec2:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec2:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
if not root:
return None
res = TreeNode(root.val)
if root.children:
res.left = self.encode(root.children[0])
cur = res.left
fo... | the_stack_v2_python_sparse | LeetcodeNew/Tree/LC_431_Encode_N_ary_Tree_to_Binary_Tree.py | Taoge123/OptimizedLeetcode | train | 9 | |
0cf786d9156d62f2f7dc640ceeb01ca0850fd09c | [
"request = DescribeDomainsRequest()\nrequest.set_accept_format('json')\nrequest.set_PageNumber(page_num)\nrequest.set_PageSize(page_size)\ndata = self._request(request)\ntotal = data.get('TotalCount')\ndata = data.get('Domains')\ndata_list = data.get('Domain')\ndata = {'total': total, 'data_list': data_list}\nretur... | <|body_start_0|>
request = DescribeDomainsRequest()
request.set_accept_format('json')
request.set_PageNumber(page_num)
request.set_PageSize(page_size)
data = self._request(request)
total = data.get('TotalCount')
data = data.get('Domains')
data_list = data.... | 阿里云DNS | AliyunDNS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliyunDNS:
"""阿里云DNS"""
def get_domains(self, page_num=1, page_size=20):
"""获取域名"""
<|body_0|>
def get_domain_records(self, domain_name, page_num=1, page_size=20):
"""获取域名解析记录列表"""
<|body_1|>
def get_domain_record(self, instance_id):
"""获取域名解... | stack_v2_sparse_classes_36k_train_015102 | 1,904 | no_license | [
{
"docstring": "获取域名",
"name": "get_domains",
"signature": "def get_domains(self, page_num=1, page_size=20)"
},
{
"docstring": "获取域名解析记录列表",
"name": "get_domain_records",
"signature": "def get_domain_records(self, domain_name, page_num=1, page_size=20)"
},
{
"docstring": "获取域名解析记... | 3 | stack_v2_sparse_classes_30k_train_004228 | Implement the Python class `AliyunDNS` described below.
Class description:
阿里云DNS
Method signatures and docstrings:
- def get_domains(self, page_num=1, page_size=20): 获取域名
- def get_domain_records(self, domain_name, page_num=1, page_size=20): 获取域名解析记录列表
- def get_domain_record(self, instance_id): 获取域名解析记录 | Implement the Python class `AliyunDNS` described below.
Class description:
阿里云DNS
Method signatures and docstrings:
- def get_domains(self, page_num=1, page_size=20): 获取域名
- def get_domain_records(self, domain_name, page_num=1, page_size=20): 获取域名解析记录列表
- def get_domain_record(self, instance_id): 获取域名解析记录
<|skeleton... | 3539cab6e73571f84b7f17391d9a363a756f12e1 | <|skeleton|>
class AliyunDNS:
"""阿里云DNS"""
def get_domains(self, page_num=1, page_size=20):
"""获取域名"""
<|body_0|>
def get_domain_records(self, domain_name, page_num=1, page_size=20):
"""获取域名解析记录列表"""
<|body_1|>
def get_domain_record(self, instance_id):
"""获取域名解... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AliyunDNS:
"""阿里云DNS"""
def get_domains(self, page_num=1, page_size=20):
"""获取域名"""
request = DescribeDomainsRequest()
request.set_accept_format('json')
request.set_PageNumber(page_num)
request.set_PageSize(page_size)
data = self._request(request)
t... | the_stack_v2_python_sparse | utils/aliyun/dns.py | cuijianzhe/cow | train | 2 |
1473b6557152218e4e3470963ac60018f9d30532 | [
"s = '#' + s\np = '#' + p\nm, n = (len(s), len(p))\ndp = [[False] * m for _ in range(n)]\ndp[0][0] = True\nfor i in range(2, n):\n dp[i][0] = dp[i - 2][0] and p[i] == '*'\nfor j in range(m):\n for i in range(1, n):\n if p[i] != '*':\n dp[i][j] = p[i] in (s[j], '.') and dp[i - 1][j - 1]\n ... | <|body_start_0|>
s = '#' + s
p = '#' + p
m, n = (len(s), len(p))
dp = [[False] * m for _ in range(n)]
dp[0][0] = True
for i in range(2, n):
dp[i][0] = dp[i - 2][0] and p[i] == '*'
for j in range(m):
for i in range(1, n):
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, s: str, p: str) -> bool:
"""没搞定!!!!!!!"""
<|body_0|>
def isMatch1(self, s, p):
"""别人的正解!!!!"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = '#' + s
p = '#' + p
m, n = (len(s), len(p))
dp = [[Fa... | stack_v2_sparse_classes_36k_train_015103 | 3,699 | no_license | [
{
"docstring": "没搞定!!!!!!!",
"name": "isMatch",
"signature": "def isMatch(self, s: str, p: str) -> bool"
},
{
"docstring": "别人的正解!!!!",
"name": "isMatch1",
"signature": "def isMatch1(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017392 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s: str, p: str) -> bool: 没搞定!!!!!!!
- def isMatch1(self, s, p): 别人的正解!!!! | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s: str, p: str) -> bool: 没搞定!!!!!!!
- def isMatch1(self, s, p): 别人的正解!!!!
<|skeleton|>
class Solution:
def isMatch(self, s: str, p: str) -> bool:
... | bc895124817aa1341d15ac85e1c6d670a9420dec | <|skeleton|>
class Solution:
def isMatch(self, s: str, p: str) -> bool:
"""没搞定!!!!!!!"""
<|body_0|>
def isMatch1(self, s, p):
"""别人的正解!!!!"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch(self, s: str, p: str) -> bool:
"""没搞定!!!!!!!"""
s = '#' + s
p = '#' + p
m, n = (len(s), len(p))
dp = [[False] * m for _ in range(n)]
dp[0][0] = True
for i in range(2, n):
dp[i][0] = dp[i - 2][0] and p[i] == '*'
f... | the_stack_v2_python_sparse | leetcode/10RegularExpressionMatching.py | qilaidi/leetcode_problems | train | 0 | |
709b7a281bac1f3d1f7541e5bddaa9a7e7cf4786 | [
"super(DeepNieFineCoattention, self).__init__()\nwith self.init_scope():\n self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1)\n self.attention_layer_1 = GraphLinear(head, 1, nobias=True)\n self.attention_layer_2 = GraphLinear(head, 1, nobias=True)\n self.prev_lt_layer_1 = GraphLinear(hidden_d... | <|body_start_0|>
super(DeepNieFineCoattention, self).__init__()
with self.init_scope():
self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1)
self.attention_layer_1 = GraphLinear(head, 1, nobias=True)
self.attention_layer_2 = GraphLinear(head, 1, nobias=True)
... | TODO | DeepNieFineCoattention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepNieFineCoattention:
"""TODO"""
def __init__(self, hidden_dim, out_dim, head, activation=functions.identity):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
... | stack_v2_sparse_classes_36k_train_015104 | 25,561 | permissive | [
{
"docstring": ":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism",
"name": "__init__",
"signature": "def __init__(self, hidden_dim, out_dim, head, activation=functions.identity)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_test_000043 | Implement the Python class `DeepNieFineCoattention` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :para... | Implement the Python class `DeepNieFineCoattention` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :para... | 21b64a3c8cc9bc33718ae09c65aa917e575132eb | <|skeleton|>
class DeepNieFineCoattention:
"""TODO"""
def __init__(self, hidden_dim, out_dim, head, activation=functions.identity):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepNieFineCoattention:
"""TODO"""
def __init__(self, hidden_dim, out_dim, head, activation=functions.identity):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
super(DeepNi... | the_stack_v2_python_sparse | models/coattention/nie_coattention.py | Minys233/GCN-BMP | train | 1 |
b20ee3b738828a6a5132685415e6914ae81cd5f4 | [
"super(GloveEmbedding, self).__init__()\nself.embedding = Embedding.from_pretrained(embedding_matrix)\nself.embedding.padding_idx = padding_idx\nif static:\n self.embedding.weight.required_grad = False\nself.flatten = Flatten(start_dim=1)",
"x_output = self.embedding(x_input)\nx_output = self.flatten(x_output)... | <|body_start_0|>
super(GloveEmbedding, self).__init__()
self.embedding = Embedding.from_pretrained(embedding_matrix)
self.embedding.padding_idx = padding_idx
if static:
self.embedding.weight.required_grad = False
self.flatten = Flatten(start_dim=1)
<|end_body_0|>
<|b... | Implement Glove based Word Embedding. | GloveEmbedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GloveEmbedding:
"""Implement Glove based Word Embedding."""
def __init__(self, embedding_matrix, padding_idx, static=True):
"""Construct GloveEmbedding. Args: embedding_matrix (torch.Tensor): The matrix contrainining the embedding weights padding_idx (int): The padding index in the t... | stack_v2_sparse_classes_36k_train_015105 | 1,291 | no_license | [
{
"docstring": "Construct GloveEmbedding. Args: embedding_matrix (torch.Tensor): The matrix contrainining the embedding weights padding_idx (int): The padding index in the tokenizer. static (bool): Whether or not to freeze embeddings.",
"name": "__init__",
"signature": "def __init__(self, embedding_matr... | 2 | stack_v2_sparse_classes_30k_train_019008 | Implement the Python class `GloveEmbedding` described below.
Class description:
Implement Glove based Word Embedding.
Method signatures and docstrings:
- def __init__(self, embedding_matrix, padding_idx, static=True): Construct GloveEmbedding. Args: embedding_matrix (torch.Tensor): The matrix contrainining the embedd... | Implement the Python class `GloveEmbedding` described below.
Class description:
Implement Glove based Word Embedding.
Method signatures and docstrings:
- def __init__(self, embedding_matrix, padding_idx, static=True): Construct GloveEmbedding. Args: embedding_matrix (torch.Tensor): The matrix contrainining the embedd... | 53c44f92e2683052741d3a6c66c8ced15f1464ed | <|skeleton|>
class GloveEmbedding:
"""Implement Glove based Word Embedding."""
def __init__(self, embedding_matrix, padding_idx, static=True):
"""Construct GloveEmbedding. Args: embedding_matrix (torch.Tensor): The matrix contrainining the embedding weights padding_idx (int): The padding index in the t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GloveEmbedding:
"""Implement Glove based Word Embedding."""
def __init__(self, embedding_matrix, padding_idx, static=True):
"""Construct GloveEmbedding. Args: embedding_matrix (torch.Tensor): The matrix contrainining the embedding weights padding_idx (int): The padding index in the tokenizer. sta... | the_stack_v2_python_sparse | src/modules/embeddings.py | abheesht17/ReCAM | train | 0 |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(InTimeToArrivalToLocation, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._time = time\nself._target_location = location",
"new_status = py_trees.common.Status.RUNNING\ncurrent_location = CarlaDataProvider.get_location(self._actor)\nif current_... | <|body_start_0|>
super(InTimeToArrivalToLocation, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._time = time
self._target_location = location
<|end_body_0|>
<|body_start_1|>
new_status = py_trees.common.Status.... | This class contains a check if a actor arrives within a given time at a given location. | InTimeToArrivalToLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InTimeToArrivalToLocation:
"""This class contains a check if a actor arrives within a given time at a given location."""
def __init__(self, actor, time, location, name='TimeToArrival'):
"""Setup parameters"""
<|body_0|>
def update(self):
"""Check if the actor can... | stack_v2_sparse_classes_36k_train_015106 | 25,380 | permissive | [
{
"docstring": "Setup parameters",
"name": "__init__",
"signature": "def __init__(self, actor, time, location, name='TimeToArrival')"
},
{
"docstring": "Check if the actor can arrive at target_location within time",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016901 | Implement the Python class `InTimeToArrivalToLocation` described below.
Class description:
This class contains a check if a actor arrives within a given time at a given location.
Method signatures and docstrings:
- def __init__(self, actor, time, location, name='TimeToArrival'): Setup parameters
- def update(self): C... | Implement the Python class `InTimeToArrivalToLocation` described below.
Class description:
This class contains a check if a actor arrives within a given time at a given location.
Method signatures and docstrings:
- def __init__(self, actor, time, location, name='TimeToArrival'): Setup parameters
- def update(self): C... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class InTimeToArrivalToLocation:
"""This class contains a check if a actor arrives within a given time at a given location."""
def __init__(self, actor, time, location, name='TimeToArrival'):
"""Setup parameters"""
<|body_0|>
def update(self):
"""Check if the actor can... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InTimeToArrivalToLocation:
"""This class contains a check if a actor arrives within a given time at a given location."""
def __init__(self, actor, time, location, name='TimeToArrival'):
"""Setup parameters"""
super(InTimeToArrivalToLocation, self).__init__(name)
self.logger.debug(... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
5505e0105bfe499a17204209f0bd67b21a8c79ab | [
"self.type = 'ATOM'\nself.serial = serial\nself.name = name\nself.altLoc = ''\nself.resName = resName\nself.chainID = ''\nself.resSeq = 1\nself.iCode = ''\nself.x = x\nself.y = y\nself.z = z\nself.occupancy = 0.0\nself.tempFactor = 0.0\nself.segID = ''\nself.element = ''\nself.charge = ''\nself.ffcharge = 0.0\nself... | <|body_start_0|>
self.type = 'ATOM'
self.serial = serial
self.name = name
self.altLoc = ''
self.resName = resName
self.chainID = ''
self.resSeq = 1
self.iCode = ''
self.x = x
self.y = y
self.z = z
self.occupancy = 0.0
... | Class DefinitionAtom The DefinitionAtom class inherits off the Atom class. It provides a trimmed down version of the initializating function from the Atom class for the definition files. | DefinitionAtom | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefinitionAtom:
"""Class DefinitionAtom The DefinitionAtom class inherits off the Atom class. It provides a trimmed down version of the initializating function from the Atom class for the definition files."""
def __init__(self, serial, name, resName, x, y, z):
"""Initialize using a f... | stack_v2_sparse_classes_36k_train_015107 | 12,649 | permissive | [
{
"docstring": "Initialize using a few basic parameters - set all other fields to null, which is necessary for debugging output by using the string function in the parent class. Parameters serial: Atom serial number (int) name: Atom name. (string) resName: Residue name. (string) resSeq: Residue sequence number.... | 2 | stack_v2_sparse_classes_30k_train_020293 | Implement the Python class `DefinitionAtom` described below.
Class description:
Class DefinitionAtom The DefinitionAtom class inherits off the Atom class. It provides a trimmed down version of the initializating function from the Atom class for the definition files.
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `DefinitionAtom` described below.
Class description:
Class DefinitionAtom The DefinitionAtom class inherits off the Atom class. It provides a trimmed down version of the initializating function from the Atom class for the definition files.
Method signatures and docstrings:
- def __init__(se... | a50f0b2f7104007c730baa51b4ec65c891008c47 | <|skeleton|>
class DefinitionAtom:
"""Class DefinitionAtom The DefinitionAtom class inherits off the Atom class. It provides a trimmed down version of the initializating function from the Atom class for the definition files."""
def __init__(self, serial, name, resName, x, y, z):
"""Initialize using a f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefinitionAtom:
"""Class DefinitionAtom The DefinitionAtom class inherits off the Atom class. It provides a trimmed down version of the initializating function from the Atom class for the definition files."""
def __init__(self, serial, name, resName, x, y, z):
"""Initialize using a few basic para... | the_stack_v2_python_sparse | mscreen/autodocktools_prepare_py3k/MolKit/pdb2pqr/definitions.py | e-mayo/mscreen | train | 10 |
d3e318f2e9cde2fb7d94faad20e1976a1af42de5 | [
"result = m.copy()\nfor x, row in enumerate(m):\n col = [i[x] for i in m]\n result[x] = col[::-1]\nreturn result",
"l = len(m) - 1\npprint(m)\nresult = m.copy()\nfor x, row in enumerate(m):\n col = [i[x] for i in m]\n result[l - x] = col\nreturn result"
] | <|body_start_0|>
result = m.copy()
for x, row in enumerate(m):
col = [i[x] for i in m]
result[x] = col[::-1]
return result
<|end_body_0|>
<|body_start_1|>
l = len(m) - 1
pprint(m)
result = m.copy()
for x, row in enumerate(m):
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate_matrix(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees clockwise."""
<|body_0|>
def rotate_matrix_ccw(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees counter-clockwise."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_015108 | 1,261 | no_license | [
{
"docstring": "Given a matrix of NxN dimension, rotate it 90 degrees clockwise.",
"name": "rotate_matrix",
"signature": "def rotate_matrix(self, m)"
},
{
"docstring": "Given a matrix of NxN dimension, rotate it 90 degrees counter-clockwise.",
"name": "rotate_matrix_ccw",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_015993 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_matrix(self, m): Given a matrix of NxN dimension, rotate it 90 degrees clockwise.
- def rotate_matrix_ccw(self, m): Given a matrix of NxN dimension, rotate it 90 degre... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_matrix(self, m): Given a matrix of NxN dimension, rotate it 90 degrees clockwise.
- def rotate_matrix_ccw(self, m): Given a matrix of NxN dimension, rotate it 90 degre... | acad7283f4af301539c621b4b50268208509d38f | <|skeleton|>
class Solution:
def rotate_matrix(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees clockwise."""
<|body_0|>
def rotate_matrix_ccw(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees counter-clockwise."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate_matrix(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees clockwise."""
result = m.copy()
for x, row in enumerate(m):
col = [i[x] for i in m]
result[x] = col[::-1]
return result
def rotate_matrix_ccw(self, m):
... | the_stack_v2_python_sparse | algos/rotate_matrix.py | arijort/prep | train | 2 | |
7bb549de5553836e43f1d8d5c837f3e00b775291 | [
"super(MEltPOSTagger, self).__init__()\nself._melt_command = ''\nself._encoding = encoding\nif language == language_support.KBLanguage.FRENCH:\n model_directory = path.join(MELT_MODEL_DIRECTORY, 'fr')\n self._melt_command = 'python %s -m %s -d %s -l %s -e %s' % (MELT_EXEC, model_directory, path.join(model_dir... | <|body_start_0|>
super(MEltPOSTagger, self).__init__()
self._melt_command = ''
self._encoding = encoding
if language == language_support.KBLanguage.FRENCH:
model_directory = path.join(MELT_MODEL_DIRECTORY, 'fr')
self._melt_command = 'python %s -m %s -d %s -l %s -e... | MElt Part-of-Speech tagger. MElt Part-of-Speech tagger. It currently only supports French (C{keybench.main.language_support.KBLanguage.FRENCH}) and English (C{keybench.main.language_support.KBLanguage.English}). | MEltPOSTagger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MEltPOSTagger:
"""MElt Part-of-Speech tagger. MElt Part-of-Speech tagger. It currently only supports French (C{keybench.main.language_support.KBLanguage.FRENCH}) and English (C{keybench.main.language_support.KBLanguage.English})."""
def __init__(self, language, encoding):
"""Construc... | stack_v2_sparse_classes_36k_train_015109 | 6,186 | no_license | [
{
"docstring": "Constructor. Args: language: The C{string} name of the language of the data to treat (see C{keybench.main.language_support.KBLanguage}). encoding: The C{string} encoding of the data to treat.",
"name": "__init__",
"signature": "def __init__(self, language, encoding)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_000473 | Implement the Python class `MEltPOSTagger` described below.
Class description:
MElt Part-of-Speech tagger. MElt Part-of-Speech tagger. It currently only supports French (C{keybench.main.language_support.KBLanguage.FRENCH}) and English (C{keybench.main.language_support.KBLanguage.English}).
Method signatures and docst... | Implement the Python class `MEltPOSTagger` described below.
Class description:
MElt Part-of-Speech tagger. MElt Part-of-Speech tagger. It currently only supports French (C{keybench.main.language_support.KBLanguage.FRENCH}) and English (C{keybench.main.language_support.KBLanguage.English}).
Method signatures and docst... | a66cf98b11260d2b74cd990f36f5dcde192b0346 | <|skeleton|>
class MEltPOSTagger:
"""MElt Part-of-Speech tagger. MElt Part-of-Speech tagger. It currently only supports French (C{keybench.main.language_support.KBLanguage.FRENCH}) and English (C{keybench.main.language_support.KBLanguage.English})."""
def __init__(self, language, encoding):
"""Construc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MEltPOSTagger:
"""MElt Part-of-Speech tagger. MElt Part-of-Speech tagger. It currently only supports French (C{keybench.main.language_support.KBLanguage.FRENCH}) and English (C{keybench.main.language_support.KBLanguage.English})."""
def __init__(self, language, encoding):
"""Constructor. Args: la... | the_stack_v2_python_sparse | src/keybench/main/nlp_tool/implementation/pos_tagger/melt_pos_tagger.py | Archer-W/KeyBench | train | 0 |
7170a4a385d109166c0a985d85f7ccca6c99e23d | [
"if not head or not head.next:\n return head\np = head\nq = head.next\nhead.next = None\nwhile q:\n r = q.next\n q.next = p\n p = q\n q = r\nreturn p",
"if not head or not head.next:\n return head\np = head.next\nnewHead = self.reverseList(p)\np.next = head\nhead.next = None\nreturn newHead"
] | <|body_start_0|>
if not head or not head.next:
return head
p = head
q = head.next
head.next = None
while q:
r = q.next
q.next = p
p = q
q = r
return p
<|end_body_0|>
<|body_start_1|>
if not head or not h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList1(self, head):
"""迭代 :param head: :return:"""
<|body_0|>
def reverseList(self, head: ListNode) -> ListNode:
"""递归 :param head: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
... | stack_v2_sparse_classes_36k_train_015110 | 868 | no_license | [
{
"docstring": "迭代 :param head: :return:",
"name": "reverseList1",
"signature": "def reverseList1(self, head)"
},
{
"docstring": "递归 :param head: :return:",
"name": "reverseList",
"signature": "def reverseList(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_009971 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): 迭代 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode: 递归 :param head: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): 迭代 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode: 递归 :param head: :return:
<|skeleton|>
class Solution:
def revers... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def reverseList1(self, head):
"""迭代 :param head: :return:"""
<|body_0|>
def reverseList(self, head: ListNode) -> ListNode:
"""递归 :param head: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList1(self, head):
"""迭代 :param head: :return:"""
if not head or not head.next:
return head
p = head
q = head.next
head.next = None
while q:
r = q.next
q.next = p
p = q
q = r
... | the_stack_v2_python_sparse | 206_反转链表.py | lovehhf/LeetCode | train | 0 | |
4408d3351401dc52435f2ab39e1f26ace725432a | [
"idx += 1\nself._idx = idx\nself._attr_name = f'{entry[CONF_NAME]} {idx}'\nself._attr_unique_id = entry.get(CONF_UNIQUE_ID)\nif self._attr_unique_id:\n self._attr_unique_id = f'{self._attr_unique_id}_{idx}'\nself._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)\nself._attr_state_class = ent... | <|body_start_0|>
idx += 1
self._idx = idx
self._attr_name = f'{entry[CONF_NAME]} {idx}'
self._attr_unique_id = entry.get(CONF_UNIQUE_ID)
if self._attr_unique_id:
self._attr_unique_id = f'{self._attr_unique_id}_{idx}'
self._attr_native_unit_of_measurement = ent... | Modbus slave register sensor. | SlaveSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlaveSensor:
"""Modbus slave register sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus register sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_36k_train_015111 | 6,226 | permissive | [
{
"docstring": "Initialize the Modbus register sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None"
},
{
"docstring": "Handle entity which will be added.",
"name": "async_added_to_hass",... | 3 | stack_v2_sparse_classes_30k_train_013193 | Implement the Python class `SlaveSensor` described below.
Class description:
Modbus slave register sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None: Initialize the Modbus register sensor.
- async def async_add... | Implement the Python class `SlaveSensor` described below.
Class description:
Modbus slave register sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None: Initialize the Modbus register sensor.
- async def async_add... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SlaveSensor:
"""Modbus slave register sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus register sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlaveSensor:
"""Modbus slave register sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus register sensor."""
idx += 1
self._idx = idx
self._attr_name = f'{entry[CONF_NAME]} ... | the_stack_v2_python_sparse | homeassistant/components/modbus/sensor.py | home-assistant/core | train | 35,501 |
2c30f6e911df4529d8787f10afb498bc8bd6a3c7 | [
"if not root:\n return ''\nresult = []\nnodes = [root]\nwhile nodes:\n node = nodes.pop()\n result.append(str(node.val))\n if node.right:\n nodes.append(node.right)\n if node.left:\n nodes.append(node.left)\nreturn ' '.join(result)",
"if not data:\n return None\npreorder = [int(val... | <|body_start_0|>
if not root:
return ''
result = []
nodes = [root]
while nodes:
node = nodes.pop()
result.append(str(node.val))
if node.right:
nodes.append(node.right)
if node.left:
nodes.append(n... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_015112 | 1,324 | permissive | [
{
"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 | stack_v2_sparse_classes_30k_train_008297 | 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... | 8a10b23335d8e9f080e5c39715b38bcc2916ff00 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
result = []
nodes = [root]
while nodes:
node = nodes.pop()
result.append(str(node.val))
if node.right:
... | the_stack_v2_python_sparse | Leetcode/449. Serialize and Deserialize BST/solution2.py | hi0t/Outtalent | train | 0 | |
d2ba59450ffeaa5c58861076ccb13821ce534094 | [
"if not root:\n return []\nself.res = []\nself._dfs(root, sum, [])\nreturn self.res",
"path.append(root.val)\nsum -= root.val\nif sum == 0 and (not root.left) and (not root.right):\n self.res.append(path[:])\n path.pop()\n return\nif root.left:\n self._dfs(root.left, sum, path)\nif root.right:\n ... | <|body_start_0|>
if not root:
return []
self.res = []
self._dfs(root, sum, [])
return self.res
<|end_body_0|>
<|body_start_1|>
path.append(root.val)
sum -= root.val
if sum == 0 and (not root.left) and (not root.right):
self.res.append(path... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: list[list[int]]"""
<|body_0|>
def _dfs(self, root, sum, path):
"""Args: root: TreeNode sum: int path: list[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not r... | stack_v2_sparse_classes_36k_train_015113 | 980 | no_license | [
{
"docstring": "Args: root: TreeNode sum: int Return: list[list[int]]",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": "Args: root: TreeNode sum: int path: list[int]",
"name": "_dfs",
"signature": "def _dfs(self, root, sum, path)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Args: root: TreeNode sum: int Return: list[list[int]]
- def _dfs(self, root, sum, path): Args: root: TreeNode sum: int path: list[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Args: root: TreeNode sum: int Return: list[list[int]]
- def _dfs(self, root, sum, path): Args: root: TreeNode sum: int path: list[int]
<|skeleton|>... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: list[list[int]]"""
<|body_0|>
def _dfs(self, root, sum, path):
"""Args: root: TreeNode sum: int path: list[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: list[list[int]]"""
if not root:
return []
self.res = []
self._dfs(root, sum, [])
return self.res
def _dfs(self, root, sum, path):
"""Args: root: TreeNode sum: int p... | the_stack_v2_python_sparse | code/面试题34. 二叉树中和为某一值的路径.py | AiZhanghan/Leetcode | train | 0 | |
247abecba3df35747b25a648538f0bd9473cd0b6 | [
"self.input_base = input_base\nself.output_base = output_base\nself.projects_file = projects_file\nself.dump_type = dump_type\nself.dump_date = dump_date\nself.max_tries = max_tries\nself.overwrite = overwrite\nself.dry_run = dry_run\nself._validate_parameters()\npath_dump_type = dump_type.replace('-', '_')\nself.o... | <|body_start_0|>
self.input_base = input_base
self.output_base = output_base
self.projects_file = projects_file
self.dump_type = dump_type
self.dump_date = dump_date
self.max_tries = max_tries
self.overwrite = overwrite
self.dry_run = dry_run
self.... | This class manages importing multiple wiki-project XML-dumps onto HDFS. It checks the output-base path validity, possibly deleting it in case of overwrite, builds the list of projects to import from a file and launches imports using MediawikiProjectDumpImporter. When all imports are finished, a success-flag file is wri... | MediawikiDumpsImporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediawikiDumpsImporter:
"""This class manages importing multiple wiki-project XML-dumps onto HDFS. It checks the output-base path validity, possibly deleting it in case of overwrite, builds the list of projects to import from a file and launches imports using MediawikiProjectDumpImporter. When al... | stack_v2_sparse_classes_36k_train_015114 | 19,943 | no_license | [
{
"docstring": "Initializes variables and validates parameters",
"name": "__init__",
"signature": "def __init__(self, input_base, output_base, projects_file, dump_type, dump_date, max_tries, overwrite, dry_run)"
},
{
"docstring": "Validates that dump-date contains 8 digits, that the file contain... | 5 | stack_v2_sparse_classes_30k_train_003150 | Implement the Python class `MediawikiDumpsImporter` described below.
Class description:
This class manages importing multiple wiki-project XML-dumps onto HDFS. It checks the output-base path validity, possibly deleting it in case of overwrite, builds the list of projects to import from a file and launches imports usin... | Implement the Python class `MediawikiDumpsImporter` described below.
Class description:
This class manages importing multiple wiki-project XML-dumps onto HDFS. It checks the output-base path validity, possibly deleting it in case of overwrite, builds the list of projects to import from a file and launches imports usin... | d62f281b092a3802ff7858f9b145b0faa0c9baab | <|skeleton|>
class MediawikiDumpsImporter:
"""This class manages importing multiple wiki-project XML-dumps onto HDFS. It checks the output-base path validity, possibly deleting it in case of overwrite, builds the list of projects to import from a file and launches imports using MediawikiProjectDumpImporter. When al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MediawikiDumpsImporter:
"""This class manages importing multiple wiki-project XML-dumps onto HDFS. It checks the output-base path validity, possibly deleting it in case of overwrite, builds the list of projects to import from a file and launches imports using MediawikiProjectDumpImporter. When all imports are... | the_stack_v2_python_sparse | bin/import-mediawiki-dumps | wikimedia/analytics-refinery | train | 17 |
caccb734707b1ce314af178a2558160ef6ccbaa1 | [
"files = self.files.getlist('file_field')\nfor file in files:\n validators.validate_filename(file.name)\n if not file:\n raise forms.ValidationError('Could not read file: %(file_name)s', params={'file_name': file.name})\nfor file in files:\n if file.size > ActiveProject.INDIVIDUAL_FILE_SIZE_LIMIT:\n... | <|body_start_0|>
files = self.files.getlist('file_field')
for file in files:
validators.validate_filename(file.name)
if not file:
raise forms.ValidationError('Could not read file: %(file_name)s', params={'file_name': file.name})
for file in files:
... | Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root. | UploadFilesForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadFilesForm:
"""Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""
def clean_file_field(self):
"""Check for file name, size limits and whether they are readable"""
<|body_0|>
def perform_action(self):
... | stack_v2_sparse_classes_36k_train_015115 | 45,155 | permissive | [
{
"docstring": "Check for file name, size limits and whether they are readable",
"name": "clean_file_field",
"signature": "def clean_file_field(self)"
},
{
"docstring": "Upload the files",
"name": "perform_action",
"signature": "def perform_action(self)"
}
] | 2 | null | Implement the Python class `UploadFilesForm` described below.
Class description:
Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root.
Method signatures and docstrings:
- def clean_file_field(self): Check for file name, size limits and whether they are readabl... | Implement the Python class `UploadFilesForm` described below.
Class description:
Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root.
Method signatures and docstrings:
- def clean_file_field(self): Check for file name, size limits and whether they are readabl... | 304e093dc550da8636552dc601d6545c07ffc771 | <|skeleton|>
class UploadFilesForm:
"""Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""
def clean_file_field(self):
"""Check for file name, size limits and whether they are readable"""
<|body_0|>
def perform_action(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadFilesForm:
"""Form for uploading multiple files to a project. `subdir` is the project subdirectory relative to the file root."""
def clean_file_field(self):
"""Check for file name, size limits and whether they are readable"""
files = self.files.getlist('file_field')
for file... | the_stack_v2_python_sparse | physionet-django/project/forms.py | MIT-LCP/physionet-build | train | 50 |
7c3f55e49c21ef73190fc2778eb1d36ff10ffde9 | [
"def dfs(i, remains: List[int]):\n if i == n + 1:\n return 1\n cnt = 0\n for j in range(1, n + 1):\n if remains[j] is None and (i % j == 0 or j % i == 0):\n remains[j] = i\n cnt += dfs(i + 1, remains)\n remains[j] = None\n return cnt\nreturn dfs(1, [None] *... | <|body_start_0|>
def dfs(i, remains: List[int]):
if i == n + 1:
return 1
cnt = 0
for j in range(1, n + 1):
if remains[j] is None and (i % j == 0 or j % i == 0):
remains[j] = i
cnt += dfs(i + 1, remains)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countArrangement(self, n: int) -> int:
"""DFS using a list"""
<|body_0|>
def countArrangement(self, n: int) -> int:
"""DFS using a binary number to make argument hashable for caching"""
<|body_1|>
def countArrangement(self, n: int) -> int:
... | stack_v2_sparse_classes_36k_train_015116 | 2,867 | no_license | [
{
"docstring": "DFS using a list",
"name": "countArrangement",
"signature": "def countArrangement(self, n: int) -> int"
},
{
"docstring": "DFS using a binary number to make argument hashable for caching",
"name": "countArrangement",
"signature": "def countArrangement(self, n: int) -> int... | 3 | stack_v2_sparse_classes_30k_train_005225 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countArrangement(self, n: int) -> int: DFS using a list
- def countArrangement(self, n: int) -> int: DFS using a binary number to make argument hashable for caching
- def cou... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countArrangement(self, n: int) -> int: DFS using a list
- def countArrangement(self, n: int) -> int: DFS using a binary number to make argument hashable for caching
- def cou... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def countArrangement(self, n: int) -> int:
"""DFS using a list"""
<|body_0|>
def countArrangement(self, n: int) -> int:
"""DFS using a binary number to make argument hashable for caching"""
<|body_1|>
def countArrangement(self, n: int) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countArrangement(self, n: int) -> int:
"""DFS using a list"""
def dfs(i, remains: List[int]):
if i == n + 1:
return 1
cnt = 0
for j in range(1, n + 1):
if remains[j] is None and (i % j == 0 or j % i == 0):
... | the_stack_v2_python_sparse | leetcode/solved/526_Beautiful_Arrangement/solution.py | sungminoh/algorithms | train | 0 | |
e571d7c568ee31bdb35b9f47c4cde2ba362fca3d | [
"try:\n self.sqlhandler = None\n self.teaId = self.get_argument('teaId')\n self.teaName = self.get_argument('teaName')\n self.teaPassword = self.get_argument('teaPassword')\n if self.AddTea():\n self.write('success')\n self.finish()\n else:\n raise RuntimeError\nexcept Excepti... | <|body_start_0|>
try:
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
self.teaName = self.get_argument('teaName')
self.teaPassword = self.get_argument('teaPassword')
if self.AddTea():
self.write('success')
... | AdmAddTeaRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdmAddTeaRequestHandler:
def post(self):
"""增加老师"""
<|body_0|>
def AddTea(self):
"""将老师信息写入数据库"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
se... | stack_v2_sparse_classes_36k_train_015117 | 1,734 | no_license | [
{
"docstring": "增加老师",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "将老师信息写入数据库",
"name": "AddTea",
"signature": "def AddTea(self)"
}
] | 2 | null | Implement the Python class `AdmAddTeaRequestHandler` described below.
Class description:
Implement the AdmAddTeaRequestHandler class.
Method signatures and docstrings:
- def post(self): 增加老师
- def AddTea(self): 将老师信息写入数据库 | Implement the Python class `AdmAddTeaRequestHandler` described below.
Class description:
Implement the AdmAddTeaRequestHandler class.
Method signatures and docstrings:
- def post(self): 增加老师
- def AddTea(self): 将老师信息写入数据库
<|skeleton|>
class AdmAddTeaRequestHandler:
def post(self):
"""增加老师"""
<|b... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class AdmAddTeaRequestHandler:
def post(self):
"""增加老师"""
<|body_0|>
def AddTea(self):
"""将老师信息写入数据库"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdmAddTeaRequestHandler:
def post(self):
"""增加老师"""
try:
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
self.teaName = self.get_argument('teaName')
self.teaPassword = self.get_argument('teaPassword')
if self.AddTea():
... | the_stack_v2_python_sparse | app/src/main/pythonWork/AdmAddTeaRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
ee10de1c9024608da759bcf5af3016d5bc340c91 | [
"get_proxy_objects = []\nget_proxy_objects.clear()\nfor pxyobj in bpy.data.scenes[bpy.context.scene.name].objects:\n if pxyobj.type == 'ARMATURE':\n name = pxyobj.name[:]\n get_proxy_objects.append((name, name, name))\nget_proxy_objects.sort()\nreturn get_proxy_objects",
"get_object_bones = []\ng... | <|body_start_0|>
get_proxy_objects = []
get_proxy_objects.clear()
for pxyobj in bpy.data.scenes[bpy.context.scene.name].objects:
if pxyobj.type == 'ARMATURE':
name = pxyobj.name[:]
get_proxy_objects.append((name, name, name))
get_proxy_objects.... | Property Used for the whole GUI in general | MasterProperties | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MasterProperties:
"""Property Used for the whole GUI in general"""
def proxy_objects(self, context):
"""Obtains a list of proxy objects from the active scene, handles reference bug in Blender 2.6x +"""
<|body_0|>
def bone_objects(self, context):
"""Obtains a list... | stack_v2_sparse_classes_36k_train_015118 | 32,908 | no_license | [
{
"docstring": "Obtains a list of proxy objects from the active scene, handles reference bug in Blender 2.6x +",
"name": "proxy_objects",
"signature": "def proxy_objects(self, context)"
},
{
"docstring": "Obtains a list of 'proxy' objects from the active scene, handles reference bug in Blender 2... | 2 | stack_v2_sparse_classes_30k_train_005054 | Implement the Python class `MasterProperties` described below.
Class description:
Property Used for the whole GUI in general
Method signatures and docstrings:
- def proxy_objects(self, context): Obtains a list of proxy objects from the active scene, handles reference bug in Blender 2.6x +
- def bone_objects(self, con... | Implement the Python class `MasterProperties` described below.
Class description:
Property Used for the whole GUI in general
Method signatures and docstrings:
- def proxy_objects(self, context): Obtains a list of proxy objects from the active scene, handles reference bug in Blender 2.6x +
- def bone_objects(self, con... | 0788f00283d7c8c083aa5d554eb1f32c201adbd6 | <|skeleton|>
class MasterProperties:
"""Property Used for the whole GUI in general"""
def proxy_objects(self, context):
"""Obtains a list of proxy objects from the active scene, handles reference bug in Blender 2.6x +"""
<|body_0|>
def bone_objects(self, context):
"""Obtains a list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MasterProperties:
"""Property Used for the whole GUI in general"""
def proxy_objects(self, context):
"""Obtains a list of proxy objects from the active scene, handles reference bug in Blender 2.6x +"""
get_proxy_objects = []
get_proxy_objects.clear()
for pxyobj in bpy.data... | the_stack_v2_python_sparse | repos/blender_addons/internal/2.7.x/addon_closeup_cam_2.py | BlenderCN-Org/working_files | train | 0 |
b9f28ae4e3d87fe52bcefec02907c0cc5e86784d | [
"res = list()\nsize = sum([len(word) for word in words])\nt1 = {}\nfor w in words:\n if w not in t1:\n t1[w] = 0\n t1[w] += 1\nfor i in range(len(s)):\n index, l, r = (i, i, i + size + 1)\n t2 = {}\n while index < r:\n if s[l:index] not in t1:\n index += 1\n else:\n ... | <|body_start_0|>
res = list()
size = sum([len(word) for word in words])
t1 = {}
for w in words:
if w not in t1:
t1[w] = 0
t1[w] += 1
for i in range(len(s)):
index, l, r = (i, i, i + size + 1)
t2 = {}
whil... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
"""串联所有单词的子串: 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。"""
<|body_0|>
def findSubstring2(self, s: str, words: List[str]) -> ... | stack_v2_sparse_classes_36k_train_015119 | 16,629 | no_license | [
{
"docstring": "串联所有单词的子串: 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。",
"name": "findSubstring",
"signature": "def findSubstring(self, s: str, words: List[str]) -> List[int]"
},
{
"docstring": "串联所有单词的子串: 给定一个字符串 s 和一些长度... | 2 | stack_v2_sparse_classes_30k_train_020582 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstring(self, s: str, words: List[str]) -> List[int]: 串联所有单词的子串: 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstring(self, s: str, words: List[str]) -> List[int]: 串联所有单词的子串: 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 ... | d74389704de4ce519a22061191b626b7204d4dbc | <|skeleton|>
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
"""串联所有单词的子串: 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。"""
<|body_0|>
def findSubstring2(self, s: str, words: List[str]) -> ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
"""串联所有单词的子串: 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。"""
res = list()
size = sum([len(word) for word in words])
t1 = {}
... | the_stack_v2_python_sparse | 05_doublepoint/difficulty_30_findSubstring.py | MrLW/algorithm | train | 0 | |
5641c488f5ecfe5ab7afd86b7f5d47ebe158fd71 | [
"r = len(matrix)\nc = len(matrix[0])\nrow = [0] * r\ncol = [0] * c\nfor i in range(r):\n for j in range(c):\n if matrix[i][j] == 0:\n row[i] = 1\n col[j] = 1\nfor i in range(r):\n for j in range(c):\n if row[i] == 1 or col[j] == 1:\n matrix[i][j] = 0",
"r = len... | <|body_start_0|>
r = len(matrix)
c = len(matrix[0])
row = [0] * r
col = [0] * c
for i in range(r):
for j in range(c):
if matrix[i][j] == 0:
row[i] = 1
col[j] = 1
for i in range(r):
for j in ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body... | stack_v2_sparse_classes_36k_train_015120 | 1,827 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def setZeroes(self, matrix: List[List[int]]) -> None: Do not retur... | aefc8006ccac4a4720dda1bd932a04fd1880ec9d | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
r = len(matrix)
c = len(matrix[0])
row = [0] * r
col = [0] * c
for i in range(r):
for j in range(c):
if matr... | the_stack_v2_python_sparse | Strings/boolean_matrix.py | viswan29/Leetcode | train | 0 | |
1c1666046b11d1cec2e1e545eb39eca3026644f2 | [
"if not hasattr(self, 'formset_name'):\n raise NotImplementedError(\"'formset_name' is not defined\")\nif not hasattr(self, 'formset'):\n raise NotImplementedError(\"'formset' is not defined\")\nsuper().__init__(*args, **kwargs)",
"context = super().get_context_data(**kwargs)\nif self.request.POST:\n if ... | <|body_start_0|>
if not hasattr(self, 'formset_name'):
raise NotImplementedError("'formset_name' is not defined")
if not hasattr(self, 'formset'):
raise NotImplementedError("'formset' is not defined")
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | Baseview for creating a module using a formset for a Foreignkey linked model. Can be subclassed by modulecreateviews needing to use a formset. | FormsetModuleCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormsetModuleCreateView:
"""Baseview for creating a module using a formset for a Foreignkey linked model. Can be subclassed by modulecreateviews needing to use a formset."""
def __init__(self, *args, **kwargs):
"""Views need to set two attributes: formset_name which is what the form ... | stack_v2_sparse_classes_36k_train_015121 | 30,024 | no_license | [
{
"docstring": "Views need to set two attributes: formset_name which is what the form will be called in the template context. formset Formset to be used.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "adds the formset to the context.",
"name": "ge... | 3 | stack_v2_sparse_classes_30k_train_009358 | Implement the Python class `FormsetModuleCreateView` described below.
Class description:
Baseview for creating a module using a formset for a Foreignkey linked model. Can be subclassed by modulecreateviews needing to use a formset.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Views need to... | Implement the Python class `FormsetModuleCreateView` described below.
Class description:
Baseview for creating a module using a formset for a Foreignkey linked model. Can be subclassed by modulecreateviews needing to use a formset.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Views need to... | 07d1387e83775bf8bd3d6f97f2a9c5d909e5119f | <|skeleton|>
class FormsetModuleCreateView:
"""Baseview for creating a module using a formset for a Foreignkey linked model. Can be subclassed by modulecreateviews needing to use a formset."""
def __init__(self, *args, **kwargs):
"""Views need to set two attributes: formset_name which is what the form ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormsetModuleCreateView:
"""Baseview for creating a module using a formset for a Foreignkey linked model. Can be subclassed by modulecreateviews needing to use a formset."""
def __init__(self, *args, **kwargs):
"""Views need to set two attributes: formset_name which is what the form will be calle... | the_stack_v2_python_sparse | pages/views.py | aspigirlcodes/uniqid | train | 2 |
6f58f47950723cbe3c286397077abbc51661877d | [
"func = self._module.learning_curve\ndata = self._data\ntarget = self._target\ntr_size, tr_score, te_score = func(estimator, *args, X=data.values, y=target.values, **kwargs)\nreturn (tr_size, tr_score, te_score)",
"func = self._module.validation_curve\ndata = self._data\ntarget = self._target\ntr_score, te_score ... | <|body_start_0|>
func = self._module.learning_curve
data = self._data
target = self._target
tr_size, tr_score, te_score = func(estimator, *args, X=data.values, y=target.values, **kwargs)
return (tr_size, tr_score, te_score)
<|end_body_0|>
<|body_start_1|>
func = self._mo... | Deprecated. Accessor to ``sklearn.learning_curve``. | LearningCurveMethods | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningCurveMethods:
"""Deprecated. Accessor to ``sklearn.learning_curve``."""
def learning_curve(self, estimator, *args, **kwargs):
"""Call ``sklearn.lerning_curve.learning_curve`` using automatic mapping. - ``X``: ``ModelFrame.data`` - ``y``: ``ModelFrame.target``"""
<|bod... | stack_v2_sparse_classes_36k_train_015122 | 1,422 | permissive | [
{
"docstring": "Call ``sklearn.lerning_curve.learning_curve`` using automatic mapping. - ``X``: ``ModelFrame.data`` - ``y``: ``ModelFrame.target``",
"name": "learning_curve",
"signature": "def learning_curve(self, estimator, *args, **kwargs)"
},
{
"docstring": "Call ``sklearn.learning_curve.vali... | 2 | stack_v2_sparse_classes_30k_train_000478 | Implement the Python class `LearningCurveMethods` described below.
Class description:
Deprecated. Accessor to ``sklearn.learning_curve``.
Method signatures and docstrings:
- def learning_curve(self, estimator, *args, **kwargs): Call ``sklearn.lerning_curve.learning_curve`` using automatic mapping. - ``X``: ``ModelFra... | Implement the Python class `LearningCurveMethods` described below.
Class description:
Deprecated. Accessor to ``sklearn.learning_curve``.
Method signatures and docstrings:
- def learning_curve(self, estimator, *args, **kwargs): Call ``sklearn.lerning_curve.learning_curve`` using automatic mapping. - ``X``: ``ModelFra... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class LearningCurveMethods:
"""Deprecated. Accessor to ``sklearn.learning_curve``."""
def learning_curve(self, estimator, *args, **kwargs):
"""Call ``sklearn.lerning_curve.learning_curve`` using automatic mapping. - ``X``: ``ModelFrame.data`` - ``y``: ``ModelFrame.target``"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearningCurveMethods:
"""Deprecated. Accessor to ``sklearn.learning_curve``."""
def learning_curve(self, estimator, *args, **kwargs):
"""Call ``sklearn.lerning_curve.learning_curve`` using automatic mapping. - ``X``: ``ModelFrame.data`` - ``y``: ``ModelFrame.target``"""
func = self._modul... | the_stack_v2_python_sparse | lib/python2.7/site-packages/pandas_ml/skaccessors/learning_curve.py | wangyum/Anaconda | train | 11 |
d4f29c641f4c48932a7e44f2126058fadfd14650 | [
"citations.sort()\nfor cut in range(len(citations), -1, -1):\n h = len(citations) - cut\n r = all([i >= h for i in citations[cut:]])\n l = all([i <= h for i in citations[:cut]])\n if r and l:\n return h",
"citations.sort()\nfor cut in range(len(citations), -1, -1):\n h = len(citations) - cut... | <|body_start_0|>
citations.sort()
for cut in range(len(citations), -1, -1):
h = len(citations) - cut
r = all([i >= h for i in citations[cut:]])
l = all([i <= h for i in citations[:cut]])
if r and l:
return h
<|end_body_0|>
<|body_start_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hIndex(self, citations: list):
""":type citations: List[int] :rtype: int 思想1: 排序,设置一个cut,切为左和右, 右边都>= cut的值 左边都<=cut的值"""
<|body_0|>
def hIndex2(self, citations: list):
""":type citations: List[int] :rtype: int 思想2: 在思想1的基础上,左边满足,则右边一定为会满足"""
<|... | stack_v2_sparse_classes_36k_train_015123 | 1,062 | no_license | [
{
"docstring": ":type citations: List[int] :rtype: int 思想1: 排序,设置一个cut,切为左和右, 右边都>= cut的值 左边都<=cut的值",
"name": "hIndex",
"signature": "def hIndex(self, citations: list)"
},
{
"docstring": ":type citations: List[int] :rtype: int 思想2: 在思想1的基础上,左边满足,则右边一定为会满足",
"name": "hIndex2",
"signature... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hIndex(self, citations: list): :type citations: List[int] :rtype: int 思想1: 排序,设置一个cut,切为左和右, 右边都>= cut的值 左边都<=cut的值
- def hIndex2(self, citations: list): :type citations: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hIndex(self, citations: list): :type citations: List[int] :rtype: int 思想1: 排序,设置一个cut,切为左和右, 右边都>= cut的值 左边都<=cut的值
- def hIndex2(self, citations: list): :type citations: Lis... | d1ddcbabfa7cc4d4f41b46f21f3227984f57bc40 | <|skeleton|>
class Solution:
def hIndex(self, citations: list):
""":type citations: List[int] :rtype: int 思想1: 排序,设置一个cut,切为左和右, 右边都>= cut的值 左边都<=cut的值"""
<|body_0|>
def hIndex2(self, citations: list):
""":type citations: List[int] :rtype: int 思想2: 在思想1的基础上,左边满足,则右边一定为会满足"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hIndex(self, citations: list):
""":type citations: List[int] :rtype: int 思想1: 排序,设置一个cut,切为左和右, 右边都>= cut的值 左边都<=cut的值"""
citations.sort()
for cut in range(len(citations), -1, -1):
h = len(citations) - cut
r = all([i >= h for i in citations[cut:]])... | the_stack_v2_python_sparse | 手写排序/274_h_index.py | whitefly/leetcode_python | train | 6 | |
e1aa91b139a55333473e03e43cb6a7a384085eae | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('sbrz_nedg', 'sbrz_nedg')\ndb = client.repo\ncollection = db['sbrz_nedg.college_university']\nx = []\ncolleges = collection.find({}, {'properties.Name': 1, 'properties.Latitude': 1, 'properties.Longitude'... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('sbrz_nedg', 'sbrz_nedg')
db = client.repo
collection = db['sbrz_nedg.college_university']
x = []
colleges = collection.find({}, {'... | selectCollegeCoords | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class selectCollegeCoords:
def execute(trial=False):
"""Select all of the addresses from the College/Universities data set"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything hap... | stack_v2_sparse_classes_36k_train_015124 | 3,183 | no_license | [
{
"docstring": "Select all of the addresses from the College/Universities data set",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document de... | 2 | stack_v2_sparse_classes_30k_train_015627 | Implement the Python class `selectCollegeCoords` described below.
Class description:
Implement the selectCollegeCoords class.
Method signatures and docstrings:
- def execute(trial=False): Select all of the addresses from the College/Universities data set
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | Implement the Python class `selectCollegeCoords` described below.
Class description:
Implement the selectCollegeCoords class.
Method signatures and docstrings:
- def execute(trial=False): Select all of the addresses from the College/Universities data set
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class selectCollegeCoords:
def execute(trial=False):
"""Select all of the addresses from the College/Universities data set"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything hap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class selectCollegeCoords:
def execute(trial=False):
"""Select all of the addresses from the College/Universities data set"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('sbrz_nedg', 'sbrz_nedg')
db = cli... | the_stack_v2_python_sparse | sbrz_nedg/selectCollegeCoords.py | ROODAY/course-2017-fal-proj | train | 3 | |
2dafe5a1ba6b43768bee8e2c8b0c45c331c3705e | [
"result = []\n\ndef output(done: str, remain_L, remain_R):\n \"\"\"\n 我考虑插入右括号的时候只要左括号数大于右括号就行了\n :param done:\n :param remain_L:\n :param remain_R:\n :return:\n \"\"\"\n if remain_R == 0:\n result.append(done)\n return 0\n if ... | <|body_start_0|>
result = []
def output(done: str, remain_L, remain_R):
"""
我考虑插入右括号的时候只要左括号数大于右括号就行了
:param done:
:param remain_L:
:param remain_R:
:return:
"""
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 我的做法 :param n: :return:"""
<|body_0|>
def generateParenthesis1(self, n: int) -> List[str]:
"""看官网上的题解试图使用动态规划的方法 。。。。 2020/11/11 实际上是记忆化搜索啊 :param n: :retur... | stack_v2_sparse_classes_36k_train_015125 | 1,704 | no_license | [
{
"docstring": "给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 我的做法 :param n: :return:",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n: int) -> List[str]"
},
{
"docstring": "看官网上的题解试图使用动态规划的方法 。。。。 2020/11/11 实际上是记忆化搜索啊 :param n: :return:",
"name": "generatePare... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 我的做法 :param n: :return:
- def generateParenthesis1(self, n: int) -> List[str]: 看... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 我的做法 :param n: :return:
- def generateParenthesis1(self, n: int) -> List[str]: 看... | e7a7b7537edbbb8fa35c2dddf2b122cf863e479d | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 我的做法 :param n: :return:"""
<|body_0|>
def generateParenthesis1(self, n: int) -> List[str]:
"""看官网上的题解试图使用动态规划的方法 。。。。 2020/11/11 实际上是记忆化搜索啊 :param n: :retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 我的做法 :param n: :return:"""
result = []
def output(done: str, remain_L, remain_R):
"""
我考虑插入右括号的时候只要左括号数大于右括号就行了
:param don... | the_stack_v2_python_sparse | Dynamic programming/括号生成L22.py | QiuHongHao123/Algorithm-Practise | train | 0 | |
36b029a8aad5a55b7ede26b49f72e7c0dfb6ec55 | [
"card_effect: CardEffect = CardEffect.objects.filter(has_modifier=True).first()\npower = None\nrange_ = None\nself.assertIsNotNone(card_effect)\nself.assertRaises(serializers.ValidationError, validate_effect_modifiers, card_effect, power, range_)",
"card_effect: CardEffect = CardEffect.objects.filter(has_modifier... | <|body_start_0|>
card_effect: CardEffect = CardEffect.objects.filter(has_modifier=True).first()
power = None
range_ = None
self.assertIsNotNone(card_effect)
self.assertRaises(serializers.ValidationError, validate_effect_modifiers, card_effect, power, range_)
<|end_body_0|>
<|bod... | ValidateEffectModifiersTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidateEffectModifiersTestCase:
def test_validate_effect_modifiers1(self):
"""Scenario: Effect which should have modifiers is provided. Modifiers are not provided. Expected result: ValidationError is raised."""
<|body_0|>
def test_validate_effect_modifiers2(self):
"... | stack_v2_sparse_classes_36k_train_015126 | 27,991 | permissive | [
{
"docstring": "Scenario: Effect which should have modifiers is provided. Modifiers are not provided. Expected result: ValidationError is raised.",
"name": "test_validate_effect_modifiers1",
"signature": "def test_validate_effect_modifiers1(self)"
},
{
"docstring": "Scenario: Effect which should... | 2 | null | Implement the Python class `ValidateEffectModifiersTestCase` described below.
Class description:
Implement the ValidateEffectModifiersTestCase class.
Method signatures and docstrings:
- def test_validate_effect_modifiers1(self): Scenario: Effect which should have modifiers is provided. Modifiers are not provided. Exp... | Implement the Python class `ValidateEffectModifiersTestCase` described below.
Class description:
Implement the ValidateEffectModifiersTestCase class.
Method signatures and docstrings:
- def test_validate_effect_modifiers1(self): Scenario: Effect which should have modifiers is provided. Modifiers are not provided. Exp... | ea812b13de0cd6c47c541cbede2d016a7837b4b8 | <|skeleton|>
class ValidateEffectModifiersTestCase:
def test_validate_effect_modifiers1(self):
"""Scenario: Effect which should have modifiers is provided. Modifiers are not provided. Expected result: ValidationError is raised."""
<|body_0|>
def test_validate_effect_modifiers2(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidateEffectModifiersTestCase:
def test_validate_effect_modifiers1(self):
"""Scenario: Effect which should have modifiers is provided. Modifiers are not provided. Expected result: ValidationError is raised."""
card_effect: CardEffect = CardEffect.objects.filter(has_modifier=True).first()
... | the_stack_v2_python_sparse | WMIAdventure/backend/WMIAdventure_backend/cards/tests.py | Michal-Czekanski/WMIAdventure-1 | train | 0 | |
0ad62148204938c5ab7c9f3f836c6f7bc2f50b2e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosUpdateConfiguration()",
"from .day_of_week import DayOfWeek\nfrom .device_configuration import DeviceConfiguration\nfrom .day_of_week import DayOfWeek\nfrom .device_configuration import DeviceConfiguration\nfields: Dict[str, Callabl... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosUpdateConfiguration()
<|end_body_0|>
<|body_start_1|>
from .day_of_week import DayOfWeek
from .device_configuration import DeviceConfiguration
from .day_of_week import DayOfWe... | IOS Update Configuration, allows you to configure time window within week to install iOS updates | IosUpdateConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosUpdateConfiguration:
"""IOS Update Configuration, allows you to configure time window within week to install iOS updates"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfiguration:
"""Creates a new instance of the appropriate class based... | stack_v2_sparse_classes_36k_train_015127 | 3,544 | 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: IosUpdateConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_012390 | Implement the Python class `IosUpdateConfiguration` described below.
Class description:
IOS Update Configuration, allows you to configure time window within week to install iOS updates
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfigurati... | Implement the Python class `IosUpdateConfiguration` described below.
Class description:
IOS Update Configuration, allows you to configure time window within week to install iOS updates
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfigurati... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosUpdateConfiguration:
"""IOS Update Configuration, allows you to configure time window within week to install iOS updates"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfiguration:
"""Creates a new instance of the appropriate class based... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IosUpdateConfiguration:
"""IOS Update Configuration, allows you to configure time window within week to install iOS updates"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfiguration:
"""Creates a new instance of the appropriate class based on discrimin... | the_stack_v2_python_sparse | msgraph/generated/models/ios_update_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
c2e64bcf6b051310957c2abeff9a87a4dffe4e04 | [
"try:\n res = requests.get(url, params=params, **kw)\nexcept Exception as e:\n logging.error('访问不成功')\nelse:\n return res",
"try:\n res = requests.post(url, data=data, json=json, **kw)\nexcept Exception as e:\n logging.error('访问不成功')\nelse:\n return res",
"if method.lower() == 'get':\n res ... | <|body_start_0|>
try:
res = requests.get(url, params=params, **kw)
except Exception as e:
logging.error('访问不成功')
else:
return res
<|end_body_0|>
<|body_start_1|>
try:
res = requests.post(url, data=data, json=json, **kw)
except Exce... | RequestsHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsHandler:
def get(self, url, params=None, **kw):
"""发送get请求"""
<|body_0|>
def post(self, url, data=None, json=None, **kw):
"""发送 post 请求"""
<|body_1|>
def visit(self, method, url, params=None, data=None, json=None, **kw):
"""访问接口"""
... | stack_v2_sparse_classes_36k_train_015128 | 3,238 | no_license | [
{
"docstring": "发送get请求",
"name": "get",
"signature": "def get(self, url, params=None, **kw)"
},
{
"docstring": "发送 post 请求",
"name": "post",
"signature": "def post(self, url, data=None, json=None, **kw)"
},
{
"docstring": "访问接口",
"name": "visit",
"signature": "def visit(... | 4 | null | Implement the Python class `RequestsHandler` described below.
Class description:
Implement the RequestsHandler class.
Method signatures and docstrings:
- def get(self, url, params=None, **kw): 发送get请求
- def post(self, url, data=None, json=None, **kw): 发送 post 请求
- def visit(self, method, url, params=None, data=None, ... | Implement the Python class `RequestsHandler` described below.
Class description:
Implement the RequestsHandler class.
Method signatures and docstrings:
- def get(self, url, params=None, **kw): 发送get请求
- def post(self, url, data=None, json=None, **kw): 发送 post 请求
- def visit(self, method, url, params=None, data=None, ... | cfadd3132c2c7c518c784589e0dab6510a662a6c | <|skeleton|>
class RequestsHandler:
def get(self, url, params=None, **kw):
"""发送get请求"""
<|body_0|>
def post(self, url, data=None, json=None, **kw):
"""发送 post 请求"""
<|body_1|>
def visit(self, method, url, params=None, data=None, json=None, **kw):
"""访问接口"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsHandler:
def get(self, url, params=None, **kw):
"""发送get请求"""
try:
res = requests.get(url, params=params, **kw)
except Exception as e:
logging.error('访问不成功')
else:
return res
def post(self, url, data=None, json=None, **kw):
... | the_stack_v2_python_sparse | lemon/python22/lemon_23_191018_登录接口框架/ZZZZ_上课代码/common/requests_handler.py | songyongzhuang/PythonCode_office | train | 0 | |
51b556ae5268bd51fc2bcc206b0b3cf2f0eb27c6 | [
"super(PredictDataset, self).__init__(fp, fr, standardize_proteins, standardize_rnas, verbose)\nself.to_predict = to_predict\nif self.to_predict is not None:\n self.Fp = self.Fp[self.to_predict]",
"if self.verbose:\n print('\\nPreparing dataset (%d protein%s and %d RNA%s)...' % (self.Fp.shape[1], (self.Fp.s... | <|body_start_0|>
super(PredictDataset, self).__init__(fp, fr, standardize_proteins, standardize_rnas, verbose)
self.to_predict = to_predict
if self.to_predict is not None:
self.Fp = self.Fp[self.to_predict]
<|end_body_0|>
<|body_start_1|>
if self.verbose:
print('... | Test dataset. | PredictDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictDataset:
"""Test dataset."""
def __init__(self, fp, fr, to_predict=None, standardize_proteins=False, standardize_rnas=False, verbose=True):
"""Constructor. Parameters ---------- fp : str The name of the HDF5 file containing features for the proteins. fr : str The name of the H... | stack_v2_sparse_classes_36k_train_015129 | 9,073 | permissive | [
{
"docstring": "Constructor. Parameters ---------- fp : str The name of the HDF5 file containing features for the proteins. fr : str The name of the HDF5 file containing features for the RNAs. to_predict : list (default : None) List of proteins from Fp to predict. If None all the proteins will be predicted. sta... | 2 | stack_v2_sparse_classes_30k_train_005966 | Implement the Python class `PredictDataset` described below.
Class description:
Test dataset.
Method signatures and docstrings:
- def __init__(self, fp, fr, to_predict=None, standardize_proteins=False, standardize_rnas=False, verbose=True): Constructor. Parameters ---------- fp : str The name of the HDF5 file contain... | Implement the Python class `PredictDataset` described below.
Class description:
Test dataset.
Method signatures and docstrings:
- def __init__(self, fp, fr, to_predict=None, standardize_proteins=False, standardize_rnas=False, verbose=True): Constructor. Parameters ---------- fp : str The name of the HDF5 file contain... | 840007ae9da2bb89ba5a60769e3bc885579c0a39 | <|skeleton|>
class PredictDataset:
"""Test dataset."""
def __init__(self, fp, fr, to_predict=None, standardize_proteins=False, standardize_rnas=False, verbose=True):
"""Constructor. Parameters ---------- fp : str The name of the HDF5 file containing features for the proteins. fr : str The name of the H... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredictDataset:
"""Test dataset."""
def __init__(self, fp, fr, to_predict=None, standardize_proteins=False, standardize_rnas=False, verbose=True):
"""Constructor. Parameters ---------- fp : str The name of the HDF5 file containing features for the proteins. fr : str The name of the HDF5 file cont... | the_stack_v2_python_sparse | rnacommender/data.py | xflicsu/RNAcommender | train | 0 |
7ff6f319c8faabf320d9503f456d562f6b21cf24 | [
"learnedForms = user.getLearnedFor(formInfo, languageContext.foreign)\nmasteryCache = BuildMasteryCache.ViaForms(learnedForms, formInfo, user)\nlearnedFormsHelper = PrequeriedFormsHelper(learnedForms, formInfo, languageContext)\nformsByRating = self.organizeByMastery(learnedForms, masteryCache)\nsample = self.getSa... | <|body_start_0|>
learnedForms = user.getLearnedFor(formInfo, languageContext.foreign)
masteryCache = BuildMasteryCache.ViaForms(learnedForms, formInfo, user)
learnedFormsHelper = PrequeriedFormsHelper(learnedForms, formInfo, languageContext)
formsByRating = self.organizeByMastery(learned... | Represents method to contstruct a Quiz from random learned Words or Symbols | RandomQuizFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomQuizFactory:
"""Represents method to contstruct a Quiz from random learned Words or Symbols"""
def buildQuiz(self, formInfo, user, languageContext):
"""Build a quiz using the from given and the user provided"""
<|body_0|>
def organizeByMastery(self, learnedForms, m... | stack_v2_sparse_classes_36k_train_015130 | 3,406 | no_license | [
{
"docstring": "Build a quiz using the from given and the user provided",
"name": "buildQuiz",
"signature": "def buildQuiz(self, formInfo, user, languageContext)"
},
{
"docstring": "Return the learned forms organized by their mastery rating",
"name": "organizeByMastery",
"signature": "de... | 4 | null | Implement the Python class `RandomQuizFactory` described below.
Class description:
Represents method to contstruct a Quiz from random learned Words or Symbols
Method signatures and docstrings:
- def buildQuiz(self, formInfo, user, languageContext): Build a quiz using the from given and the user provided
- def organiz... | Implement the Python class `RandomQuizFactory` described below.
Class description:
Represents method to contstruct a Quiz from random learned Words or Symbols
Method signatures and docstrings:
- def buildQuiz(self, formInfo, user, languageContext): Build a quiz using the from given and the user provided
- def organiz... | f08dc4465b7e4fb32235e1647c46edd4472f9093 | <|skeleton|>
class RandomQuizFactory:
"""Represents method to contstruct a Quiz from random learned Words or Symbols"""
def buildQuiz(self, formInfo, user, languageContext):
"""Build a quiz using the from given and the user provided"""
<|body_0|>
def organizeByMastery(self, learnedForms, m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomQuizFactory:
"""Represents method to contstruct a Quiz from random learned Words or Symbols"""
def buildQuiz(self, formInfo, user, languageContext):
"""Build a quiz using the from given and the user provided"""
learnedForms = user.getLearnedFor(formInfo, languageContext.foreign)
... | the_stack_v2_python_sparse | src/Quiz/random_quiz_factory.py | cloew/VocabTester | train | 0 |
d125dc95a8be592cce926eea0ee9c9107c033ead | [
"if not headA or not headB:\n return None\nS = set()\nha, hb = (headA, headB)\nwhile ha:\n S.add(headA)\n ha = ha.next\nwhile hb:\n if hb in S:\n return hb\n headB = headB.next\nreturn None",
"ha, hb = (headA, headB)\nwhile ha != hb:\n ha = ha.next if ha else headB\n hb = hb.next if hb... | <|body_start_0|>
if not headA or not headB:
return None
S = set()
ha, hb = (headA, headB)
while ha:
S.add(headA)
ha = ha.next
while hb:
if hb in S:
return hb
headB = headB.next
return None
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNodeBySet(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode 使用集合保存第一个链表 再遍历B查看B中的元素是否在集合中,如果存在返回"""
<|body_0|>
def getIntersectionNodeByTwoIndex(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode 使用双... | stack_v2_sparse_classes_36k_train_015131 | 1,467 | no_license | [
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode 使用集合保存第一个链表 再遍历B查看B中的元素是否在集合中,如果存在返回",
"name": "getIntersectionNodeBySet",
"signature": "def getIntersectionNodeBySet(self, headA, headB)"
},
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode 使用双指针 ha和hb分别指向headA和headB ha和... | 2 | stack_v2_sparse_classes_30k_train_006940 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNodeBySet(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode 使用集合保存第一个链表 再遍历B查看B中的元素是否在集合中,如果存在返回
- def getIntersectionNodeByTwoIndex(self, hea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNodeBySet(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode 使用集合保存第一个链表 再遍历B查看B中的元素是否在集合中,如果存在返回
- def getIntersectionNodeByTwoIndex(self, hea... | a3a1556abc5adb9325de54d64f9814e64b96db0f | <|skeleton|>
class Solution:
def getIntersectionNodeBySet(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode 使用集合保存第一个链表 再遍历B查看B中的元素是否在集合中,如果存在返回"""
<|body_0|>
def getIntersectionNodeByTwoIndex(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode 使用双... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNodeBySet(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode 使用集合保存第一个链表 再遍历B查看B中的元素是否在集合中,如果存在返回"""
if not headA or not headB:
return None
S = set()
ha, hb = (headA, headB)
while ha:
S.add(headA)
... | the_stack_v2_python_sparse | leetcode/linked_list/IntersectionNode.py | BigerWANG/geek_algorithm | train | 0 | |
9193651aa9e4d16d33f0b7b4bdc8307099a537b2 | [
"cmd_output = self._run_command([self.EXECUTABLE, '--version'])\nmatch = re.search('^Poetry version (?P<version>\\\\S*)', cmd_output)\nif not match:\n LOGGER.warning('unable to parse poetry version from output:\\n%s', cmd_output)\n return Version('0.0.0')\nreturn Version(match.group('version'))",
"pyproject... | <|body_start_0|>
cmd_output = self._run_command([self.EXECUTABLE, '--version'])
match = re.search('^Poetry version (?P<version>\\S*)', cmd_output)
if not match:
LOGGER.warning('unable to parse poetry version from output:\n%s', cmd_output)
return Version('0.0.0')
r... | Poetry dependency manager. | Poetry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poetry:
"""Poetry dependency manager."""
def version(self) -> Version:
"""poetry version."""
<|body_0|>
def dir_is_project(cls, directory: StrPath, **__kwargs: Any) -> bool:
"""Determine if the directory contains a project for this dependency manager. Args: direc... | stack_v2_sparse_classes_36k_train_015132 | 4,732 | permissive | [
{
"docstring": "poetry version.",
"name": "version",
"signature": "def version(self) -> Version"
},
{
"docstring": "Determine if the directory contains a project for this dependency manager. Args: directory: Directory to check.",
"name": "dir_is_project",
"signature": "def dir_is_project... | 3 | stack_v2_sparse_classes_30k_train_005156 | Implement the Python class `Poetry` described below.
Class description:
Poetry dependency manager.
Method signatures and docstrings:
- def version(self) -> Version: poetry version.
- def dir_is_project(cls, directory: StrPath, **__kwargs: Any) -> bool: Determine if the directory contains a project for this dependency... | Implement the Python class `Poetry` described below.
Class description:
Poetry dependency manager.
Method signatures and docstrings:
- def version(self) -> Version: poetry version.
- def dir_is_project(cls, directory: StrPath, **__kwargs: Any) -> bool: Determine if the directory contains a project for this dependency... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class Poetry:
"""Poetry dependency manager."""
def version(self) -> Version:
"""poetry version."""
<|body_0|>
def dir_is_project(cls, directory: StrPath, **__kwargs: Any) -> bool:
"""Determine if the directory contains a project for this dependency manager. Args: direc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poetry:
"""Poetry dependency manager."""
def version(self) -> Version:
"""poetry version."""
cmd_output = self._run_command([self.EXECUTABLE, '--version'])
match = re.search('^Poetry version (?P<version>\\S*)', cmd_output)
if not match:
LOGGER.warning('unable t... | the_stack_v2_python_sparse | runway/dependency_managers/_poetry.py | onicagroup/runway | train | 156 |
4a7cc0b71fc71fb38ca3b43b7a9f8bd8fb6c26d4 | [
"ids = cls.extract(request)\nproduct_dict = Product.objects.browsable().in_bulk(ids)\nids.reverse()\nreturn [product_dict[product_id] for product_id in ids if product_id in product_dict]",
"ids = []\nif cls.cookie_name in request.COOKIES:\n try:\n ids = json.loads(request.COOKIES[cls.cookie_name])\n ... | <|body_start_0|>
ids = cls.extract(request)
product_dict = Product.objects.browsable().in_bulk(ids)
ids.reverse()
return [product_dict[product_id] for product_id in ids if product_id in product_dict]
<|end_body_0|>
<|body_start_1|>
ids = []
if cls.cookie_name in request.... | CustomerHistoryManager | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerHistoryManager:
def get(cls, request):
"""Return a list of recently viewed products"""
<|body_0|>
def extract(cls, request, response=None):
"""Extract the IDs of products in the history cookie"""
<|body_1|>
def add(cls, ids, new_id):
"""A... | stack_v2_sparse_classes_36k_train_015133 | 2,287 | permissive | [
{
"docstring": "Return a list of recently viewed products",
"name": "get",
"signature": "def get(cls, request)"
},
{
"docstring": "Extract the IDs of products in the history cookie",
"name": "extract",
"signature": "def extract(cls, request, response=None)"
},
{
"docstring": "Add... | 4 | null | Implement the Python class `CustomerHistoryManager` described below.
Class description:
Implement the CustomerHistoryManager class.
Method signatures and docstrings:
- def get(cls, request): Return a list of recently viewed products
- def extract(cls, request, response=None): Extract the IDs of products in the histor... | Implement the Python class `CustomerHistoryManager` described below.
Class description:
Implement the CustomerHistoryManager class.
Method signatures and docstrings:
- def get(cls, request): Return a list of recently viewed products
- def extract(cls, request, response=None): Extract the IDs of products in the histor... | 5edac196f41f8cc97f8a07f7579f1041db2a02af | <|skeleton|>
class CustomerHistoryManager:
def get(cls, request):
"""Return a list of recently viewed products"""
<|body_0|>
def extract(cls, request, response=None):
"""Extract the IDs of products in the history cookie"""
<|body_1|>
def add(cls, ids, new_id):
"""A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerHistoryManager:
def get(cls, request):
"""Return a list of recently viewed products"""
ids = cls.extract(request)
product_dict = Product.objects.browsable().in_bulk(ids)
ids.reverse()
return [product_dict[product_id] for product_id in ids if product_id in produc... | the_stack_v2_python_sparse | src/oscar/apps/customer/history.py | django-oscar/django-oscar | train | 5,320 | |
2ea8de6d36b7a5294e4d963e41bb3f4aa64cab8d | [
"self.fobj = None\nself.keywords = []\nself.values = []\nself.formats = {}\nself.header = {}\nself.cdata = {}",
"parts = urlparse.urlparse(filename)\nif parts.scheme == VOS_SCHEME:\n self.fobj = vos.Client().open(filename)\nelif parts.scheme == FILE_SCHEME or parts.scheme == '':\n self.fobj = open(filename)... | <|body_start_0|>
self.fobj = None
self.keywords = []
self.values = []
self.formats = {}
self.header = {}
self.cdata = {}
<|end_body_0|>
<|body_start_1|>
parts = urlparse.urlparse(filename)
if parts.scheme == VOS_SCHEME:
self.fobj = vos.Client(... | Read in a MOP formated file | Parser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Read in a MOP formated file"""
def __init__(self):
"""does nothing"""
<|body_0|>
def open(self, filename):
"""Open the file for reading"""
<|body_1|>
def parse(self, filename):
"""read in a file and return a MOPFile object."""
... | stack_v2_sparse_classes_36k_train_015134 | 3,407 | no_license | [
{
"docstring": "does nothing",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Open the file for reading",
"name": "open",
"signature": "def open(self, filename)"
},
{
"docstring": "read in a file and return a MOPFile object.",
"name": "parse",
"s... | 3 | null | Implement the Python class `Parser` described below.
Class description:
Read in a MOP formated file
Method signatures and docstrings:
- def __init__(self): does nothing
- def open(self, filename): Open the file for reading
- def parse(self, filename): read in a file and return a MOPFile object. | Implement the Python class `Parser` described below.
Class description:
Read in a MOP formated file
Method signatures and docstrings:
- def __init__(self): does nothing
- def open(self, filename): Open the file for reading
- def parse(self, filename): read in a file and return a MOPFile object.
<|skeleton|>
class Pa... | 754931a4a6c500acad91b7ab2c4d7c86d1e82e08 | <|skeleton|>
class Parser:
"""Read in a MOP formated file"""
def __init__(self):
"""does nothing"""
<|body_0|>
def open(self, filename):
"""Open the file for reading"""
<|body_1|>
def parse(self, filename):
"""read in a file and return a MOPFile object."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parser:
"""Read in a MOP formated file"""
def __init__(self):
"""does nothing"""
self.fobj = None
self.keywords = []
self.values = []
self.formats = {}
self.header = {}
self.cdata = {}
def open(self, filename):
"""Open the file for read... | the_stack_v2_python_sparse | src/ossos-pipeline/ossos/mop_file.py | sevenlin123/MOP | train | 0 |
de4ed25e0e555321242cbce6ad4daf234edc3f4d | [
"existing_entities = existing_entities or {}\nnew_entities: EntityMapping = {}\nself._merge(session, entities, new_entities=new_entities, existing_entities=existing_entities)\nreturn list({**existing_entities, **new_entities}.values())",
"processed_entities = []\nfor entity in entities:\n key = entity.entity_k... | <|body_start_0|>
existing_entities = existing_entities or {}
new_entities: EntityMapping = {}
self._merge(session, entities, new_entities=new_entities, existing_entities=existing_entities)
return list({**existing_entities, **new_entities}.values())
<|end_body_0|>
<|body_start_1|>
... | A stateless functor in charge of detecting and merging entities that already exist on the database before flushing the session. | EntitiesMerger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntitiesMerger:
"""A stateless functor in charge of detecting and merging entities that already exist on the database before flushing the session."""
def __call__(self, session: Session, entities: Iterable[Entity], existing_entities: Optional[EntityMapping]=None) -> List[Entity]:
"""... | stack_v2_sparse_classes_36k_train_015135 | 7,489 | permissive | [
{
"docstring": "Merge a set of entities with their existing representations and update the parent/child relationships and return a list containing ``[*updated_entities, *new_entities]``.",
"name": "__call__",
"signature": "def __call__(self, session: Session, entities: Iterable[Entity], existing_entitie... | 5 | null | Implement the Python class `EntitiesMerger` described below.
Class description:
A stateless functor in charge of detecting and merging entities that already exist on the database before flushing the session.
Method signatures and docstrings:
- def __call__(self, session: Session, entities: Iterable[Entity], existing_... | Implement the Python class `EntitiesMerger` described below.
Class description:
A stateless functor in charge of detecting and merging entities that already exist on the database before flushing the session.
Method signatures and docstrings:
- def __call__(self, session: Session, entities: Iterable[Entity], existing_... | 446bc2f67493d3554c5422242ff91d5b5c76d78a | <|skeleton|>
class EntitiesMerger:
"""A stateless functor in charge of detecting and merging entities that already exist on the database before flushing the session."""
def __call__(self, session: Session, entities: Iterable[Entity], existing_entities: Optional[EntityMapping]=None) -> List[Entity]:
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntitiesMerger:
"""A stateless functor in charge of detecting and merging entities that already exist on the database before flushing the session."""
def __call__(self, session: Session, entities: Iterable[Entity], existing_entities: Optional[EntityMapping]=None) -> List[Entity]:
"""Merge a set o... | the_stack_v2_python_sparse | platypush/entities/_engine/repo/merger.py | BlackLight/platypush | train | 265 |
ef67cb7ddd6a739eaf553b30cf2bfe82fc573c92 | [
"total_n = factorial(len(nums))\nresult = []\nfor i in range(total_n):\n result.append(nums[:])\n nums = self.next_permute(nums)\nreturn result",
"first_idx = len(nums) - 2\nsecond_idx = len(nums) - 1\nwhile first_idx >= 0 and nums[first_idx] >= nums[first_idx + 1]:\n first_idx -= 1\nif first_idx == -1:\... | <|body_start_0|>
total_n = factorial(len(nums))
result = []
for i in range(total_n):
result.append(nums[:])
nums = self.next_permute(nums)
return result
<|end_body_0|>
<|body_start_1|>
first_idx = len(nums) - 2
second_idx = len(nums) - 1
w... | Solution_B2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B2:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers"""
<|body_0|>
def next_permute(self, nums: List[int]) -> List... | stack_v2_sparse_classes_36k_train_015136 | 5,911 | permissive | [
{
"docstring": "Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers",
"name": "permute",
"signature": "def permute(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Herlper for B1, B2 From Leet... | 2 | stack_v2_sparse_classes_30k_train_000235 | Implement the Python class `Solution_B2` described below.
Class description:
Implement the Solution_B2 class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a colle... | Implement the Python class `Solution_B2` described below.
Class description:
Implement the Solution_B2 class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a colle... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B2:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers"""
<|body_0|>
def next_permute(self, nums: List[int]) -> List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_B2:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers"""
total_n = factorial(len(nums))
result = []
for i in range(tot... | the_stack_v2_python_sparse | LeetCode/LC046_permutations.py | jxie0755/Learning_Python | train | 0 | |
bdc4abc0d790ecb0f535d92deb1f8eb639f644d9 | [
"d = {}\nfor propname, _ in self.PROPERTIES:\n if propname in props:\n d[propname] = props[propname]\nself.properties = d",
"try:\n return self.properties == other.properties\nexcept AttributeError:\n return NotImplemented",
"if name == '__setstate__':\n raise AttributeError('__setstate__')\n... | <|body_start_0|>
d = {}
for propname, _ in self.PROPERTIES:
if propname in props:
d[propname] = props[propname]
self.properties = d
<|end_body_0|>
<|body_start_1|>
try:
return self.properties == other.properties
except AttributeError:
... | Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute. | GenericContent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericContent:
"""Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute."""
def __init__(self, **props):
"""Save the properties appropriate to this AMQP content type in a 'properties' dictionary."""
<|body_0|>
def __eq__(self, other):... | stack_v2_sparse_classes_36k_train_015137 | 16,315 | permissive | [
{
"docstring": "Save the properties appropriate to this AMQP content type in a 'properties' dictionary.",
"name": "__init__",
"signature": "def __init__(self, **props)"
},
{
"docstring": "Check if this object has the same properties as another content object.",
"name": "__eq__",
"signatu... | 5 | stack_v2_sparse_classes_30k_train_002651 | Implement the Python class `GenericContent` described below.
Class description:
Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute.
Method signatures and docstrings:
- def __init__(self, **props): Save the properties appropriate to this AMQP content type in a 'properties' dictio... | Implement the Python class `GenericContent` described below.
Class description:
Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute.
Method signatures and docstrings:
- def __init__(self, **props): Save the properties appropriate to this AMQP content type in a 'properties' dictio... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class GenericContent:
"""Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute."""
def __init__(self, **props):
"""Save the properties appropriate to this AMQP content type in a 'properties' dictionary."""
<|body_0|>
def __eq__(self, other):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericContent:
"""Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute."""
def __init__(self, **props):
"""Save the properties appropriate to this AMQP content type in a 'properties' dictionary."""
d = {}
for propname, _ in self.PROPERTIES:
... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/amqp/serialization.py | Raniac/NEURO-LEARN | train | 9 |
bf01ff913c02d62e8acf3f671618ce173072780c | [
"self.html = html\nself.start = start\nself.xLimits = xLimits\nif not font:\n font = piddle.Font()\nself.font = font\nself.color = color",
"writer = _HtmlPiddleWriter(self, aPiddleCanvas)\nfmt = formatter.AbstractFormatter(writer)\nparser = _HtmlParser(fmt)\nparser.feed(self.html)\nparser.close()"
] | <|body_start_0|>
self.html = html
self.start = start
self.xLimits = xLimits
if not font:
font = piddle.Font()
self.font = font
self.color = color
<|end_body_0|>
<|body_start_1|>
writer = _HtmlPiddleWriter(self, aPiddleCanvas)
fmt = formatter.A... | jjk 02/01/00 | HTMLPiddler | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTMLPiddler:
"""jjk 02/01/00"""
def __init__(self, html='', start=(0, 0), xLimits=(0, 800), font=None, color=None):
"""instance initializer jjk 02/01/00"""
<|body_0|>
def renderOn(self, aPiddleCanvas):
"""draw the text with aPiddleCanvas jjk 02/01/00"""
<... | stack_v2_sparse_classes_36k_train_015138 | 13,640 | permissive | [
{
"docstring": "instance initializer jjk 02/01/00",
"name": "__init__",
"signature": "def __init__(self, html='', start=(0, 0), xLimits=(0, 800), font=None, color=None)"
},
{
"docstring": "draw the text with aPiddleCanvas jjk 02/01/00",
"name": "renderOn",
"signature": "def renderOn(self... | 2 | null | Implement the Python class `HTMLPiddler` described below.
Class description:
jjk 02/01/00
Method signatures and docstrings:
- def __init__(self, html='', start=(0, 0), xLimits=(0, 800), font=None, color=None): instance initializer jjk 02/01/00
- def renderOn(self, aPiddleCanvas): draw the text with aPiddleCanvas jjk ... | Implement the Python class `HTMLPiddler` described below.
Class description:
jjk 02/01/00
Method signatures and docstrings:
- def __init__(self, html='', start=(0, 0), xLimits=(0, 800), font=None, color=None): instance initializer jjk 02/01/00
- def renderOn(self, aPiddleCanvas): draw the text with aPiddleCanvas jjk ... | 650141ece7b68f054ed14813e1585436ad57d3df | <|skeleton|>
class HTMLPiddler:
"""jjk 02/01/00"""
def __init__(self, html='', start=(0, 0), xLimits=(0, 800), font=None, color=None):
"""instance initializer jjk 02/01/00"""
<|body_0|>
def renderOn(self, aPiddleCanvas):
"""draw the text with aPiddleCanvas jjk 02/01/00"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTMLPiddler:
"""jjk 02/01/00"""
def __init__(self, html='', start=(0, 0), xLimits=(0, 800), font=None, color=None):
"""instance initializer jjk 02/01/00"""
self.html = html
self.start = start
self.xLimits = xLimits
if not font:
font = piddle.Font()
... | the_stack_v2_python_sparse | rdkit/sping/util/HTMLPiddler.py | biolearning-stadius/rdkit | train | 6 |
27c7f10b4dbb90b01c2ef7c4b0df2f0ff87f5851 | [
"self._send_data = send_data\nself._recv_data = recv_data\nself._timer: Timer = timer if timer is not None else NullTimer()",
"for request, transfer_buffer in self._send_data:\n with self._timer.clock('wait'):\n request.wait()\n with self._timer.clock('unpack'):\n Buffer.push_to_cache(transfer... | <|body_start_0|>
self._send_data = send_data
self._recv_data = recv_data
self._timer: Timer = timer if timer is not None else NullTimer()
<|end_body_0|>
<|body_start_1|>
for request, transfer_buffer in self._send_data:
with self._timer.clock('wait'):
request.... | Asynchronous request object for halo updates. | HaloUpdateRequest | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HaloUpdateRequest:
"""Asynchronous request object for halo updates."""
def __init__(self, send_data: _HaloRequestSendList, recv_data: _HaloRequestRecvList, timer: Optional[Timer]=None):
"""Build a halo request. Args: send_data: a tuple of the MPI request and the buffer sent recv_data... | stack_v2_sparse_classes_36k_train_015139 | 19,384 | permissive | [
{
"docstring": "Build a halo request. Args: send_data: a tuple of the MPI request and the buffer sent recv_data: a tuple of the MPI request, the temporary buffer and the destination buffer timer: optional, time the wait & unpack of a halo exchange",
"name": "__init__",
"signature": "def __init__(self, s... | 2 | stack_v2_sparse_classes_30k_train_007140 | Implement the Python class `HaloUpdateRequest` described below.
Class description:
Asynchronous request object for halo updates.
Method signatures and docstrings:
- def __init__(self, send_data: _HaloRequestSendList, recv_data: _HaloRequestRecvList, timer: Optional[Timer]=None): Build a halo request. Args: send_data:... | Implement the Python class `HaloUpdateRequest` described below.
Class description:
Asynchronous request object for halo updates.
Method signatures and docstrings:
- def __init__(self, send_data: _HaloRequestSendList, recv_data: _HaloRequestRecvList, timer: Optional[Timer]=None): Build a halo request. Args: send_data:... | c543e8ec478d46d88b48cdd3beaaa1717a95b935 | <|skeleton|>
class HaloUpdateRequest:
"""Asynchronous request object for halo updates."""
def __init__(self, send_data: _HaloRequestSendList, recv_data: _HaloRequestRecvList, timer: Optional[Timer]=None):
"""Build a halo request. Args: send_data: a tuple of the MPI request and the buffer sent recv_data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HaloUpdateRequest:
"""Asynchronous request object for halo updates."""
def __init__(self, send_data: _HaloRequestSendList, recv_data: _HaloRequestRecvList, timer: Optional[Timer]=None):
"""Build a halo request. Args: send_data: a tuple of the MPI request and the buffer sent recv_data: a tuple of ... | the_stack_v2_python_sparse | util/pace/util/halo_updater.py | ai2cm/pace | train | 27 |
27a65d72eb227977ba2fc0414ff3462275cdb4b8 | [
"self.estrutura = frame(frame=fram)\nself.e = self.estrutura\nself.size = size\nself.cor_dos_detalhes = c\nself.desenha_as_partes_do_bloco()",
"s = self.size / 2\nfr, ns = (self.estrutura, (-s, s))\nconvex(pos=[(x, ht * z / self.size, y) for x in ns for y in ns for z in ns if x - y or x - s], color=self.cor_dos_d... | <|body_start_0|>
self.estrutura = frame(frame=fram)
self.e = self.estrutura
self.size = size
self.cor_dos_detalhes = c
self.desenha_as_partes_do_bloco()
<|end_body_0|>
<|body_start_1|>
s = self.size / 2
fr, ns = (self.estrutura, (-s, s))
convex(pos=[(x, h... | Esse eu fiz para vocês: um prisma triangular que representa um telhado | prism | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class prism:
"""Esse eu fiz para vocês: um prisma triangular que representa um telhado"""
def __init__(self, fram=frame(), size=10.0, c=color.white):
"""ontogênese: assim que é criado, o bloco se desenha"""
<|body_0|>
def desenha_as_partes_do_bloco(self):
"""cria um ob... | stack_v2_sparse_classes_36k_train_015140 | 5,267 | no_license | [
{
"docstring": "ontogênese: assim que é criado, o bloco se desenha",
"name": "__init__",
"signature": "def __init__(self, fram=frame(), size=10.0, c=color.white)"
},
{
"docstring": "cria um objeto convexo que passa por seis pontos no espaço",
"name": "desenha_as_partes_do_bloco",
"signat... | 2 | stack_v2_sparse_classes_30k_train_012929 | Implement the Python class `prism` described below.
Class description:
Esse eu fiz para vocês: um prisma triangular que representa um telhado
Method signatures and docstrings:
- def __init__(self, fram=frame(), size=10.0, c=color.white): ontogênese: assim que é criado, o bloco se desenha
- def desenha_as_partes_do_bl... | Implement the Python class `prism` described below.
Class description:
Esse eu fiz para vocês: um prisma triangular que representa um telhado
Method signatures and docstrings:
- def __init__(self, fram=frame(), size=10.0, c=color.white): ontogênese: assim que é criado, o bloco se desenha
- def desenha_as_partes_do_bl... | 91a88b5a9b15f324a64afc18607a5d1d0a25c4d0 | <|skeleton|>
class prism:
"""Esse eu fiz para vocês: um prisma triangular que representa um telhado"""
def __init__(self, fram=frame(), size=10.0, c=color.white):
"""ontogênese: assim que é criado, o bloco se desenha"""
<|body_0|>
def desenha_as_partes_do_bloco(self):
"""cria um ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class prism:
"""Esse eu fiz para vocês: um prisma triangular que representa um telhado"""
def __init__(self, fram=frame(), size=10.0, c=color.white):
"""ontogênese: assim que é criado, o bloco se desenha"""
self.estrutura = frame(frame=fram)
self.e = self.estrutura
self.size = s... | the_stack_v2_python_sparse | artwork/abrapa/abrapa.py | cetoli/labase-draft | train | 0 |
072a847da49d695bdcca34f88304b3ca0053f10b | [
"self.n_samples = n_samples\nif test_size < 0.0:\n raise ValueError('the parameter test_size(%.5f) must be int or float which is greater than 0' % test_size)\nif test_size < 1.0:\n self.test_size = self.n_samples * test_size\nelse:\n self.test_size = test_size\nself.test_size = int(np.floor(self.test_size)... | <|body_start_0|>
self.n_samples = n_samples
if test_size < 0.0:
raise ValueError('the parameter test_size(%.5f) must be int or float which is greater than 0' % test_size)
if test_size < 1.0:
self.test_size = self.n_samples * test_size
else:
self.test_s... | ShuffleSpliter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShuffleSpliter:
def __init__(self, n_samples, test_size=0.2):
""":param n_samples: int, the number of samples :param test_size: int or float, if float it's the ratio of test samples."""
<|body_0|>
def shuffle(self):
""":return: train indexes and test indexes"""
... | stack_v2_sparse_classes_36k_train_015141 | 926 | no_license | [
{
"docstring": ":param n_samples: int, the number of samples :param test_size: int or float, if float it's the ratio of test samples.",
"name": "__init__",
"signature": "def __init__(self, n_samples, test_size=0.2)"
},
{
"docstring": ":return: train indexes and test indexes",
"name": "shuffl... | 2 | stack_v2_sparse_classes_30k_train_005355 | Implement the Python class `ShuffleSpliter` described below.
Class description:
Implement the ShuffleSpliter class.
Method signatures and docstrings:
- def __init__(self, n_samples, test_size=0.2): :param n_samples: int, the number of samples :param test_size: int or float, if float it's the ratio of test samples.
- ... | Implement the Python class `ShuffleSpliter` described below.
Class description:
Implement the ShuffleSpliter class.
Method signatures and docstrings:
- def __init__(self, n_samples, test_size=0.2): :param n_samples: int, the number of samples :param test_size: int or float, if float it's the ratio of test samples.
- ... | 3fd81b17411f01622adf48e0bb4187ffb2c11c68 | <|skeleton|>
class ShuffleSpliter:
def __init__(self, n_samples, test_size=0.2):
""":param n_samples: int, the number of samples :param test_size: int or float, if float it's the ratio of test samples."""
<|body_0|>
def shuffle(self):
""":return: train indexes and test indexes"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShuffleSpliter:
def __init__(self, n_samples, test_size=0.2):
""":param n_samples: int, the number of samples :param test_size: int or float, if float it's the ratio of test samples."""
self.n_samples = n_samples
if test_size < 0.0:
raise ValueError('the parameter test_size... | the_stack_v2_python_sparse | utils/shuffle.py | Lehyu/pyml | train | 4 | |
f566e586deb45031b1ca6f316e5f706fa765db5c | [
"self = object.__new__(cls)\nself.name = value\nself.value = value\nself.metadata_type = RoleManagerMetadataBase\nreturn self",
"self.name = name\nself.value = value\nself.metadata_type = metadata_type\nself.INSTANCES[value] = self",
"if self.value:\n boolean = True\nelse:\n boolean = False\nreturn boolea... | <|body_start_0|>
self = object.__new__(cls)
self.name = value
self.value = value
self.metadata_type = RoleManagerMetadataBase
return self
<|end_body_0|>
<|body_start_1|>
self.name = name
self.value = value
self.metadata_type = metadata_type
self.I... | Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the predefined ``RoleManagerType``-s. These can be a... | RoleManagerType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleManagerType:
"""Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the prede... | stack_v2_sparse_classes_36k_train_015142 | 5,532 | permissive | [
{
"docstring": "Creates a new role manager type with the given value. Parameters ---------- value : `int` Value representing the role manager. Returns ------- self : `instance<cls>`",
"name": "_from_value",
"signature": "def _from_value(cls, value)"
},
{
"docstring": "Creates a new scheduled eve... | 3 | stack_v2_sparse_classes_30k_test_000791 | Implement the Python class `RoleManagerType` described below.
Class description:
Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``Ro... | Implement the Python class `RoleManagerType` described below.
Class description:
Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``Ro... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class RoleManagerType:
"""Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the prede... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleManagerType:
"""Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the predefined ``RoleM... | the_stack_v2_python_sparse | hata/discord/role/role/preinstanced.py | HuyaneMatsu/hata | train | 3 |
98a0e702cc5df157fd32d387767acc8b2f588187 | [
"super(RNNDEC, self).__init__()\nself.msgs = nn.CellList([nn.SequentialCell([nn.Dense(2 * n_in_node, msg_hid), nn.ReLU(), nn.Dropout(p=do_prob), nn.Dense(msg_hid, msg_out), nn.ReLU()]) for _ in range(edge_types)])\nself.out = nn.SequentialCell([nn.Dense(n_in_node + msg_out, n_hid), nn.ReLU(), nn.Dropout(p=do_prob),... | <|body_start_0|>
super(RNNDEC, self).__init__()
self.msgs = nn.CellList([nn.SequentialCell([nn.Dense(2 * n_in_node, msg_hid), nn.ReLU(), nn.Dropout(p=do_prob), nn.Dense(msg_hid, msg_out), nn.ReLU()]) for _ in range(edge_types)])
self.out = nn.SequentialCell([nn.Dense(n_in_node + msg_out, n_hid),... | RNN decoder with spatio-temporal message passing mechanisms. | RNNDEC | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDEC:
"""RNN decoder with spatio-temporal message passing mechanisms."""
def __init__(self, n_in_node: int, edge_types: int, msg_hid: int, msg_out: int, n_hid: int, do_prob: float=0.0, skip_first: bool=False):
"""Parameters ---------- n_in_node : int input dimension. edge_types : i... | stack_v2_sparse_classes_36k_train_015143 | 12,491 | permissive | [
{
"docstring": "Parameters ---------- n_in_node : int input dimension. edge_types : int number of edge types. msg_hid, msg_out, n_hid: int dimension of different hidden layers. do_prob : float, optional rate of dropout. The default is 0.. skip_first : bool, optional setting the first type of edge as non-edge or... | 3 | stack_v2_sparse_classes_30k_train_006724 | Implement the Python class `RNNDEC` described below.
Class description:
RNN decoder with spatio-temporal message passing mechanisms.
Method signatures and docstrings:
- def __init__(self, n_in_node: int, edge_types: int, msg_hid: int, msg_out: int, n_hid: int, do_prob: float=0.0, skip_first: bool=False): Parameters -... | Implement the Python class `RNNDEC` described below.
Class description:
RNN decoder with spatio-temporal message passing mechanisms.
Method signatures and docstrings:
- def __init__(self, n_in_node: int, edge_types: int, msg_hid: int, msg_out: int, n_hid: int, do_prob: float=0.0, skip_first: bool=False): Parameters -... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class RNNDEC:
"""RNN decoder with spatio-temporal message passing mechanisms."""
def __init__(self, n_in_node: int, edge_types: int, msg_hid: int, msg_out: int, n_hid: int, do_prob: float=0.0, skip_first: bool=False):
"""Parameters ---------- n_in_node : int input dimension. edge_types : i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDEC:
"""RNN decoder with spatio-temporal message passing mechanisms."""
def __init__(self, n_in_node: int, edge_types: int, msg_hid: int, msg_out: int, n_hid: int, do_prob: float=0.0, skip_first: bool=False):
"""Parameters ---------- n_in_node : int input dimension. edge_types : int number of ... | the_stack_v2_python_sparse | research/gnn/nri-mpm/models/nri.py | mindspore-ai/models | train | 301 |
b8abc7779291e8c25aa1c755ed638b84af17ce0d | [
"super(FunctionComponent, self).__init__(opts)\nself.options = opts.get('fn_hibp', {})\nself.hibp = Hibp(self.options)",
"try:\n yield StatusMessage('starting...')\n result_payload = ResultPayload('hibp', **kwargs)\n log = logging.getLogger(__name__)\n email_address = kwargs.get('email_address')\n ... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.options = opts.get('fn_hibp', {})
self.hibp = Hibp(self.options)
<|end_body_0|>
<|body_start_1|>
try:
yield StatusMessage('starting...')
result_payload = ResultPayload('hibp', **kwargs)
... | Component that implements Resilient function 'have_i_been_pwned_get_breaches | FunctionComponent | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'have_i_been_pwned_get_breaches"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _have_i_been_pwned_get_breaches_function(self, event, *args, **kw... | stack_v2_sparse_classes_36k_train_015144 | 2,140 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Function: Get all breaches of an email address from Have I Been Pwned.",
"name": "_have_i_been_pwned_get_breaches_function",
"signatur... | 2 | null | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'have_i_been_pwned_get_breaches
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _have_i_been_pwned_get_breaches_f... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'have_i_been_pwned_get_breaches
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _have_i_been_pwned_get_breaches_f... | 6878c78b94eeca407998a41ce8db2cc00f2b6758 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'have_i_been_pwned_get_breaches"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _have_i_been_pwned_get_breaches_function(self, event, *args, **kw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionComponent:
"""Component that implements Resilient function 'have_i_been_pwned_get_breaches"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.options = opts.get('fn_hibp', {})
... | the_stack_v2_python_sparse | fn_hibp/fn_hibp/components/have_i_been_pwned_get_breaches.py | ibmresilient/resilient-community-apps | train | 81 |
3105e2514fdba6f0a9bfa72c2503e2f9be4b79b7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Segment()",
"from ..entity import Entity\nfrom .endpoint import Endpoint\nfrom .failure_info import FailureInfo\nfrom .media import Media\nfrom ..entity import Entity\nfrom .endpoint import Endpoint\nfrom .failure_info import FailureIn... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Segment()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .endpoint import Endpoint
from .failure_info import FailureInfo
from .media import Media
... | Segment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Segment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Segment:
"""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: Segment"""... | stack_v2_sparse_classes_36k_train_015145 | 3,941 | 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: Segment",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse... | 3 | null | Implement the Python class `Segment` described below.
Class description:
Implement the Segment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Segment: Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | Implement the Python class `Segment` described below.
Class description:
Implement the Segment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Segment: Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Segment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Segment:
"""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: Segment"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Segment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Segment:
"""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: Segment"""
if no... | the_stack_v2_python_sparse | msgraph/generated/models/call_records/segment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fbf9c8c9a7b9afcb48c765b2de0e8d03698f2ac2 | [
"self.context = context\nself.builder = builder\nself.struct_type = struct_type",
"context = self.context\nbuilder = self.builder\nstruct_type = self.struct_type\nst = cgutils.create_struct_proxy(struct_type)(context, builder)\nst.meminfo = mi\nreturn st",
"context = self.context\nbuilder = self.builder\nstruct... | <|body_start_0|>
self.context = context
self.builder = builder
self.struct_type = struct_type
<|end_body_0|>
<|body_start_1|>
context = self.context
builder = self.builder
struct_type = self.struct_type
st = cgutils.create_struct_proxy(struct_type)(context, build... | Internal builder-code utils for structref definitions. | _Utils | [
"LicenseRef-scancode-secret-labs-2011",
"BSD-3-Clause",
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Python-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Utils:
"""Internal builder-code utils for structref definitions."""
def __init__(self, context, builder, struct_type):
"""Parameters ---------- context : a numba target context builder : a llvmlite IRBuilder struct_type : numba.core.types.StructRef"""
<|body_0|>
def new... | stack_v2_sparse_classes_36k_train_015146 | 11,491 | permissive | [
{
"docstring": "Parameters ---------- context : a numba target context builder : a llvmlite IRBuilder struct_type : numba.core.types.StructRef",
"name": "__init__",
"signature": "def __init__(self, context, builder, struct_type)"
},
{
"docstring": "Encapsulate the MemInfo from a `StructRefPayloa... | 5 | stack_v2_sparse_classes_30k_test_001102 | Implement the Python class `_Utils` described below.
Class description:
Internal builder-code utils for structref definitions.
Method signatures and docstrings:
- def __init__(self, context, builder, struct_type): Parameters ---------- context : a numba target context builder : a llvmlite IRBuilder struct_type : numb... | Implement the Python class `_Utils` described below.
Class description:
Internal builder-code utils for structref definitions.
Method signatures and docstrings:
- def __init__(self, context, builder, struct_type): Parameters ---------- context : a numba target context builder : a llvmlite IRBuilder struct_type : numb... | 46059957ad416e68476d1e5f32ccd59f7d5df2bb | <|skeleton|>
class _Utils:
"""Internal builder-code utils for structref definitions."""
def __init__(self, context, builder, struct_type):
"""Parameters ---------- context : a numba target context builder : a llvmlite IRBuilder struct_type : numba.core.types.StructRef"""
<|body_0|>
def new... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Utils:
"""Internal builder-code utils for structref definitions."""
def __init__(self, context, builder, struct_type):
"""Parameters ---------- context : a numba target context builder : a llvmlite IRBuilder struct_type : numba.core.types.StructRef"""
self.context = context
self.... | the_stack_v2_python_sparse | numba/experimental/structref.py | numba/numba | train | 8,247 |
6a9a6ac588b3fbdf635e50e4e09503872308054c | [
"tokens = self.input.split(' ', 2)\nif not self.bot.callsign in tokens[0].lower():\n return False\ntry:\n command = tokens[1].lower()\nexcept IndexError:\n return False\nif not command:\n return False\ntry:\n argument = tokens[2]\nexcept IndexError:\n argument = ''\ntry:\n f = getattr(self, 'cm... | <|body_start_0|>
tokens = self.input.split(' ', 2)
if not self.bot.callsign in tokens[0].lower():
return False
try:
command = tokens[1].lower()
except IndexError:
return False
if not command:
return False
try:
ar... | Base class to process IRC events containing commands to the bot. Events that get handled is in the formats: `bot_name command [argument]` for channel messages, `command [argument]` for private ones. Read on BaseContext's .send() for how you should send back text. Usage: ------ You shouldn't need to override any of the ... | BaseCommandContext | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseCommandContext:
"""Base class to process IRC events containing commands to the bot. Events that get handled is in the formats: `bot_name command [argument]` for channel messages, `command [argument]` for private ones. Read on BaseContext's .send() for how you should send back text. Usage: ---... | stack_v2_sparse_classes_36k_train_015147 | 8,615 | permissive | [
{
"docstring": "Dispatch a public event to a cmd__public or cmd_ method",
"name": "do_public",
"signature": "def do_public(self)"
},
{
"docstring": "Dispatch a private event to a cmd__private or cmd_ method",
"name": "do_private",
"signature": "def do_private(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010049 | Implement the Python class `BaseCommandContext` described below.
Class description:
Base class to process IRC events containing commands to the bot. Events that get handled is in the formats: `bot_name command [argument]` for channel messages, `command [argument]` for private ones. Read on BaseContext's .send() for ho... | Implement the Python class `BaseCommandContext` described below.
Class description:
Base class to process IRC events containing commands to the bot. Events that get handled is in the formats: `bot_name command [argument]` for channel messages, `command [argument]` for private ones. Read on BaseContext's .send() for ho... | 61d97a7255300ddc0b3067cd2da43e059d48600e | <|skeleton|>
class BaseCommandContext:
"""Base class to process IRC events containing commands to the bot. Events that get handled is in the formats: `bot_name command [argument]` for channel messages, `command [argument]` for private ones. Read on BaseContext's .send() for how you should send back text. Usage: ---... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseCommandContext:
"""Base class to process IRC events containing commands to the bot. Events that get handled is in the formats: `bot_name command [argument]` for channel messages, `command [argument]` for private ones. Read on BaseContext's .send() for how you should send back text. Usage: ------ You shoul... | the_stack_v2_python_sparse | src/modules/basemodule.py | nickraptis/fidibot | train | 0 |
cae6234c1ec7b6077adee71649c4540e3e546011 | [
"cfrom = -1\ntry:\n if self.lnk.type == Lnk.CHARSPAN:\n cfrom = self.lnk.data[0]\nexcept AttributeError:\n pass\nreturn cfrom",
"cto = -1\ntry:\n if self.lnk.type == Lnk.CHARSPAN:\n cto = self.lnk.data[1]\nexcept AttributeError:\n pass\nreturn cto"
] | <|body_start_0|>
cfrom = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
cfrom = self.lnk.data[0]
except AttributeError:
pass
return cfrom
<|end_body_0|>
<|body_start_1|>
cto = -1
try:
if self.lnk.type == Lnk.CHARSPAN:
... | A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is not a Lnk.CHARSPAN type). | _LnkMixin | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LnkMixin:
"""A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is n... | stack_v2_sparse_classes_36k_train_015148 | 24,086 | permissive | [
{
"docstring": "The initial character position in the surface string. Defaults to -1 if there is no valid cfrom value.",
"name": "cfrom",
"signature": "def cfrom(self)"
},
{
"docstring": "The final character position in the surface string. Defaults to -1 if there is no valid cto value.",
"na... | 2 | null | Implement the Python class `_LnkMixin` described below.
Class description:
A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1... | Implement the Python class `_LnkMixin` described below.
Class description:
A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1... | de0a143e283a41e2ab15a7bb197bfdd0f7fb8655 | <|skeleton|>
class _LnkMixin:
"""A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _LnkMixin:
"""A mixin class for predications ([EPs] or [Nodes]) or full [Xmrs] objects, which are the types that can be linked to surface strings. This class provides the `cfrom` and `cto` properties so they are always available (defaulting to a value of `-1` if there is no lnk or if the lnk is not a Lnk.CHAR... | the_stack_v2_python_sparse | delphin/mrs/components.py | draplater/hrg-parser | train | 10 |
cfd404458c4ae82b964b91e6ca78123fba158d5b | [
"super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs)\nself.endpoint = 'reports'\nself.campaign_id = None\nself.report_id = None",
"self.campaign_id = campaign_id\nself.report_id = None\nreturn self._mc_client._get(url=self._build_path(campaign_id, 'abuse-reports'), **queryparams)",
"self.campaign_... | <|body_start_0|>
super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs)
self.endpoint = 'reports'
self.campaign_id = None
self.report_id = None
<|end_body_0|>
<|body_start_1|>
self.campaign_id = campaign_id
self.report_id = None
return self._mc_client.... | Get information about campaign abuse complaints. | ReportCampaignAbuseReports | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportCampaignAbuseReports:
"""Get information about campaign abuse complaints."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, campaign_id, **queryparams):
"""Get a list of abuse complaints for a specific campaign. ... | stack_v2_sparse_classes_36k_train_015149 | 1,850 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get a list of abuse complaints for a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: T... | 3 | stack_v2_sparse_classes_30k_train_014115 | Implement the Python class `ReportCampaignAbuseReports` described below.
Class description:
Get information about campaign abuse complaints.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, campaign_id, **queryparams): Get a list of abuse complaints for ... | Implement the Python class `ReportCampaignAbuseReports` described below.
Class description:
Get information about campaign abuse complaints.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, campaign_id, **queryparams): Get a list of abuse complaints for ... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class ReportCampaignAbuseReports:
"""Get information about campaign abuse complaints."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, campaign_id, **queryparams):
"""Get a list of abuse complaints for a specific campaign. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportCampaignAbuseReports:
"""Get information about campaign abuse complaints."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs)
self.endpoint = 'reports'
self.campaign_id = None
... | the_stack_v2_python_sparse | mailchimp3/entities/reportcampaignabusereports.py | VingtCinq/python-mailchimp | train | 190 |
e12924ef23ce25fe08c2089900e939be83f144ea | [
"ret = defaultdict(list)\nfor addresses in self._list_chunks(address_list, 199):\n path = 'addresses/' + ','.join(addresses) + '/transactions?limit={}'.format(limit)\n if min_block:\n path += '&min_block={}'.format(min_block)\n r = self._request('GET', path)\n txn_data = r.json()\n for data in... | <|body_start_0|>
ret = defaultdict(list)
for addresses in self._list_chunks(address_list, 199):
path = 'addresses/' + ','.join(addresses) + '/transactions?limit={}'.format(limit)
if min_block:
path += '&min_block={}'.format(min_block)
r = self._request... | TwentyOneProviderRehive | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwentyOneProviderRehive:
def get_transactions_json(self, address_list, limit=100, min_block=None):
"""Provides transactions associated with each address in address_list. Args: address_list (list): List of Base58Check encoded Bitcoin addresses. limit (int): Maximum number of transactions ... | stack_v2_sparse_classes_36k_train_015150 | 1,873 | permissive | [
{
"docstring": "Provides transactions associated with each address in address_list. Args: address_list (list): List of Base58Check encoded Bitcoin addresses. limit (int): Maximum number of transactions to return. min_block (int): Block height from which to start getting transactions. If None, will get transacti... | 2 | stack_v2_sparse_classes_30k_val_000025 | Implement the Python class `TwentyOneProviderRehive` described below.
Class description:
Implement the TwentyOneProviderRehive class.
Method signatures and docstrings:
- def get_transactions_json(self, address_list, limit=100, min_block=None): Provides transactions associated with each address in address_list. Args: ... | Implement the Python class `TwentyOneProviderRehive` described below.
Class description:
Implement the TwentyOneProviderRehive class.
Method signatures and docstrings:
- def get_transactions_json(self, address_list, limit=100, min_block=None): Provides transactions associated with each address in address_list. Args: ... | 658db548faa70fb06c9eb35239bb581d18ae4b56 | <|skeleton|>
class TwentyOneProviderRehive:
def get_transactions_json(self, address_list, limit=100, min_block=None):
"""Provides transactions associated with each address in address_list. Args: address_list (list): List of Base58Check encoded Bitcoin addresses. limit (int): Maximum number of transactions ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwentyOneProviderRehive:
def get_transactions_json(self, address_list, limit=100, min_block=None):
"""Provides transactions associated with each address in address_list. Args: address_list (list): List of Base58Check encoded Bitcoin addresses. limit (int): Maximum number of transactions to return. min... | the_stack_v2_python_sparse | src/bitcoin_monitoring/utils.py | getslideapp/django-starter | train | 0 | |
d9d441a089d8b563e8a752c66b6f3bbb2445bcde | [
"config = loadcookiecutterconfig(template.metadata.location, template.root)\nrenderer = createcookiecutterrenderer(template.root, config)\npaths = findcookiecutterpaths(template.root, config)\nhooks = findcookiecutterhooks(template.root)\nreturn cls(template.metadata, config, renderer, paths, hooks)",
"binder: Bi... | <|body_start_0|>
config = loadcookiecutterconfig(template.metadata.location, template.root)
renderer = createcookiecutterrenderer(template.root, config)
paths = findcookiecutterpaths(template.root, config)
hooks = findcookiecutterhooks(template.root)
return cls(template.metadata,... | A project generator. | ProjectGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectGenerator:
"""A project generator."""
def create(cls, template: Template) -> ProjectGenerator:
"""Create a project generator."""
<|body_0|>
def bind(self, *, interactive: bool=True, bindings: Sequence[Binding]=()) -> Sequence[Binding]:
"""Bind the variable... | stack_v2_sparse_classes_36k_train_015151 | 3,727 | permissive | [
{
"docstring": "Create a project generator.",
"name": "create",
"signature": "def create(cls, template: Template) -> ProjectGenerator"
},
{
"docstring": "Bind the variables.",
"name": "bind",
"signature": "def bind(self, *, interactive: bool=True, bindings: Sequence[Binding]=()) -> Seque... | 4 | null | Implement the Python class `ProjectGenerator` described below.
Class description:
A project generator.
Method signatures and docstrings:
- def create(cls, template: Template) -> ProjectGenerator: Create a project generator.
- def bind(self, *, interactive: bool=True, bindings: Sequence[Binding]=()) -> Sequence[Bindin... | Implement the Python class `ProjectGenerator` described below.
Class description:
A project generator.
Method signatures and docstrings:
- def create(cls, template: Template) -> ProjectGenerator: Create a project generator.
- def bind(self, *, interactive: bool=True, bindings: Sequence[Binding]=()) -> Sequence[Bindin... | c6b26377153d60d5da825002e03f9a28467378a9 | <|skeleton|>
class ProjectGenerator:
"""A project generator."""
def create(cls, template: Template) -> ProjectGenerator:
"""Create a project generator."""
<|body_0|>
def bind(self, *, interactive: bool=True, bindings: Sequence[Binding]=()) -> Sequence[Binding]:
"""Bind the variable... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectGenerator:
"""A project generator."""
def create(cls, template: Template) -> ProjectGenerator:
"""Create a project generator."""
config = loadcookiecutterconfig(template.metadata.location, template.root)
renderer = createcookiecutterrenderer(template.root, config)
p... | the_stack_v2_python_sparse | src/cutty/projects/generate.py | cjolowicz/cutty | train | 4 |
0412076db90ea11821a480fa6f180f97512f384a | [
"if isinstance(tagname, STRING_TYPES):\n tag = Tag.query.filter_by(tag=tagname).first()\nelse:\n tag = Tag.query.filter_by(id=tagname).first()\nif tag is None:\n return (jsonify(error='tag %s not found' % tagname), NOT_FOUND)\nif not isinstance(g.json, dict):\n return (jsonify(error='expected a json dic... | <|body_start_0|>
if isinstance(tagname, STRING_TYPES):
tag = Tag.query.filter_by(tag=tagname).first()
else:
tag = Tag.query.filter_by(id=tagname).first()
if tag is None:
return (jsonify(error='tag %s not found' % tagname), NOT_FOUND)
if not isinstance(... | AgentsInTagIndexAPI | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentsInTagIndexAPI:
def post(self, tagname=None):
"""A ``POST`` will add an agent to the list of agents tagged with this tag The tag can be given as a string or as an integer (its id). .. http:post:: /api/v1/tags/<str:tagname>/agents/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/... | stack_v2_sparse_classes_36k_train_015152 | 17,872 | permissive | [
{
"docstring": "A ``POST`` will add an agent to the list of agents tagged with this tag The tag can be given as a string or as an integer (its id). .. http:post:: /api/v1/tags/<str:tagname>/agents/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/tags/interesting/agents/ HTTP/1.1 Accept: application/json ... | 2 | stack_v2_sparse_classes_30k_train_012869 | Implement the Python class `AgentsInTagIndexAPI` described below.
Class description:
Implement the AgentsInTagIndexAPI class.
Method signatures and docstrings:
- def post(self, tagname=None): A ``POST`` will add an agent to the list of agents tagged with this tag The tag can be given as a string or as an integer (its... | Implement the Python class `AgentsInTagIndexAPI` described below.
Class description:
Implement the AgentsInTagIndexAPI class.
Method signatures and docstrings:
- def post(self, tagname=None): A ``POST`` will add an agent to the list of agents tagged with this tag The tag can be given as a string or as an integer (its... | ea04bbcb807eb669415c569417b4b1b68e75d29d | <|skeleton|>
class AgentsInTagIndexAPI:
def post(self, tagname=None):
"""A ``POST`` will add an agent to the list of agents tagged with this tag The tag can be given as a string or as an integer (its id). .. http:post:: /api/v1/tags/<str:tagname>/agents/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentsInTagIndexAPI:
def post(self, tagname=None):
"""A ``POST`` will add an agent to the list of agents tagged with this tag The tag can be given as a string or as an integer (its id). .. http:post:: /api/v1/tags/<str:tagname>/agents/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/tags/intere... | the_stack_v2_python_sparse | pyfarm/master/api/tags.py | pyfarm/pyfarm-master | train | 2 | |
76cab94880e642b3ad4a04f58dc67d98c5a8ec08 | [
"for field in self.fields:\n if not field in self.UPDATE_FIELDS:\n if isinstance(self.fields[field], forms.ChoiceField):\n self.fields[field] = forms.CharField()\n self.fields[field].widget.attrs['readonly'] = True\nreturn self",
"data = self.cleaned_data.copy()\nfor key in list(data.k... | <|body_start_0|>
for field in self.fields:
if not field in self.UPDATE_FIELDS:
if isinstance(self.fields[field], forms.ChoiceField):
self.fields[field] = forms.CharField()
self.fields[field].widget.attrs['readonly'] = True
return self
<|end... | Custom base class for forms that need to support updating a subset of the field used to create the object | UpdateForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateForm:
"""Custom base class for forms that need to support updating a subset of the field used to create the object"""
def is_update(self):
"""Mark all fields not listed in UPDATE_FIELDS as readonly"""
<|body_0|>
def cleaned_update_data(self):
"""Get cleaned... | stack_v2_sparse_classes_36k_train_015153 | 12,765 | permissive | [
{
"docstring": "Mark all fields not listed in UPDATE_FIELDS as readonly",
"name": "is_update",
"signature": "def is_update(self)"
},
{
"docstring": "Get cleaned_data with only the keys listed in UPDATE_FIELDS",
"name": "cleaned_update_data",
"signature": "def cleaned_update_data(self)"
... | 2 | stack_v2_sparse_classes_30k_val_000444 | Implement the Python class `UpdateForm` described below.
Class description:
Custom base class for forms that need to support updating a subset of the field used to create the object
Method signatures and docstrings:
- def is_update(self): Mark all fields not listed in UPDATE_FIELDS as readonly
- def cleaned_update_da... | Implement the Python class `UpdateForm` described below.
Class description:
Custom base class for forms that need to support updating a subset of the field used to create the object
Method signatures and docstrings:
- def is_update(self): Mark all fields not listed in UPDATE_FIELDS as readonly
- def cleaned_update_da... | c2e26d272bd7b8d54abdc2948193163537e31291 | <|skeleton|>
class UpdateForm:
"""Custom base class for forms that need to support updating a subset of the field used to create the object"""
def is_update(self):
"""Mark all fields not listed in UPDATE_FIELDS as readonly"""
<|body_0|>
def cleaned_update_data(self):
"""Get cleaned... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateForm:
"""Custom base class for forms that need to support updating a subset of the field used to create the object"""
def is_update(self):
"""Mark all fields not listed in UPDATE_FIELDS as readonly"""
for field in self.fields:
if not field in self.UPDATE_FIELDS:
... | the_stack_v2_python_sparse | django/mgmt/forms.py | jhuapl-boss/boss | train | 20 |
11e01b03017ca1c5a1301d1e6d90d325a58091ee | [
"self.tags = tags\nself.attachments = attachments\nself.required_signatures = required_signatures\nself.get_social_security_number = get_social_security_number\nself.time_to_live = time_to_live\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nattachments = dictionary... | <|body_start_0|>
self.tags = tags
self.attachments = attachments
self.required_signatures = required_signatures
self.get_social_security_number = get_social_security_number
self.time_to_live = time_to_live
self.additional_properties = additional_properties
<|end_body_0|>
... | Implementation of the 'Advanced' model. TODO: type model description here. Attributes: tags (list of string): TODO: type description here. attachments (int): TODO: type description here. required_signatures (int): TODO: type description here. get_social_security_number (bool): TODO: type description here. time_to_live ... | Advanced | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Advanced:
"""Implementation of the 'Advanced' model. TODO: type model description here. Attributes: tags (list of string): TODO: type description here. attachments (int): TODO: type description here. required_signatures (int): TODO: type description here. get_social_security_number (bool): TODO: ... | stack_v2_sparse_classes_36k_train_015154 | 3,008 | permissive | [
{
"docstring": "Constructor for the Advanced class",
"name": "__init__",
"signature": "def __init__(self, attachments=None, get_social_security_number=None, required_signatures=None, tags=None, time_to_live=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model fro... | 2 | stack_v2_sparse_classes_30k_train_014175 | Implement the Python class `Advanced` described below.
Class description:
Implementation of the 'Advanced' model. TODO: type model description here. Attributes: tags (list of string): TODO: type description here. attachments (int): TODO: type description here. required_signatures (int): TODO: type description here. ge... | Implement the Python class `Advanced` described below.
Class description:
Implementation of the 'Advanced' model. TODO: type model description here. Attributes: tags (list of string): TODO: type description here. attachments (int): TODO: type description here. required_signatures (int): TODO: type description here. ge... | 49acc3d416a1dde7ea43b178d070484baf1b7f2b | <|skeleton|>
class Advanced:
"""Implementation of the 'Advanced' model. TODO: type model description here. Attributes: tags (list of string): TODO: type description here. attachments (int): TODO: type description here. required_signatures (int): TODO: type description here. get_social_security_number (bool): TODO: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Advanced:
"""Implementation of the 'Advanced' model. TODO: type model description here. Attributes: tags (list of string): TODO: type description here. attachments (int): TODO: type description here. required_signatures (int): TODO: type description here. get_social_security_number (bool): TODO: type descript... | the_stack_v2_python_sparse | PYTHON_GENERIC_LIB/tester/models/advanced.py | MaryamAdnan3/Tester1 | train | 0 |
e8df151a2ee23dee3e567e2be58f85352d6ffcc7 | [
"if opt_options is None:\n opt_options = {'maxiter': 100, 'disp': True, 'iprint': 2, 'ftol': 1e-12, 'eps': 0.1}\nsuper().__init__(fi=fi, minimum_yaw_angle=minimum_yaw_angle, maximum_yaw_angle=maximum_yaw_angle, yaw_angles_baseline=yaw_angles_baseline, x0=x0, turbine_weights=turbine_weights, normalize_control_var... | <|body_start_0|>
if opt_options is None:
opt_options = {'maxiter': 100, 'disp': True, 'iprint': 2, 'ftol': 1e-12, 'eps': 0.1}
super().__init__(fi=fi, minimum_yaw_angle=minimum_yaw_angle, maximum_yaw_angle=maximum_yaw_angle, yaw_angles_baseline=yaw_angles_baseline, x0=x0, turbine_weights=turb... | YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package. | YawOptimizationScipy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YawOptimizationScipy:
"""YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package."""
def __init_... | stack_v2_sparse_classes_36k_train_015155 | 5,455 | permissive | [
{
"docstring": "Instantiate YawOptimizationScipy object with a FlorisInterface object and assign parameter values.",
"name": "__init__",
"signature": "def __init__(self, fi, minimum_yaw_angle=0.0, maximum_yaw_angle=25.0, yaw_angles_baseline=None, x0=None, opt_method='SLSQP', opt_options=None, turbine_we... | 2 | stack_v2_sparse_classes_30k_train_011180 | Implement the Python class `YawOptimizationScipy` described below.
Class description:
YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciP... | Implement the Python class `YawOptimizationScipy` described below.
Class description:
YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciP... | 59e53a66aef134a3c9e912f9468ca667b599d4e5 | <|skeleton|>
class YawOptimizationScipy:
"""YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package."""
def __init_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YawOptimizationScipy:
"""YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package."""
def __init__(self, fi, m... | the_stack_v2_python_sparse | floris/tools/optimization/yaw_optimization/yaw_optimizer_scipy.py | NREL/floris | train | 151 |
0bcc5ef1ddbbef9794b9aa79f758fc1bdbdb0f35 | [
"Exception.__init__(self)\nself.message = message\nself.status_code = status_code\nself.payload = payload",
"ret_val = dict(self.payload or ())\nret_val['message'] = self.message\nreturn ret_val"
] | <|body_start_0|>
Exception.__init__(self)
self.message = message
self.status_code = status_code
self.payload = payload
<|end_body_0|>
<|body_start_1|>
ret_val = dict(self.payload or ())
ret_val['message'] = self.message
return ret_val
<|end_body_1|>
| Class to represent invalid API usage or when Route is not available. | InvalidAPIUsage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvalidAPIUsage:
"""Class to represent invalid API usage or when Route is not available."""
def __init__(self, message='Some error occurred. Please try again.', status_code=html_codes.HTTP_BAD_REQUEST, payload=None):
"""Initialize the class with proper message and status_code."""
... | stack_v2_sparse_classes_36k_train_015156 | 762 | no_license | [
{
"docstring": "Initialize the class with proper message and status_code.",
"name": "__init__",
"signature": "def __init__(self, message='Some error occurred. Please try again.', status_code=html_codes.HTTP_BAD_REQUEST, payload=None)"
},
{
"docstring": "Convert message to a dict to be returned i... | 2 | stack_v2_sparse_classes_30k_train_006144 | Implement the Python class `InvalidAPIUsage` described below.
Class description:
Class to represent invalid API usage or when Route is not available.
Method signatures and docstrings:
- def __init__(self, message='Some error occurred. Please try again.', status_code=html_codes.HTTP_BAD_REQUEST, payload=None): Initial... | Implement the Python class `InvalidAPIUsage` described below.
Class description:
Class to represent invalid API usage or when Route is not available.
Method signatures and docstrings:
- def __init__(self, message='Some error occurred. Please try again.', status_code=html_codes.HTTP_BAD_REQUEST, payload=None): Initial... | 473aa1c4445a71f8c272ab01c30e7a7ffe29f78a | <|skeleton|>
class InvalidAPIUsage:
"""Class to represent invalid API usage or when Route is not available."""
def __init__(self, message='Some error occurred. Please try again.', status_code=html_codes.HTTP_BAD_REQUEST, payload=None):
"""Initialize the class with proper message and status_code."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvalidAPIUsage:
"""Class to represent invalid API usage or when Route is not available."""
def __init__(self, message='Some error occurred. Please try again.', status_code=html_codes.HTTP_BAD_REQUEST, payload=None):
"""Initialize the class with proper message and status_code."""
Exceptio... | the_stack_v2_python_sparse | web/server/utils/errors.py | adrianplusplus/rest-api | train | 0 |
e19cb802b7b66cf80fdc4da41cf4ae2d6e4bb1bc | [
"if not nums:\n return\nnums.sort()\nhalf = len(nums) // 2\nnums[:half] = nums[:half][::-1]\ni = 1\nj = len(nums) - 1\nwhile j > len(nums) // 2:\n val = nums.pop()\n nums.insert(i, val)\n i += 2\n j -= 1",
"arr = sorted(nums)\nfor i in range(1, len(nums), 2):\n nums[i] = arr.pop()\nfor i in rang... | <|body_start_0|>
if not nums:
return
nums.sort()
half = len(nums) // 2
nums[:half] = nums[:half][::-1]
i = 1
j = len(nums) - 1
while j > len(nums) // 2:
val = nums.pop()
nums.insert(i, val)
i += 2
j -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def wiggleSort2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k_train_015157 | 1,414 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "wiggleSort",
"signature": "def wiggleSort(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "wi... | 3 | stack_v2_sparse_classes_30k_train_021426 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def wiggleSort2(self, nums): :type nums: List[int] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def wiggleSort2(self, nums): :type nums: List[int] :rtype: ... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def wiggleSort2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
if not nums:
return
nums.sort()
half = len(nums) // 2
nums[:half] = nums[:half][::-1]
i = 1
j = len(nums) - 1... | the_stack_v2_python_sparse | 324. Wiggle Sort II/wiggle.py | Macielyoung/LeetCode | train | 1 | |
242179912e1d8753e3765c7faef75c124506dca6 | [
"super(Attention, self).__init__()\nself.linear_h = nn.Linear(input_dim, hidden_size, bias=False)\nself.linear_c = nn.Linear(candidate_dim, hidden_size, bias=False)\nself.softmax = nn.Softmax(dim=1)\nself.linear_out = nn.Linear(hidden_size, 1, bias=False)\nself.tanh = nn.Tanh()\nself.output_logits = output_logits",... | <|body_start_0|>
super(Attention, self).__init__()
self.linear_h = nn.Linear(input_dim, hidden_size, bias=False)
self.linear_c = nn.Linear(candidate_dim, hidden_size, bias=False)
self.softmax = nn.Softmax(dim=1)
self.linear_out = nn.Linear(hidden_size, 1, bias=False)
self... | Generic Attention module | Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Generic Attention module"""
def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False):
"""Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned."... | stack_v2_sparse_classes_36k_train_015158 | 14,666 | permissive | [
{
"docstring": "Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned.",
"name": "__init__",
"signature": "def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_020311 | Implement the Python class `Attention` described below.
Class description:
Generic Attention module
Method signatures and docstrings:
- def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False): Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwi... | Implement the Python class `Attention` described below.
Class description:
Generic Attention module
Method signatures and docstrings:
- def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False): Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwi... | f819aea21b94d9d3e23d9b6b9264054ee50c007b | <|skeleton|>
class Attention:
"""Generic Attention module"""
def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False):
"""Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""Generic Attention module"""
def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False):
"""Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned."""
su... | the_stack_v2_python_sparse | tracker/modules/components.py | iCodeIN/vln-chasing-ghosts | train | 0 |
3ea9e57ce4fe508c710b8c1cc2b677db19cbc776 | [
"super(CloudWatchClient, self).__init__(region_name=region_name, max_retry_attempts=max_retry_attempts, backoff_time_sec=backoff_time_sec, boto_client_name=self.name, session=session)\nself._log_and_cont = log_and_cont\nself._max_retry_attempts = max_retry_attempts",
"try:\n return self.get_client()\nexcept Ex... | <|body_start_0|>
super(CloudWatchClient, self).__init__(region_name=region_name, max_retry_attempts=max_retry_attempts, backoff_time_sec=backoff_time_sec, boto_client_name=self.name, session=session)
self._log_and_cont = log_and_cont
self._max_retry_attempts = max_retry_attempts
<|end_body_0|>
... | CloudWatch Boto Client | CloudWatchClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudWatchClient:
"""CloudWatch Boto Client"""
def __init__(self, region_name='us-east-1', max_retry_attempts=5, backoff_time_sec=1.0, session=None, log_and_cont=False):
"""CloudWatch client Args: region_name (str): aws region name. max_retry_attempts (int): maximum number of retry. ... | stack_v2_sparse_classes_36k_train_015159 | 7,572 | permissive | [
{
"docstring": "CloudWatch client Args: region_name (str): aws region name. max_retry_attempts (int): maximum number of retry. backoff_time_sec (float): backoff second between each retry. session (boto3.Session): An alternative session to use. Defaults to None. log_and_cont (bool, optional): Log the error and c... | 6 | null | Implement the Python class `CloudWatchClient` described below.
Class description:
CloudWatch Boto Client
Method signatures and docstrings:
- def __init__(self, region_name='us-east-1', max_retry_attempts=5, backoff_time_sec=1.0, session=None, log_and_cont=False): CloudWatch client Args: region_name (str): aws region ... | Implement the Python class `CloudWatchClient` described below.
Class description:
CloudWatch Boto Client
Method signatures and docstrings:
- def __init__(self, region_name='us-east-1', max_retry_attempts=5, backoff_time_sec=1.0, session=None, log_and_cont=False): CloudWatch client Args: region_name (str): aws region ... | 2ce50508dd4100eaef7f8729436549a801505705 | <|skeleton|>
class CloudWatchClient:
"""CloudWatch Boto Client"""
def __init__(self, region_name='us-east-1', max_retry_attempts=5, backoff_time_sec=1.0, session=None, log_and_cont=False):
"""CloudWatch client Args: region_name (str): aws region name. max_retry_attempts (int): maximum number of retry. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudWatchClient:
"""CloudWatch Boto Client"""
def __init__(self, region_name='us-east-1', max_retry_attempts=5, backoff_time_sec=1.0, session=None, log_and_cont=False):
"""CloudWatch client Args: region_name (str): aws region name. max_retry_attempts (int): maximum number of retry. backoff_time_... | the_stack_v2_python_sparse | bundle/markov/boto/cloudwatch/cloudwatch_client.py | aws-deepracer-community/deepracer-simapp | train | 83 |
b5e7cdc5752a78168aa4cc3cad4b9861cd7ce4e5 | [
"self.__case_folder = CaseFolder()\nself.__tokenizer = Tokenizer()\nstopword_remover_factory = StopwordRemoverFactory()\nself.__stopword_remover = stopword_remover_factory.create()\nstemmer_factory = StemmerFactory()\nself.__stemmer = stemmer_factory.create()\nself.__tf_unigram = TfUnigram()\nself.__tf_bigram = TfB... | <|body_start_0|>
self.__case_folder = CaseFolder()
self.__tokenizer = Tokenizer()
stopword_remover_factory = StopwordRemoverFactory()
self.__stopword_remover = stopword_remover_factory.create()
stemmer_factory = StemmerFactory()
self.__stemmer = stemmer_factory.create()
... | Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing) | Preprocesser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocesser:
"""Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)"""
def __init__(self):
"""Konstruktor"""
<|body_0|>
def __del__(self):
"""Destructor"""
<|body_1|>
def __get_features(self, tokens: list):
"""Mendapatkan Fitur Ruang-Ve... | stack_v2_sparse_classes_36k_train_015160 | 2,073 | no_license | [
{
"docstring": "Konstruktor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Destructor",
"name": "__del__",
"signature": "def __del__(self)"
},
{
"docstring": "Mendapatkan Fitur Ruang-Vektor Kombinasi Unigram dan Bigram",
"name": "__get_features",
... | 5 | stack_v2_sparse_classes_30k_train_000769 | Implement the Python class `Preprocesser` described below.
Class description:
Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)
Method signatures and docstrings:
- def __init__(self): Konstruktor
- def __del__(self): Destructor
- def __get_features(self, tokens: list): Mendapatkan Fitur Ruang-Vektor Kombinasi ... | Implement the Python class `Preprocesser` described below.
Class description:
Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)
Method signatures and docstrings:
- def __init__(self): Konstruktor
- def __del__(self): Destructor
- def __get_features(self, tokens: list): Mendapatkan Fitur Ruang-Vektor Kombinasi ... | 9742c193251303334ef805c8c94eb075afad777f | <|skeleton|>
class Preprocesser:
"""Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)"""
def __init__(self):
"""Konstruktor"""
<|body_0|>
def __del__(self):
"""Destructor"""
<|body_1|>
def __get_features(self, tokens: list):
"""Mendapatkan Fitur Ruang-Ve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preprocesser:
"""Bertugas Melakukan Pemrosesan Teks (Text Proeprocessing)"""
def __init__(self):
"""Konstruktor"""
self.__case_folder = CaseFolder()
self.__tokenizer = Tokenizer()
stopword_remover_factory = StopwordRemoverFactory()
self.__stopword_remover = stopwor... | the_stack_v2_python_sparse | ujian_app/penilaian/pemrosesan_teks/preprocesser.py | anh4rs/Aplikasi-Penilaian-Otomatis-Esai-BI | train | 0 |
27c837c7d32b0e76088841c52ca2b150c0ae7154 | [
"k = k % len(nums)\nfor i in range(k):\n tmp = nums[-1]\n nums[1:] = nums[:-1]\n nums[0] = tmp",
"n = len(nums)\nk = k % n\nnums[:] = nums[n - k:] + nums[:n - k]"
] | <|body_start_0|>
k = k % len(nums)
for i in range(k):
tmp = nums[-1]
nums[1:] = nums[:-1]
nums[0] = tmp
<|end_body_0|>
<|body_start_1|>
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + nums[:n - k]
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate2(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtyp... | stack_v2_sparse_classes_36k_train_015161 | 866 | no_license | [
{
"docstring": "Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate2",
"signature": "def rotate2(self, nums, k)"
},
{
"docstring": "Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not r... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate2(self, nums, k): Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate(self, nums, k):... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate2(self, nums, k): Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate(self, nums, k):... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def rotate2(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate2(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
k = k % len(nums)
for i in range(k):
tmp = nums[-1]
nums[1:] = nums[:-1]
nums[0] = t... | the_stack_v2_python_sparse | 101-200/189. Rotate Array.py | SunnyMarkLiu/LeetCode | train | 1 | |
3aebed1187e0a3086bc994d64758c0dafedd22af | [
"if root is None:\n return\nif root.left is None and root.right is None:\n res[0] += partial * 10 + root.val\n return\nself.sumNumbersHelper(root.left, partial * 10 + root.val, res)\nself.sumNumbersHelper(root.right, partial * 10 + root.val, res)",
"res = [0]\nself.sumNumbersHelper(root, partial=0, res=r... | <|body_start_0|>
if root is None:
return
if root.left is None and root.right is None:
res[0] += partial * 10 + root.val
return
self.sumNumbersHelper(root.left, partial * 10 + root.val, res)
self.sumNumbersHelper(root.right, partial * 10 + root.val, res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbersHelper(self, root, partial, res):
"""partial is a number, before comming to this level res is a list of one number. We will update that number"""
<|body_0|>
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_015162 | 901 | no_license | [
{
"docstring": "partial is a number, before comming to this level res is a list of one number. We will update that number",
"name": "sumNumbersHelper",
"signature": "def sumNumbersHelper(self, root, partial, res)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers",
... | 2 | stack_v2_sparse_classes_30k_train_004099 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbersHelper(self, root, partial, res): partial is a number, before comming to this level res is a list of one number. We will update that number
- def sumNumbers(self, r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbersHelper(self, root, partial, res): partial is a number, before comming to this level res is a list of one number. We will update that number
- def sumNumbers(self, r... | 6e051eb554d9cf6f424f1e0a77f3072adf7f64c4 | <|skeleton|>
class Solution:
def sumNumbersHelper(self, root, partial, res):
"""partial is a number, before comming to this level res is a list of one number. We will update that number"""
<|body_0|>
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbersHelper(self, root, partial, res):
"""partial is a number, before comming to this level res is a list of one number. We will update that number"""
if root is None:
return
if root.left is None and root.right is None:
res[0] += partial * 10 ... | the_stack_v2_python_sparse | 129. Sum Root to Leaf Numbers.py | vincent-kangzhou/LeetCode-Python | train | 0 | |
c0ab1201cfeb26d246951258c47f02e5c0d20e83 | [
"super(GenericNet, self).__init__(name=model_name)\nfor key, val in kwargs.items():\n setattr(self, key, val)\nif self.name_scope is None:\n self.name_scope = model_name\nwith tf.name_scope(self.name_scope):\n self.flatten = tf.keras.layers.Flatten(name='flatten')\n with tf.name_scope('x_layer'):\n ... | <|body_start_0|>
super(GenericNet, self).__init__(name=model_name)
for key, val in kwargs.items():
setattr(self, key, val)
if self.name_scope is None:
self.name_scope = model_name
with tf.name_scope(self.name_scope):
self.flatten = tf.keras.layers.Flat... | Conv. neural net with different initialization scale based on input. | GenericNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericNet:
"""Conv. neural net with different initialization scale based on input."""
def __init__(self, model_name='GenericNet', **kwargs):
"""Initialization method."""
<|body_0|>
def call(self, inputs):
"""call method. NOTE Architecture looks like: * inputs: x... | stack_v2_sparse_classes_36k_train_015163 | 5,329 | permissive | [
{
"docstring": "Initialization method.",
"name": "__init__",
"signature": "def __init__(self, model_name='GenericNet', **kwargs)"
},
{
"docstring": "call method. NOTE Architecture looks like: * inputs: x, v, t x --> FLATTEN_X --> X_LAYER --> X_OUT v --> FLATTEN_V --> V_LAYER --> V_OUT t --> T_LA... | 2 | stack_v2_sparse_classes_30k_val_000722 | Implement the Python class `GenericNet` described below.
Class description:
Conv. neural net with different initialization scale based on input.
Method signatures and docstrings:
- def __init__(self, model_name='GenericNet', **kwargs): Initialization method.
- def call(self, inputs): call method. NOTE Architecture lo... | Implement the Python class `GenericNet` described below.
Class description:
Conv. neural net with different initialization scale based on input.
Method signatures and docstrings:
- def __init__(self, model_name='GenericNet', **kwargs): Initialization method.
- def call(self, inputs): call method. NOTE Architecture lo... | db58c2f1a90d6631de30343a7f76d093d7e6b48f | <|skeleton|>
class GenericNet:
"""Conv. neural net with different initialization scale based on input."""
def __init__(self, model_name='GenericNet', **kwargs):
"""Initialization method."""
<|body_0|>
def call(self, inputs):
"""call method. NOTE Architecture looks like: * inputs: x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericNet:
"""Conv. neural net with different initialization scale based on input."""
def __init__(self, model_name='GenericNet', **kwargs):
"""Initialization method."""
super(GenericNet, self).__init__(name=model_name)
for key, val in kwargs.items():
setattr(self, ke... | the_stack_v2_python_sparse | l2hmc/network/generic_net.py | saforem2/l2hmc | train | 1 |
2ab3c10d8a9c12c4b6199fa2938692dea29b3d75 | [
"super(Unxz, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.options = options\nself.xz_file = xz_file\nself.ret_required = False",
"if self.options:\n cmd = '{} {} {}'.format('unxz', self.options, self.xz_file)\nelse:\n cmd = '{} {}'.format('unxz', sel... | <|body_start_0|>
super(Unxz, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
self.options = options
self.xz_file = xz_file
self.ret_required = False
<|end_body_0|>
<|body_start_1|>
if self.options:
cmd = '{} {} {}'.for... | Unxz command class. | Unxz | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unxz:
"""Unxz command class."""
def __init__(self, connection, xz_file, options='', prompt=None, newline_chars=None, runner=None):
"""Unxz command. :param connection: Moler connection to device, terminal when command is executed. :param xz_file: Name of a file which shall be extracte... | stack_v2_sparse_classes_36k_train_015164 | 1,818 | permissive | [
{
"docstring": "Unxz command. :param connection: Moler connection to device, terminal when command is executed. :param xz_file: Name of a file which shall be extracted. :param options: Options of command unxz. :param prompt: Expected prompt that has been sent by device after command execution. :param newline_ch... | 2 | null | Implement the Python class `Unxz` described below.
Class description:
Unxz command class.
Method signatures and docstrings:
- def __init__(self, connection, xz_file, options='', prompt=None, newline_chars=None, runner=None): Unxz command. :param connection: Moler connection to device, terminal when command is execute... | Implement the Python class `Unxz` described below.
Class description:
Unxz command class.
Method signatures and docstrings:
- def __init__(self, connection, xz_file, options='', prompt=None, newline_chars=None, runner=None): Unxz command. :param connection: Moler connection to device, terminal when command is execute... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class Unxz:
"""Unxz command class."""
def __init__(self, connection, xz_file, options='', prompt=None, newline_chars=None, runner=None):
"""Unxz command. :param connection: Moler connection to device, terminal when command is executed. :param xz_file: Name of a file which shall be extracte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Unxz:
"""Unxz command class."""
def __init__(self, connection, xz_file, options='', prompt=None, newline_chars=None, runner=None):
"""Unxz command. :param connection: Moler connection to device, terminal when command is executed. :param xz_file: Name of a file which shall be extracted. :param opt... | the_stack_v2_python_sparse | moler/cmd/unix/unxz.py | nokia/moler | train | 60 |
855b21380e26916be92250eee201b437aa9dc315 | [
"action_space = Bag([])\naction_space.seed(seed=seed)\nsuper().__init__(initial_state=initial_state, default_reward=default_reward, seed=seed, columns=columns, action_space=action_space)",
"x, y = position\nif action == self.actions['RIGHT']:\n x += 1\nelif action == self.actions['DOWN']:\n y += 1\nnext_pos... | <|body_start_0|>
action_space = Bag([])
action_space.seed(seed=seed)
super().__init__(initial_state=initial_state, default_reward=default_reward, seed=seed, columns=columns, action_space=action_space)
<|end_body_0|>
<|body_start_1|>
x, y = position
if action == self.actions['RIG... | DeepSeaTreasureRightDown | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepSeaTreasureRightDown:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=10):
""":param initial_state: Initial state where start the agent. :param default_reward: (time_inverted, treasure_value) :param seed: Seed used for np.random.R... | stack_v2_sparse_classes_36k_train_015165 | 4,417 | no_license | [
{
"docstring": ":param initial_state: Initial state where start the agent. :param default_reward: (time_inverted, treasure_value) :param seed: Seed used for np.random.RandomState method. :param columns: Number of columns to be used to build this environment (allows experimenting with an identical environment, b... | 4 | null | Implement the Python class `DeepSeaTreasureRightDown` described below.
Class description:
Implement the DeepSeaTreasureRightDown class.
Method signatures and docstrings:
- def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=10): :param initial_state: Initial state whe... | Implement the Python class `DeepSeaTreasureRightDown` described below.
Class description:
Implement the DeepSeaTreasureRightDown class.
Method signatures and docstrings:
- def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=10): :param initial_state: Initial state whe... | b51c64c867e15356c9f978839fd0040182324edd | <|skeleton|>
class DeepSeaTreasureRightDown:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=10):
""":param initial_state: Initial state where start the agent. :param default_reward: (time_inverted, treasure_value) :param seed: Seed used for np.random.R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepSeaTreasureRightDown:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=10):
""":param initial_state: Initial state where start the agent. :param default_reward: (time_inverted, treasure_value) :param seed: Seed used for np.random.RandomState met... | the_stack_v2_python_sparse | environments/deep_sea_treasure_right_down.py | Pozas91/tiadas | train | 1 | |
8a105f7e25566198b7b23bb0f50aae758ce128e3 | [
"super(ResNet_Det, self).__init__()\nself.net_desc = desc\nself.depth = desc['depth']\nself.num_stages = desc['num_stages'] if 'num_stages' in desc else 4\nself.strides = desc['strides'] if 'strides' in desc else (1, 2, 2, 2)\nself.dilations = desc['dilations'] if 'dilations' in desc else (1, 1, 1, 1)\nself.out_ind... | <|body_start_0|>
super(ResNet_Det, self).__init__()
self.net_desc = desc
self.depth = desc['depth']
self.num_stages = desc['num_stages'] if 'num_stages' in desc else 4
self.strides = desc['strides'] if 'strides' in desc else (1, 2, 2, 2)
self.dilations = desc['dilations']... | ResNet for detection. | ResNet_Det | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet_Det:
"""ResNet for detection."""
def __init__(self, desc):
"""Init ResNet."""
<|body_0|>
def _make_stem_layer(self):
"""Make stem layer."""
<|body_1|>
def _freeze_stages(self):
"""Freeze stages."""
<|body_2|>
def init_weig... | stack_v2_sparse_classes_36k_train_015166 | 6,387 | permissive | [
{
"docstring": "Init ResNet.",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Make stem layer.",
"name": "_make_stem_layer",
"signature": "def _make_stem_layer(self)"
},
{
"docstring": "Freeze stages.",
"name": "_freeze_stages",
"signature"... | 6 | stack_v2_sparse_classes_30k_test_000182 | Implement the Python class `ResNet_Det` described below.
Class description:
ResNet for detection.
Method signatures and docstrings:
- def __init__(self, desc): Init ResNet.
- def _make_stem_layer(self): Make stem layer.
- def _freeze_stages(self): Freeze stages.
- def init_weights(self, pretrained=None): Init weight.... | Implement the Python class `ResNet_Det` described below.
Class description:
ResNet for detection.
Method signatures and docstrings:
- def __init__(self, desc): Init ResNet.
- def _make_stem_layer(self): Make stem layer.
- def _freeze_stages(self): Freeze stages.
- def init_weights(self, pretrained=None): Init weight.... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class ResNet_Det:
"""ResNet for detection."""
def __init__(self, desc):
"""Init ResNet."""
<|body_0|>
def _make_stem_layer(self):
"""Make stem layer."""
<|body_1|>
def _freeze_stages(self):
"""Freeze stages."""
<|body_2|>
def init_weig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResNet_Det:
"""ResNet for detection."""
def __init__(self, desc):
"""Init ResNet."""
super(ResNet_Det, self).__init__()
self.net_desc = desc
self.depth = desc['depth']
self.num_stages = desc['num_stages'] if 'num_stages' in desc else 4
self.strides = desc['... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/pytorch/backbones/resnet_det.py | Huawei-Ascend/modelzoo | train | 1 |
3baae2be9cec4db151086ae8aeebcc1d39b7c8a4 | [
"sql = \"SELECT stock_id, rmw_type FROM base_finance.stock_type_style WHERE `date` > '{start}' AND `date` <= '{end}'\".format(start=start, end=end)\ndf = pd.read_sql(sql, cls.engine)\nd = {0: 'W', 1: 'M', 2: 'R'}\ndf['rmw_type'] = df['rmw_type'].apply(lambda x: d.get(x))\ndf = df.dropna()\nreturn df.groupby('rmw_ty... | <|body_start_0|>
sql = "SELECT stock_id, rmw_type FROM base_finance.stock_type_style WHERE `date` > '{start}' AND `date` <= '{end}'".format(start=start, end=end)
df = pd.read_sql(sql, cls.engine)
d = {0: 'W', 1: 'M', 2: 'R'}
df['rmw_type'] = df['rmw_type'].apply(lambda x: d.get(x))
... | FamaFrenchDataloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FamaFrenchDataloader:
def load_type_rmw(cls, start, end):
"""Robust minus Weak"""
<|body_0|>
def load_type_cma(cls, start, end):
"""Conservative minus Aggressive"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sql = "SELECT stock_id, rmw_type FROM b... | stack_v2_sparse_classes_36k_train_015167 | 6,329 | no_license | [
{
"docstring": "Robust minus Weak",
"name": "load_type_rmw",
"signature": "def load_type_rmw(cls, start, end)"
},
{
"docstring": "Conservative minus Aggressive",
"name": "load_type_cma",
"signature": "def load_type_cma(cls, start, end)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013221 | Implement the Python class `FamaFrenchDataloader` described below.
Class description:
Implement the FamaFrenchDataloader class.
Method signatures and docstrings:
- def load_type_rmw(cls, start, end): Robust minus Weak
- def load_type_cma(cls, start, end): Conservative minus Aggressive | Implement the Python class `FamaFrenchDataloader` described below.
Class description:
Implement the FamaFrenchDataloader class.
Method signatures and docstrings:
- def load_type_rmw(cls, start, end): Robust minus Weak
- def load_type_cma(cls, start, end): Conservative minus Aggressive
<|skeleton|>
class FamaFrenchDa... | 5dc1eed2739ea0f54c48e6de7de03932e1a9091c | <|skeleton|>
class FamaFrenchDataloader:
def load_type_rmw(cls, start, end):
"""Robust minus Weak"""
<|body_0|>
def load_type_cma(cls, start, end):
"""Conservative minus Aggressive"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FamaFrenchDataloader:
def load_type_rmw(cls, start, end):
"""Robust minus Weak"""
sql = "SELECT stock_id, rmw_type FROM base_finance.stock_type_style WHERE `date` > '{start}' AND `date` <= '{end}'".format(start=start, end=end)
df = pd.read_sql(sql, cls.engine)
d = {0: 'W', 1: '... | the_stack_v2_python_sparse | utils/algorithm/fama/share/sqlfactory.py | Chihihiro/index | train | 1 | |
e289205113301f5ec8e762154fa23b908b845812 | [
"if serializer_class is None:\n if 'context' in kwargs.keys():\n kwargs.pop('context')\n return self.get_serializer(queryset, *args, **kwargs)\nreturn serializer_class(queryset, *args, context=self.get_serializer_context(), **kwargs)",
"if plan_pk is None:\n queryset = self.get_queryset()\nelse:\n... | <|body_start_0|>
if serializer_class is None:
if 'context' in kwargs.keys():
kwargs.pop('context')
return self.get_serializer(queryset, *args, **kwargs)
return serializer_class(queryset, *args, context=self.get_serializer_context(), **kwargs)
<|end_body_0|>
<|bod... | /plans/<plan_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin | PlanNestedListMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlanNestedListMixin:
"""/plans/<plan_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin"""
def _serialize(self, serializer_class, queryset, *args, **kwargs):
"""Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位... | stack_v2_sparse_classes_36k_train_015168 | 5,541 | no_license | [
{
"docstring": "Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位置引数 :param kwargs: Serializerをインスタンス化する際のオプション引数 :return: インスタンス化されたSerializer",
"name": "_serialize",
"signature": "def _serialize(self, serializer_class... | 2 | stack_v2_sparse_classes_30k_train_004933 | Implement the Python class `PlanNestedListMixin` described below.
Class description:
/plans/<plan_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin
Method signatures and docstrings:
- def _serialize(self, serializer_class, queryset, *args, **kwargs): Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用... | Implement the Python class `PlanNestedListMixin` described below.
Class description:
/plans/<plan_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin
Method signatures and docstrings:
- def _serialize(self, serializer_class, queryset, *args, **kwargs): Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用... | 6f9487dcfc13c706d312be6586159c7d3a25c6aa | <|skeleton|>
class PlanNestedListMixin:
"""/plans/<plan_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin"""
def _serialize(self, serializer_class, queryset, *args, **kwargs):
"""Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlanNestedListMixin:
"""/plans/<plan_pk>/favs/ のようなネストされた要素に対してリストを返す時のmixin"""
def _serialize(self, serializer_class, queryset, *args, **kwargs):
"""Serializerの指定があればそれで返す.無ければself.get_serializerする. :param serializer_class: 使用するSerializerクラスを指定する :param args: Serializerをインスタンス化する際の位置引数 :param kw... | the_stack_v2_python_sparse | src/plan/mixins.py | jphacks/KB_1809_2 | train | 3 |
e6164e470ea8b3e7fb60a21db9dd465ee5738e07 | [
"with self.assertRaises(ValidationError):\n miner = Miner(name='Some Miner', version='1.0.0', slug='create')\n miner.full_clean()\n miner.save()",
"miner = Miner(name='Some Miner', version='1.0.0', slug='some-miner-slug')\nminer.full_clean()\nminer.save()"
] | <|body_start_0|>
with self.assertRaises(ValidationError):
miner = Miner(name='Some Miner', version='1.0.0', slug='create')
miner.full_clean()
miner.save()
<|end_body_0|>
<|body_start_1|>
miner = Miner(name='Some Miner', version='1.0.0', slug='some-miner-slug')
... | Тестирование валидатора slug | SlugValidatorTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlugValidatorTest:
"""Тестирование валидатора slug"""
def test_validate_invalid_slug(self):
"""Тестирование invalid slug"""
<|body_0|>
def test_validate_valid_slug(self):
"""Тестирование valid slug"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015169 | 13,105 | permissive | [
{
"docstring": "Тестирование invalid slug",
"name": "test_validate_invalid_slug",
"signature": "def test_validate_invalid_slug(self)"
},
{
"docstring": "Тестирование valid slug",
"name": "test_validate_valid_slug",
"signature": "def test_validate_valid_slug(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009378 | Implement the Python class `SlugValidatorTest` described below.
Class description:
Тестирование валидатора slug
Method signatures and docstrings:
- def test_validate_invalid_slug(self): Тестирование invalid slug
- def test_validate_valid_slug(self): Тестирование valid slug | Implement the Python class `SlugValidatorTest` described below.
Class description:
Тестирование валидатора slug
Method signatures and docstrings:
- def test_validate_invalid_slug(self): Тестирование invalid slug
- def test_validate_valid_slug(self): Тестирование valid slug
<|skeleton|>
class SlugValidatorTest:
"... | d173f1bee44d0752eefb53b1a0da847a3882a352 | <|skeleton|>
class SlugValidatorTest:
"""Тестирование валидатора slug"""
def test_validate_invalid_slug(self):
"""Тестирование invalid slug"""
<|body_0|>
def test_validate_valid_slug(self):
"""Тестирование valid slug"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlugValidatorTest:
"""Тестирование валидатора slug"""
def test_validate_invalid_slug(self):
"""Тестирование invalid slug"""
with self.assertRaises(ValidationError):
miner = Miner(name='Some Miner', version='1.0.0', slug='create')
miner.full_clean()
mine... | the_stack_v2_python_sparse | miningstatistic/core/tests.py | crowmurk/miners | train | 0 |
5166e5b9694523545e23a2888f9b58ad2747dfe9 | [
"already_exist = self.check_if_already_registered(substitute)\nif already_exist == None:\n connector = Connector()\n cnx = connector.connection()\n cursor = cnx.cursor()\n query = 'INSERT INTO substitutes(initial_product_id, substituted_product_id) VALUES(%s, %s)'\n cursor.execute(query, (substitute.... | <|body_start_0|>
already_exist = self.check_if_already_registered(substitute)
if already_exist == None:
connector = Connector()
cnx = connector.connection()
cursor = cnx.cursor()
query = 'INSERT INTO substitutes(initial_product_id, substituted_product_id) ... | SubstituteService class To manage the relationship between the Substitute object and the MySQL database | SubstituteService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubstituteService:
"""SubstituteService class To manage the relationship between the Substitute object and the MySQL database"""
def insert(self, substitute):
"""Insert substitute data in database"""
<|body_0|>
def check_if_already_registered(self, substitute):
"... | stack_v2_sparse_classes_36k_train_015170 | 4,237 | no_license | [
{
"docstring": "Insert substitute data in database",
"name": "insert",
"signature": "def insert(self, substitute)"
},
{
"docstring": "Check if a substitute (couple \"initial food\" + \"substituted food\") already exists in the database.",
"name": "check_if_already_registered",
"signature... | 3 | stack_v2_sparse_classes_30k_train_021101 | Implement the Python class `SubstituteService` described below.
Class description:
SubstituteService class To manage the relationship between the Substitute object and the MySQL database
Method signatures and docstrings:
- def insert(self, substitute): Insert substitute data in database
- def check_if_already_registe... | Implement the Python class `SubstituteService` described below.
Class description:
SubstituteService class To manage the relationship between the Substitute object and the MySQL database
Method signatures and docstrings:
- def insert(self, substitute): Insert substitute data in database
- def check_if_already_registe... | 377deb35afe3749c8db8d09a55d4b69f8a8238a0 | <|skeleton|>
class SubstituteService:
"""SubstituteService class To manage the relationship between the Substitute object and the MySQL database"""
def insert(self, substitute):
"""Insert substitute data in database"""
<|body_0|>
def check_if_already_registered(self, substitute):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubstituteService:
"""SubstituteService class To manage the relationship between the Substitute object and the MySQL database"""
def insert(self, substitute):
"""Insert substitute data in database"""
already_exist = self.check_if_already_registered(substitute)
if already_exist == ... | the_stack_v2_python_sparse | src/data/db/substitute_service.py | Githb-usr/substitution | train | 0 |
53283867c4bc673431004b1b84d247a8f2199241 | [
"super(TorchvisionSSLRotation, self).__init__()\nself.model_function = get_object_from_path(config.cfg['model']['model_function_path'])\nself.pretrained = config.cfg['model']['pretrained']\nself.num_classes_classification = config.cfg['model']['classes_count']\nself.num_classes_rot = config.cfg['model']['rotation_c... | <|body_start_0|>
super(TorchvisionSSLRotation, self).__init__()
self.model_function = get_object_from_path(config.cfg['model']['model_function_path'])
self.pretrained = config.cfg['model']['pretrained']
self.num_classes_classification = config.cfg['model']['classes_count']
self.n... | The class adds rotation as an auxiliary task to the standard torchvision network. | TorchvisionSSLRotation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TorchvisionSSLRotation:
"""The class adds rotation as an auxiliary task to the standard torchvision network."""
def __init__(self, config):
"""Constructor, the function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object"""... | stack_v2_sparse_classes_36k_train_015171 | 2,485 | permissive | [
{
"docstring": "Constructor, the function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "The function implements the forward pass of the model. :pa... | 2 | stack_v2_sparse_classes_30k_train_010748 | Implement the Python class `TorchvisionSSLRotation` described below.
Class description:
The class adds rotation as an auxiliary task to the standard torchvision network.
Method signatures and docstrings:
- def __init__(self, config): Constructor, the function parse the config and initialize the layers of the correspo... | Implement the Python class `TorchvisionSSLRotation` described below.
Class description:
The class adds rotation as an auxiliary task to the standard torchvision network.
Method signatures and docstrings:
- def __init__(self, config): Constructor, the function parse the config and initialize the layers of the correspo... | 9a4bf0a112b818caca8794868a903dc736839a43 | <|skeleton|>
class TorchvisionSSLRotation:
"""The class adds rotation as an auxiliary task to the standard torchvision network."""
def __init__(self, config):
"""Constructor, the function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TorchvisionSSLRotation:
"""The class adds rotation as an auxiliary task to the standard torchvision network."""
def __init__(self, config):
"""Constructor, the function parse the config and initialize the layers of the corresponding model. :param config: Configuration class object"""
supe... | the_stack_v2_python_sparse | model/torchvision_ssl_rotation.py | Niousha12/ssl_for_fgvc | train | 0 |
bc7de1f208e99a5991ed3cfe3933b5909fa0cbbe | [
"self.data = dict()\nself.max = float('-inf')\nself.min = float('inf')",
"self.data[number] = self.data.get(number, 0) + 1\nif number > self.max:\n self.max = number\nif number < self.min:\n self.min = number",
"if value > self.max * 2 or value < self.min * 2:\n return False\ndic = self.data\nfor k in ... | <|body_start_0|>
self.data = dict()
self.max = float('-inf')
self.min = float('inf')
<|end_body_0|>
<|body_start_1|>
self.data[number] = self.data.get(number, 0) + 1
if number > self.max:
self.max = number
if number < self.min:
self.min = number
<... | TwoSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoSum:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def add(self, number):
"""Add the number to an internal data structure.. :type number: int :rtype: None"""
<|body_1|>
def find(self, value):
"""Find if there exists... | stack_v2_sparse_classes_36k_train_015172 | 1,115 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add the number to an internal data structure.. :type number: int :rtype: None",
"name": "add",
"signature": "def add(self, number)"
},
{
"docstring": "F... | 3 | stack_v2_sparse_classes_30k_train_009734 | Implement the Python class `TwoSum` described below.
Class description:
Implement the TwoSum class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def add(self, number): Add the number to an internal data structure.. :type number: int :rtype: None
- def find(self, value... | Implement the Python class `TwoSum` described below.
Class description:
Implement the TwoSum class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def add(self, number): Add the number to an internal data structure.. :type number: int :rtype: None
- def find(self, value... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class TwoSum:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def add(self, number):
"""Add the number to an internal data structure.. :type number: int :rtype: None"""
<|body_1|>
def find(self, value):
"""Find if there exists... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoSum:
def __init__(self):
"""Initialize your data structure here."""
self.data = dict()
self.max = float('-inf')
self.min = float('inf')
def add(self, number):
"""Add the number to an internal data structure.. :type number: int :rtype: None"""
self.data[n... | the_stack_v2_python_sparse | _0170_Two_Sum III_Data_structure_design.py | mingweihe/leetcode | train | 3 | |
89825e71b6994510bab81350757ae7eae38b5a6c | [
"self.source = source\nself.count_tags = tags\nself.aggregate_tag = aggregate_tag\nself.saved_columns = None\nself.aggregate_iter = None",
"if self.saved_columns is None:\n cols = []\n for tag in self.count_tags:\n cols.append(HXLColumn(hxlTag=tag))\n cols.append(HXLColumn(hxlTag='#x_count_num'))\... | <|body_start_0|>
self.source = source
self.count_tags = tags
self.aggregate_tag = aggregate_tag
self.saved_columns = None
self.aggregate_iter = None
<|end_body_0|>
<|body_start_1|>
if self.saved_columns is None:
cols = []
for tag in self.count_tag... | Composable filter class to aggregate rows in a HXL dataset. This is the class supporting the hxlcount command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single-threaded processing pipeline. WARNING: thi... | HXLCountFilter | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HXLCountFilter:
"""Composable filter class to aggregate rows in a HXL dataset. This is the class supporting the hxlcount command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single-... | stack_v2_sparse_classes_36k_train_015173 | 6,532 | permissive | [
{
"docstring": "Constructor @param source the HXL data source @param tags a list of HXL tags that form a unique key together (what combinations are you counting?) @param aggregate_tag an optional numeric tag for calculating aggregate values.",
"name": "__init__",
"signature": "def __init__(self, source,... | 4 | stack_v2_sparse_classes_30k_train_019224 | Implement the Python class `HXLCountFilter` described below.
Class description:
Composable filter class to aggregate rows in a HXL dataset. This is the class supporting the hxlcount command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another f... | Implement the Python class `HXLCountFilter` described below.
Class description:
Composable filter class to aggregate rows in a HXL dataset. This is the class supporting the hxlcount command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another f... | b0209e75789501d99a2fb2df8a30cf55a383065a | <|skeleton|>
class HXLCountFilter:
"""Composable filter class to aggregate rows in a HXL dataset. This is the class supporting the hxlcount command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HXLCountFilter:
"""Composable filter class to aggregate rows in a HXL dataset. This is the class supporting the hxlcount command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single-threaded proc... | the_stack_v2_python_sparse | hxl/filters/count.py | jayvdb/libhxl-python | train | 0 |
1b209fe72f984ff382d8da3ac02bcd9d6173e0b1 | [
"if isinstance(value, bool):\n return value\nexpr = str(value).lower()\nif 'y' == expr:\n return True\nelif 'n' == expr:\n return False\nelse:\n raise ValueError('Unable to deserialize boolean string: %s' % value)",
"if value in ['Y', 'N', 'y', 'n']:\n return str(value).upper()\nif isinstance(value... | <|body_start_0|>
if isinstance(value, bool):
return value
expr = str(value).lower()
if 'y' == expr:
return True
elif 'n' == expr:
return False
else:
raise ValueError('Unable to deserialize boolean string: %s' % value)
<|end_body_0|>... | YNBool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YNBool:
def deserialize(cls, value):
"""Convert a boolean string to a boolean"""
<|body_0|>
def serialize(cls, value):
"""Convert a boolean to a boolean string"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if isinstance(value, bool):
r... | stack_v2_sparse_classes_36k_train_015174 | 3,502 | permissive | [
{
"docstring": "Convert a boolean string to a boolean",
"name": "deserialize",
"signature": "def deserialize(cls, value)"
},
{
"docstring": "Convert a boolean to a boolean string",
"name": "serialize",
"signature": "def serialize(cls, value)"
}
] | 2 | null | Implement the Python class `YNBool` described below.
Class description:
Implement the YNBool class.
Method signatures and docstrings:
- def deserialize(cls, value): Convert a boolean string to a boolean
- def serialize(cls, value): Convert a boolean to a boolean string | Implement the Python class `YNBool` described below.
Class description:
Implement the YNBool class.
Method signatures and docstrings:
- def deserialize(cls, value): Convert a boolean string to a boolean
- def serialize(cls, value): Convert a boolean to a boolean string
<|skeleton|>
class YNBool:
def deserialize... | 60d75438d71ffb7998f5dc407ffa890cc98d3171 | <|skeleton|>
class YNBool:
def deserialize(cls, value):
"""Convert a boolean string to a boolean"""
<|body_0|>
def serialize(cls, value):
"""Convert a boolean to a boolean string"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YNBool:
def deserialize(cls, value):
"""Convert a boolean string to a boolean"""
if isinstance(value, bool):
return value
expr = str(value).lower()
if 'y' == expr:
return True
elif 'n' == expr:
return False
else:
r... | the_stack_v2_python_sparse | openstack/format.py | huaweicloudsdk/sdk-python | train | 20 | |
bff0de695c79f52cd3baa541d9dde3d1cded4f47 | [
"n = len(xint)\nself.n = n\nself.xint = xint\nself.yint = yint\nw = np.ones(n)\nself.C = (np.max(xint) - np.min(xint)) / 4\nshuffle = np.random.permutation(n - 1)\nfor j in range(n):\n temp = (xint[j] - np.delete(xint, j)) / self.C\n temp = temp[shuffle]\n w[j] /= np.product(temp)\nself.w = w",
"v = lamb... | <|body_start_0|>
n = len(xint)
self.n = n
self.xint = xint
self.yint = yint
w = np.ones(n)
self.C = (np.max(xint) - np.min(xint)) / 4
shuffle = np.random.permutation(n - 1)
for j in range(n):
temp = (xint[j] - np.delete(xint, j)) / self.C
... | Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points. | Barycentric | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init_... | stack_v2_sparse_classes_36k_train_015175 | 7,883 | no_license | [
{
"docstring": "Calculate the Barycentric weights using initial interpolating points. Parameters: xint ((n,) ndarray): x values of interpolating points. yint ((n,) ndarray): y values of interpolating points.",
"name": "__init__",
"signature": "def __init__(self, xint, yint)"
},
{
"docstring": "U... | 3 | stack_v2_sparse_classes_30k_train_019639 | Implement the Python class `Barycentric` described below.
Class description:
Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of in... | Implement the Python class `Barycentric` described below.
Class description:
Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of in... | ae7d5732d1c6c3b468229b0b75f378ee5028fcbc | <|skeleton|>
class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init__(self, xint,... | the_stack_v2_python_sparse | PolynomialInterpolation/polynomial_interpolation.py | mingyanz130/Algorithms_Approximation_Optimization | train | 0 |
68280b53e28cbcb03b6b46c17e31ac384ff780db | [
"super(xpmem, self).__init__(**kwargs)\nself.__branch = kwargs.pop('branch', 'master')\nself.__configure_opts = kwargs.pop('configure_opts', ['--disable-kernel-module'])\nself.__ospackages = kwargs.pop('ospackages', ['autoconf', 'automake', 'ca-certificates', 'file', 'git', 'libtool', 'make'])\nself.__prefix = kwar... | <|body_start_0|>
super(xpmem, self).__init__(**kwargs)
self.__branch = kwargs.pop('branch', 'master')
self.__configure_opts = kwargs.pop('configure_opts', ['--disable-kernel-module'])
self.__ospackages = kwargs.pop('ospackages', ['autoconf', 'automake', 'ca-certificates', 'file', 'git', ... | The `xpmem` building block builds and installs the user space library from the [XPMEM](https://github.com/hjelmn/xpmem) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. branch: The branch of XPMEM to use. The default value is `master`. configure_op... | xpmem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class xpmem:
"""The `xpmem` building block builds and installs the user space library from the [XPMEM](https://github.com/hjelmn/xpmem) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. branch: The branch of XPMEM to use. The defaul... | stack_v2_sparse_classes_36k_train_015176 | 5,966 | permissive | [
{
"docstring": "Initialize building block",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Generate the set of instructions to install the runtime specific components from a build in a previous stage. # Examples ```python x = xpmem(...) Stage0 += x Stage1 += x... | 2 | null | Implement the Python class `xpmem` described below.
Class description:
The `xpmem` building block builds and installs the user space library from the [XPMEM](https://github.com/hjelmn/xpmem) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. branch:... | Implement the Python class `xpmem` described below.
Class description:
The `xpmem` building block builds and installs the user space library from the [XPMEM](https://github.com/hjelmn/xpmem) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. branch:... | 60fd2a51c171258a6b3f93c2523101cb7018ba1b | <|skeleton|>
class xpmem:
"""The `xpmem` building block builds and installs the user space library from the [XPMEM](https://github.com/hjelmn/xpmem) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. branch: The branch of XPMEM to use. The defaul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class xpmem:
"""The `xpmem` building block builds and installs the user space library from the [XPMEM](https://github.com/hjelmn/xpmem) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. branch: The branch of XPMEM to use. The default value is `m... | the_stack_v2_python_sparse | hpccm/building_blocks/xpmem.py | NVIDIA/hpc-container-maker | train | 419 |
aef305f631e46db5d8fbd4806647767151e789d7 | [
"if model._meta.app_label == 'syncwerk_server_models':\n return 'syncwerk-server'\nreturn None",
"if model._meta.app_label == 'syncwerk_server_models':\n return 'syncwerk-server'\nreturn None",
"if obj1._meta.app_label == 'syncwerk_server_models' or obj2._meta.app_label == 'syncwerk_server_models':\n r... | <|body_start_0|>
if model._meta.app_label == 'syncwerk_server_models':
return 'syncwerk-server'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'syncwerk_server_models':
return 'syncwerk-server'
return None
<|end_body_1|>
<|body_start_2|>... | A router to control all database operations on models related to syncwerk-server | SyncwerkServerModelsRouter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncwerkServerModelsRouter:
"""A router to control all database operations on models related to syncwerk-server"""
def db_for_read(self, model, **hints):
"""Point all operations which has app_label='syncwerk_server_models' models to 'syncwerk-server'"""
<|body_0|>
def db... | stack_v2_sparse_classes_36k_train_015177 | 1,598 | permissive | [
{
"docstring": "Point all operations which has app_label='syncwerk_server_models' models to 'syncwerk-server'",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all operations on syncwerk_server_models models to 'syncwerk-server'",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_020035 | Implement the Python class `SyncwerkServerModelsRouter` described below.
Class description:
A router to control all database operations on models related to syncwerk-server
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations which has app_label='syncwerk_server_models' mode... | Implement the Python class `SyncwerkServerModelsRouter` described below.
Class description:
A router to control all database operations on models related to syncwerk-server
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations which has app_label='syncwerk_server_models' mode... | 13b3ed26a04248211ef91ca70dccc617be27a3c3 | <|skeleton|>
class SyncwerkServerModelsRouter:
"""A router to control all database operations on models related to syncwerk-server"""
def db_for_read(self, model, **hints):
"""Point all operations which has app_label='syncwerk_server_models' models to 'syncwerk-server'"""
<|body_0|>
def db... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SyncwerkServerModelsRouter:
"""A router to control all database operations on models related to syncwerk-server"""
def db_for_read(self, model, **hints):
"""Point all operations which has app_label='syncwerk_server_models' models to 'syncwerk-server'"""
if model._meta.app_label == 'syncwe... | the_stack_v2_python_sparse | fhs/usr/share/python/syncwerk/restapi/restapi/syncwerk_server_models/routers.py | syncwerk/syncwerk-server-restapi | train | 0 |
f014960277f5d513b01c4ebc257dc23dd7971b96 | [
"model_name = self.kwargs['name']\nlearning_model = get_learning_model(model_name)\nif not learning_model:\n raise Http404('Learning model `%(name)s` is not registered' % {'name': model_name})\nreturn learning_model",
"context = super(LearningModelMixin, self).get_context_data(**kwargs)\ncontext['learning_mode... | <|body_start_0|>
model_name = self.kwargs['name']
learning_model = get_learning_model(model_name)
if not learning_model:
raise Http404('Learning model `%(name)s` is not registered' % {'name': model_name})
return learning_model
<|end_body_0|>
<|body_start_1|>
context ... | Mixin for LearningModel base | LearningModelMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningModelMixin:
"""Mixin for LearningModel base"""
def get_learning_model(self):
"""Returns the learning model corresponding to the name in the URL pattern."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Adds LearningModel data in the context"""
... | stack_v2_sparse_classes_36k_train_015178 | 4,524 | no_license | [
{
"docstring": "Returns the learning model corresponding to the name in the URL pattern.",
"name": "get_learning_model",
"signature": "def get_learning_model(self)"
},
{
"docstring": "Adds LearningModel data in the context",
"name": "get_context_data",
"signature": "def get_context_data(... | 3 | stack_v2_sparse_classes_30k_train_000914 | Implement the Python class `LearningModelMixin` described below.
Class description:
Mixin for LearningModel base
Method signatures and docstrings:
- def get_learning_model(self): Returns the learning model corresponding to the name in the URL pattern.
- def get_context_data(self, **kwargs): Adds LearningModel data in... | Implement the Python class `LearningModelMixin` described below.
Class description:
Mixin for LearningModel base
Method signatures and docstrings:
- def get_learning_model(self): Returns the learning model corresponding to the name in the URL pattern.
- def get_context_data(self, **kwargs): Adds LearningModel data in... | e7713cf11e5af23e28dadd9aff226ea7c14de36b | <|skeleton|>
class LearningModelMixin:
"""Mixin for LearningModel base"""
def get_learning_model(self):
"""Returns the learning model corresponding to the name in the URL pattern."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Adds LearningModel data in the context"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearningModelMixin:
"""Mixin for LearningModel base"""
def get_learning_model(self):
"""Returns the learning model corresponding to the name in the URL pattern."""
model_name = self.kwargs['name']
learning_model = get_learning_model(model_name)
if not learning_model:
... | the_stack_v2_python_sparse | django_learnit/views/base.py | florianpaquet/django-learnit | train | 0 |
3917395df17d219e2444abb475fe5293b8a3a7f7 | [
"if not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nres = []\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_015179 | 2,208 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_009822 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | b365ba85036e51f7a9e018767914ef22314a6780 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
i... | the_stack_v2_python_sparse | 剑指offer/剑指 Offer 37. 序列化二叉树.py | f1amingo/leetcode-python | train | 1 | |
934dcba20fce370275cc59c40317f951bad92714 | [
"words = line.split('\\t')\nif words == ['\\n']:\n raise BadTweetException\nself.sid = words[0]\nself.uid = words[1]\nself.label = words[2]\nself.sent = words[3].strip('\\n')\nif self.sent == 'Not Available':\n raise BadTweetException('text not provided')\nif self.label == 'objective-OR-neutral':\n self.la... | <|body_start_0|>
words = line.split('\t')
if words == ['\n']:
raise BadTweetException
self.sid = words[0]
self.uid = words[1]
self.label = words[2]
self.sent = words[3].strip('\n')
if self.sent == 'Not Available':
raise BadTweetException('t... | Tweet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tweet:
def __init__(self, line):
"""Tweet::Constructor Purpose: Parse a line of a SemEval file & store the representation. File format: SID UID label sentence ex. 111344599699693568 338069340 neutral michael jackson - hollywood tonight http://t.co/s6n3HJj"""
<|body_0|>
def _... | stack_v2_sparse_classes_36k_train_015180 | 1,781 | no_license | [
{
"docstring": "Tweet::Constructor Purpose: Parse a line of a SemEval file & store the representation. File format: SID UID label sentence ex. 111344599699693568 338069340 neutral michael jackson - hollywood tonight http://t.co/s6n3HJj",
"name": "__init__",
"signature": "def __init__(self, line)"
},
... | 2 | null | Implement the Python class `Tweet` described below.
Class description:
Implement the Tweet class.
Method signatures and docstrings:
- def __init__(self, line): Tweet::Constructor Purpose: Parse a line of a SemEval file & store the representation. File format: SID UID label sentence ex. 111344599699693568 338069340 ne... | Implement the Python class `Tweet` described below.
Class description:
Implement the Tweet class.
Method signatures and docstrings:
- def __init__(self, line): Tweet::Constructor Purpose: Parse a line of a SemEval file & store the representation. File format: SID UID label sentence ex. 111344599699693568 338069340 ne... | ce3bb02e4f8b2883a9390b6ff9994d76a2281daf | <|skeleton|>
class Tweet:
def __init__(self, line):
"""Tweet::Constructor Purpose: Parse a line of a SemEval file & store the representation. File format: SID UID label sentence ex. 111344599699693568 338069340 neutral michael jackson - hollywood tonight http://t.co/s6n3HJj"""
<|body_0|>
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tweet:
def __init__(self, line):
"""Tweet::Constructor Purpose: Parse a line of a SemEval file & store the representation. File format: SID UID label sentence ex. 111344599699693568 338069340 neutral michael jackson - hollywood tonight http://t.co/s6n3HJj"""
words = line.split('\t')
if... | the_stack_v2_python_sparse | TaskB/code/tweet.py | GeneralZh/Twitter-Sentiment-SemEval2015-UML-classifiers | train | 0 | |
32b1f1e35a1ebb6bf6cc9caba8c37ee4db8c757b | [
"self.filepath = filepath\nself.interval = interval\nself.verbose = verbose\nself.kmodel = kmodel\nself.total_steps = 0",
"self.total_steps += 1\nif self.total_steps % self.interval != 0:\n return\nfilepath = self.filepath.format(step=self.total_steps, **logs)\nif self.verbose > 0:\n print('\\nStep {}: savi... | <|body_start_0|>
self.filepath = filepath
self.interval = interval
self.verbose = verbose
self.kmodel = kmodel
self.total_steps = 0
<|end_body_0|>
<|body_start_1|>
self.total_steps += 1
if self.total_steps % self.interval != 0:
return
filepath... | ModelIntervalCheck | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelIntervalCheck:
def __init__(self, filepath, interval, verbose=0, kmodel=None):
"""save every x steps"""
<|body_0|>
def on_step_end(self, step, logs={}):
"""Save weights at interval steps during training"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015181 | 2,749 | no_license | [
{
"docstring": "save every x steps",
"name": "__init__",
"signature": "def __init__(self, filepath, interval, verbose=0, kmodel=None)"
},
{
"docstring": "Save weights at interval steps during training",
"name": "on_step_end",
"signature": "def on_step_end(self, step, logs={})"
}
] | 2 | stack_v2_sparse_classes_30k_train_005368 | Implement the Python class `ModelIntervalCheck` described below.
Class description:
Implement the ModelIntervalCheck class.
Method signatures and docstrings:
- def __init__(self, filepath, interval, verbose=0, kmodel=None): save every x steps
- def on_step_end(self, step, logs={}): Save weights at interval steps duri... | Implement the Python class `ModelIntervalCheck` described below.
Class description:
Implement the ModelIntervalCheck class.
Method signatures and docstrings:
- def __init__(self, filepath, interval, verbose=0, kmodel=None): save every x steps
- def on_step_end(self, step, logs={}): Save weights at interval steps duri... | a49eb348ff994f35b0efbbd5ac3ac8ae8ccb57d2 | <|skeleton|>
class ModelIntervalCheck:
def __init__(self, filepath, interval, verbose=0, kmodel=None):
"""save every x steps"""
<|body_0|>
def on_step_end(self, step, logs={}):
"""Save weights at interval steps during training"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelIntervalCheck:
def __init__(self, filepath, interval, verbose=0, kmodel=None):
"""save every x steps"""
self.filepath = filepath
self.interval = interval
self.verbose = verbose
self.kmodel = kmodel
self.total_steps = 0
def on_step_end(self, step, logs=... | the_stack_v2_python_sparse | reinforcement_learning/0x01-deep_q_learning/train.py | salmenz/holbertonschool-machine_learning | train | 4 | |
33354bceda75692810332b0fcdb42bde41e942c5 | [
"ser = []\n\ndef preOrder(root):\n if not root:\n ser.append('#')\n else:\n ser.append(str(root.val))\n preOrder(root.left)\n preOrder(root.right)\npreOrder(root)\nreturn ' '.join(ser)",
"vals = collections.deque([x for x in data.split()])\n\ndef build():\n if vals:\n v... | <|body_start_0|>
ser = []
def preOrder(root):
if not root:
ser.append('#')
else:
ser.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
preOrder(root)
return ' '.join(ser)
<|end_body_0|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
def serialize(self, r... | stack_v2_sparse_classes_36k_train_015182 | 2,959 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 4 | stack_v2_sparse_classes_30k_train_004258 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | a39280ab6bbbf3b688a024a71ef952be5010d98e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
def serialize(self, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
ser = []
def preOrder(root):
if not root:
ser.append('#')
else:
ser.append(str(root.val))
preOrder(root.l... | the_stack_v2_python_sparse | 297_Serialize_and_Deserialize_Binary_Tree.py | MarcelArthur/leetcode_collection | train | 0 | |
7a88f24954bb02389d332885ac483236a1f6a796 | [
"if user not in self._user_enrollments:\n self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)\nreturn self._user_enrollments[user]",
"field_dictionary = super().field_dictionary(**kwargs)\nif not kwargs.get('user'):\n field_dictionary['course'] = []\nelif not kwargs.get('course_id'):\... | <|body_start_0|>
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
return self._user_enrollments[user]
<|end_body_0|>
<|body_start_1|>
field_dictionary = super().field_dictionary(**kwargs)
if not kwargs.get('use... | SearchFilterGenerator for LMS Search | LmsSearchFilterGenerator | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
<|body_0|>
def field_dictionary(self, **kwargs):
"""add course if provided otherwise add courses in wh... | stack_v2_sparse_classes_36k_train_015183 | 2,467 | permissive | [
{
"docstring": "Return the specified user's course enrollments",
"name": "_enrollments_for_user",
"signature": "def _enrollments_for_user(self, user)"
},
{
"docstring": "add course if provided otherwise add courses in which the user is enrolled in",
"name": "field_dictionary",
"signature... | 3 | stack_v2_sparse_classes_30k_test_000473 | Implement the Python class `LmsSearchFilterGenerator` described below.
Class description:
SearchFilterGenerator for LMS Search
Method signatures and docstrings:
- def _enrollments_for_user(self, user): Return the specified user's course enrollments
- def field_dictionary(self, **kwargs): add course if provided otherw... | Implement the Python class `LmsSearchFilterGenerator` described below.
Class description:
SearchFilterGenerator for LMS Search
Method signatures and docstrings:
- def _enrollments_for_user(self, user): Return the specified user's course enrollments
- def field_dictionary(self, **kwargs): add course if provided otherw... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
<|body_0|>
def field_dictionary(self, **kwargs):
"""add course if provided otherwise add courses in wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/lib/courseware_search/lms_filter_generator.py | luque/better-ways-of-thinking-about-software | train | 3 |
5ea9070f2dac811101b4f40f500a2af64490df92 | [
"if getattr(self, 'token') is not None:\n return self.token.refresh()\nelif not self.can_refresh:\n return getattr(self, '_token', None)\nelse:\n raise Exception('Oauth client is not configured to refresh tokens')",
"resp = {}\nresp['access_token'] = getattr(self, '_token', None)\nresp['refresh_token'] =... | <|body_start_0|>
if getattr(self, 'token') is not None:
return self.token.refresh()
elif not self.can_refresh:
return getattr(self, '_token', None)
else:
raise Exception('Oauth client is not configured to refresh tokens')
<|end_body_0|>
<|body_start_1|>
... | TokenCommands | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenCommands:
def refresh(self):
"""If possible, attempt to refresh the Oauth token This is the function that should be used to regenerate an Oauth token as it can deal with cases where no refresh capability is configured."""
<|body_0|>
def tokens(self):
"""Return c... | stack_v2_sparse_classes_36k_train_015184 | 889 | permissive | [
{
"docstring": "If possible, attempt to refresh the Oauth token This is the function that should be used to regenerate an Oauth token as it can deal with cases where no refresh capability is configured.",
"name": "refresh",
"signature": "def refresh(self)"
},
{
"docstring": "Return current acces... | 2 | null | Implement the Python class `TokenCommands` described below.
Class description:
Implement the TokenCommands class.
Method signatures and docstrings:
- def refresh(self): If possible, attempt to refresh the Oauth token This is the function that should be used to regenerate an Oauth token as it can deal with cases where... | Implement the Python class `TokenCommands` described below.
Class description:
Implement the TokenCommands class.
Method signatures and docstrings:
- def refresh(self): If possible, attempt to refresh the Oauth token This is the function that should be used to regenerate an Oauth token as it can deal with cases where... | 7f2d5f20b0918a5ca1a047dcee7613c1847342b6 | <|skeleton|>
class TokenCommands:
def refresh(self):
"""If possible, attempt to refresh the Oauth token This is the function that should be used to regenerate an Oauth token as it can deal with cases where no refresh capability is configured."""
<|body_0|>
def tokens(self):
"""Return c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenCommands:
def refresh(self):
"""If possible, attempt to refresh the Oauth token This is the function that should be used to regenerate an Oauth token as it can deal with cases where no refresh capability is configured."""
if getattr(self, 'token') is not None:
return self.toke... | the_stack_v2_python_sparse | agavepy/interactive/tokens.py | TACC/agavepy | train | 16 | |
c63023019111cd51fc6ecaf5602af33e842a6462 | [
"m = len(prices)\nbuy = float('inf')\nres = 0\nfor i in range(m):\n if prices[i] > buy:\n res = max(res, prices[i] - buy)\n else:\n buy = prices[i]\nreturn res",
"stack = []\nres = 0\nfor i in prices:\n flag = 0\n while stack and stack[-1] > i:\n if flag == 0:\n res = m... | <|body_start_0|>
m = len(prices)
buy = float('inf')
res = 0
for i in range(m):
if prices[i] > buy:
res = max(res, prices[i] - buy)
else:
buy = prices[i]
return res
<|end_body_0|>
<|body_start_1|>
stack = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit1(self, prices):
"""[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化"""
<|body_0|>
def maxProfit(self, prices):
"""单调栈: [7,1_最短回文串.py,5,3,6,4] stack = [1_最短回文串.py,2,3] #单调递减栈 出... | stack_v2_sparse_classes_36k_train_015185 | 1,225 | no_license | [
{
"docstring": "[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices)"
},
{
"docstring": "单调栈: [7,1_最短回文串.py,5,3,6,4] stack = [1_最短回文串.py,2,3] #单调递减栈 出栈产生利润",
"na... | 2 | stack_v2_sparse_classes_30k_train_019635 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices): [7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化
- def maxProfit(self, prices): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices): [7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化
- def maxProfit(self, prices): ... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def maxProfit1(self, prices):
"""[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化"""
<|body_0|>
def maxProfit(self, prices):
"""单调栈: [7,1_最短回文串.py,5,3,6,4] stack = [1_最短回文串.py,2,3] #单调递减栈 出... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit1(self, prices):
"""[7,1_最短回文串.py,5,3,6,4] dp[i] = prices[i] - buy if price[i]>buy 0, buy = prices[i] 边界 buy = 无穷大 res = max(dp) 时间 空间优化"""
m = len(prices)
buy = float('inf')
res = 0
for i in range(m):
if prices[i] > buy:
... | the_stack_v2_python_sparse | 3_Offer2nd-HandWriting/6_DP/8_股票的最大利润.py | fzingithub/SwordRefers2Offer | train | 1 | |
50f5630ba25db9979dc108bedbc12a3d54e5282d | [
"super(PixelLoss, self).__init__()\nself.num_classes = num_classes\nself.loss_weights = loss_weights\nself.hnm = hnm",
"eps = 1e-06\ny_pred = y_pred.permute(0, 2, 3, 1).contiguous().view(-1, self.num_classes)\ny_pred += eps\ny = y.view(-1)\nif self.hnm is not None:\n y, y_pred = self.hard_negative_mining(y, y_... | <|body_start_0|>
super(PixelLoss, self).__init__()
self.num_classes = num_classes
self.loss_weights = loss_weights
self.hnm = hnm
<|end_body_0|>
<|body_start_1|>
eps = 1e-06
y_pred = y_pred.permute(0, 2, 3, 1).contiguous().view(-1, self.num_classes)
y_pred += eps... | PixelLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelLoss:
def __init__(self, num_classes=3, loss_weights=None, hnm=None):
"""hnm : Hard negative mining factor None => no hard negative mining int => factor of hrd negative mining"""
<|body_0|>
def forward(self, y_pred, y):
"""y_pred : batch, n_classes, h, w y : bat... | stack_v2_sparse_classes_36k_train_015186 | 1,849 | no_license | [
{
"docstring": "hnm : Hard negative mining factor None => no hard negative mining int => factor of hrd negative mining",
"name": "__init__",
"signature": "def __init__(self, num_classes=3, loss_weights=None, hnm=None)"
},
{
"docstring": "y_pred : batch, n_classes, h, w y : batch, 1, h, w",
"... | 3 | stack_v2_sparse_classes_30k_train_002060 | Implement the Python class `PixelLoss` described below.
Class description:
Implement the PixelLoss class.
Method signatures and docstrings:
- def __init__(self, num_classes=3, loss_weights=None, hnm=None): hnm : Hard negative mining factor None => no hard negative mining int => factor of hrd negative mining
- def for... | Implement the Python class `PixelLoss` described below.
Class description:
Implement the PixelLoss class.
Method signatures and docstrings:
- def __init__(self, num_classes=3, loss_weights=None, hnm=None): hnm : Hard negative mining factor None => no hard negative mining int => factor of hrd negative mining
- def for... | 35e4d872f7d1c3d09799edcdbd7c1aaccd892b0a | <|skeleton|>
class PixelLoss:
def __init__(self, num_classes=3, loss_weights=None, hnm=None):
"""hnm : Hard negative mining factor None => no hard negative mining int => factor of hrd negative mining"""
<|body_0|>
def forward(self, y_pred, y):
"""y_pred : batch, n_classes, h, w y : bat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PixelLoss:
def __init__(self, num_classes=3, loss_weights=None, hnm=None):
"""hnm : Hard negative mining factor None => no hard negative mining int => factor of hrd negative mining"""
super(PixelLoss, self).__init__()
self.num_classes = num_classes
self.loss_weights = loss_weig... | the_stack_v2_python_sparse | models/utils/loss.py | amritsaha607/Aerial-Image-Segmentation | train | 1 | |
7187fad5ca8f75aec450e7b895f8fd8f938ac537 | [
"decl = fortran.arguments()\nself.assertEqual(decl['FORTRAN']['help'], 'The default Fortran compiler for all versions of Fortran')\nself.assertEqual(decl['FORTRAN']['metavar'], 'PROG')\nself.assertEqual(decl['SHFORTRAN']['help'], 'The default Fortran compiler used for generating shared-library objects')\nself.asser... | <|body_start_0|>
decl = fortran.arguments()
self.assertEqual(decl['FORTRAN']['help'], 'The default Fortran compiler for all versions of Fortran')
self.assertEqual(decl['FORTRAN']['metavar'], 'PROG')
self.assertEqual(decl['SHFORTRAN']['help'], 'The default Fortran compiler used for genera... | Test SConsArguments.fortran | Test_fortran | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_fortran:
"""Test SConsArguments.fortran"""
def test_arguments1(self):
"""Test SConsArguments.fortran.arguments()"""
<|body_0|>
def test_arguments__groups_1(self):
"""Test SConsArguments.fortran.arguments() with groups (exclude, include)"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_015187 | 4,876 | permissive | [
{
"docstring": "Test SConsArguments.fortran.arguments()",
"name": "test_arguments1",
"signature": "def test_arguments1(self)"
},
{
"docstring": "Test SConsArguments.fortran.arguments() with groups (exclude, include)",
"name": "test_arguments__groups_1",
"signature": "def test_arguments__... | 3 | stack_v2_sparse_classes_30k_train_010610 | Implement the Python class `Test_fortran` described below.
Class description:
Test SConsArguments.fortran
Method signatures and docstrings:
- def test_arguments1(self): Test SConsArguments.fortran.arguments()
- def test_arguments__groups_1(self): Test SConsArguments.fortran.arguments() with groups (exclude, include)
... | Implement the Python class `Test_fortran` described below.
Class description:
Test SConsArguments.fortran
Method signatures and docstrings:
- def test_arguments1(self): Test SConsArguments.fortran.arguments()
- def test_arguments__groups_1(self): Test SConsArguments.fortran.arguments() with groups (exclude, include)
... | f4b783fc79fe3fc16e8d0f58308099a67752d299 | <|skeleton|>
class Test_fortran:
"""Test SConsArguments.fortran"""
def test_arguments1(self):
"""Test SConsArguments.fortran.arguments()"""
<|body_0|>
def test_arguments__groups_1(self):
"""Test SConsArguments.fortran.arguments() with groups (exclude, include)"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_fortran:
"""Test SConsArguments.fortran"""
def test_arguments1(self):
"""Test SConsArguments.fortran.arguments()"""
decl = fortran.arguments()
self.assertEqual(decl['FORTRAN']['help'], 'The default Fortran compiler for all versions of Fortran')
self.assertEqual(decl['... | the_stack_v2_python_sparse | unit_tests/SConsArgumentsT/fortranTests.py | mcqueen256/scons-arguments | train | 0 |
0ef7e2699d243e144e2dc5cab8cd2bec951afbbf | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')\nself.lexicon = Lexicon()",
"if tnode.gram_tense != 'post' or (tnode.gram_aspect != 'proc' and tnode.gram_deontmod == 'decl'):\n return\naconj = tnode.get_deref_attr('wild/conjugated')\nif ... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
self.lexicon = Lexicon()
<|end_body_0|>
<|body_start_1|>
if tnode.gram_tense != 'post' or (tnode.gram_aspect != 'proc' and tnode.gram_deontmod ... | Add compound future auxiliary 'bude'. Arguments: language: the language of the target tree selector: the selector of the target tree | AddAuxVerbCompoundFuture | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddAuxVerbCompoundFuture:
"""Add compound future auxiliary 'bude'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def pr... | stack_v2_sparse_classes_36k_train_015188 | 1,872 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add compound future auxiliary to a node, where appropriate.",
"name": "process_tnode",
"signature": "def process_tnode(self, tnode)"
... | 2 | null | Implement the Python class `AddAuxVerbCompoundFuture` described below.
Class description:
Add compound future auxiliary 'bude'. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just check... | Implement the Python class `AddAuxVerbCompoundFuture` described below.
Class description:
Add compound future auxiliary 'bude'. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario, args): Constructor, just check... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddAuxVerbCompoundFuture:
"""Add compound future auxiliary 'bude'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
<|body_0|>
def pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddAuxVerbCompoundFuture:
"""Add compound future auxiliary 'bude'. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Block.__init__(self, scenario, args... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addauxverbcompoundfuture.py | oplatek/alex | train | 0 |
5656abc14d6cc707f4afa029349d5942ad3517f9 | [
"total = 0\nstack = []\nnode = root\nwhile stack or node:\n while node:\n stack.append(node)\n node = node.right\n node = stack.pop()\n total += node.val\n node.val = total\n node = node.left\nreturn root",
"node = root\ntotal = 0\nwhile node:\n if node.right is None:\n tota... | <|body_start_0|>
total = 0
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.right
node = stack.pop()
total += node.val
node.val = total
node = node.left
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
"""inorder traversal reversed"""
<|body_0|>
def bstToGst(self, root: TreeNode) -> TreeNode:
"""morris"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
total = 0
stack = []
node... | stack_v2_sparse_classes_36k_train_015189 | 2,223 | no_license | [
{
"docstring": "inorder traversal reversed",
"name": "bstToGst",
"signature": "def bstToGst(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "morris",
"name": "bstToGst",
"signature": "def bstToGst(self, root: TreeNode) -> TreeNode"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bstToGst(self, root: TreeNode) -> TreeNode: inorder traversal reversed
- def bstToGst(self, root: TreeNode) -> TreeNode: morris | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bstToGst(self, root: TreeNode) -> TreeNode: inorder traversal reversed
- def bstToGst(self, root: TreeNode) -> TreeNode: morris
<|skeleton|>
class Solution:
def bstToGs... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
"""inorder traversal reversed"""
<|body_0|>
def bstToGst(self, root: TreeNode) -> TreeNode:
"""morris"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
"""inorder traversal reversed"""
total = 0
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.right
node = stack.pop()
... | the_stack_v2_python_sparse | Leetcode 1038. Binary Search Tree to Greater Sum Tree.py | Chaoran-sjsu/leetcode | train | 0 | |
da5aa7b529e4bc99335ca50dc9373350f8d0b0d3 | [
"if get_setting('eor.debug-auth'):\n log.info('permits: context %s, principals %s, permission %s' % (context, principals, permission))\nacl = '<No ACL found on any object in resource lineage>'\nfor location in lineage(context):\n try:\n acl = location.__acl__\n except AttributeError:\n contin... | <|body_start_0|>
if get_setting('eor.debug-auth'):
log.info('permits: context %s, principals %s, permission %s' % (context, principals, permission))
acl = '<No ACL found on any object in resource lineage>'
for location in lineage(context):
try:
acl = locat... | An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. If the context is part of a :term:`lineage`, the context's parents are consulted for ACL information too. The following is true abou... | ACLAuthorizationPolicy2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACLAuthorizationPolicy2:
"""An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. If the context is part of a :term:`lineage`, the context's parents are consulted ... | stack_v2_sparse_classes_36k_train_015190 | 9,445 | no_license | [
{
"docstring": "Return an instance of :class:`pyramid.security.ACLAllowed` instance if the policy permits access, return an instance of :class:`pyramid.security.ACLDenied` if not.",
"name": "permits",
"signature": "def permits(self, context, principals, permission)"
},
{
"docstring": "Return the... | 2 | stack_v2_sparse_classes_30k_train_004072 | Implement the Python class `ACLAuthorizationPolicy2` described below.
Class description:
An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. If the context is part of a :term:`lineage... | Implement the Python class `ACLAuthorizationPolicy2` described below.
Class description:
An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. If the context is part of a :term:`lineage... | 959a049458de74fb9228acba1f074f3fa56f626f | <|skeleton|>
class ACLAuthorizationPolicy2:
"""An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. If the context is part of a :term:`lineage`, the context's parents are consulted ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ACLAuthorizationPolicy2:
"""An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. If the context is part of a :term:`lineage`, the context's parents are consulted for ACL infor... | the_stack_v2_python_sparse | eor/auth/authorization.py | pthorn/Eye-Of-Ra | train | 1 |
b7094885839d34430b25400fa5d96a0e9c221107 | [
"super().setUp()\nself.n_batch = 4\nself.x_dims = 5\nself.z_dims = 2\nself.x = tf.ones([self.n_batch, self.x_dims])\nself.inputs = {'test_data': self.x}\nself.gin_config_kwarg_modules = f\"\\n import ddsp\\n\\n ### Modules\\n ConfigurableDAGLayer.dag = [\\n ('encoder', ['inputs/test_data'], ['z']),\... | <|body_start_0|>
super().setUp()
self.n_batch = 4
self.x_dims = 5
self.z_dims = 2
self.x = tf.ones([self.n_batch, self.x_dims])
self.inputs = {'test_data': self.x}
self.gin_config_kwarg_modules = f"\n import ddsp\n\n ### Modules\n ConfigurableDAGLayer.dag... | DAGLayerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAGLayerTest:
def setUp(self):
"""Create some dummy input data for the chain."""
<|body_0|>
def test_build_layer(self, kwarg_modules):
"""Tests if layer builds properly and produces outputs of correct shape."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015191 | 3,744 | permissive | [
{
"docstring": "Create some dummy input data for the chain.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests if layer builds properly and produces outputs of correct shape.",
"name": "test_build_layer",
"signature": "def test_build_layer(self, kwarg_modules)"
... | 2 | stack_v2_sparse_classes_30k_train_005150 | Implement the Python class `DAGLayerTest` described below.
Class description:
Implement the DAGLayerTest class.
Method signatures and docstrings:
- def setUp(self): Create some dummy input data for the chain.
- def test_build_layer(self, kwarg_modules): Tests if layer builds properly and produces outputs of correct s... | Implement the Python class `DAGLayerTest` described below.
Class description:
Implement the DAGLayerTest class.
Method signatures and docstrings:
- def setUp(self): Create some dummy input data for the chain.
- def test_build_layer(self, kwarg_modules): Tests if layer builds properly and produces outputs of correct s... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class DAGLayerTest:
def setUp(self):
"""Create some dummy input data for the chain."""
<|body_0|>
def test_build_layer(self, kwarg_modules):
"""Tests if layer builds properly and produces outputs of correct shape."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DAGLayerTest:
def setUp(self):
"""Create some dummy input data for the chain."""
super().setUp()
self.n_batch = 4
self.x_dims = 5
self.z_dims = 2
self.x = tf.ones([self.n_batch, self.x_dims])
self.inputs = {'test_data': self.x}
self.gin_config_kw... | the_stack_v2_python_sparse | ddsp/dags_test.py | magenta/ddsp | train | 2,666 | |
988e4ced292537a34dc631d783516c9b410440a0 | [
"task_manager.Builder.__init__(self, output_directory, output_subdirectory)\nself._android_device = android_device\nself._url = url\nself.default_final_tasks = []\nself.original_wpr_task = None\nself.original_wpr_recording_trace_path = None",
"runner = sandwich_runner.SandwichRunner()\nrunner.url = self._url\nrun... | <|body_start_0|>
task_manager.Builder.__init__(self, output_directory, output_subdirectory)
self._android_device = android_device
self._url = url
self.default_final_tasks = []
self.original_wpr_task = None
self.original_wpr_recording_trace_path = None
<|end_body_0|>
<|bo... | A builder for a graph of tasks, each prepares or invokes a SandwichRunner. | SandwichCommonBuilder | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SandwichCommonBuilder:
"""A builder for a graph of tasks, each prepares or invokes a SandwichRunner."""
def __init__(self, android_device, url, output_directory, output_subdirectory):
"""Constructor. Args: android_device: The android DeviceUtils to run sandwich on or None to run it l... | stack_v2_sparse_classes_36k_train_015192 | 5,638 | permissive | [
{
"docstring": "Constructor. Args: android_device: The android DeviceUtils to run sandwich on or None to run it locally. url: URL to benchmark. output_directory: As in task_manager.Builder.__init__ output_subdirectory: As in task_manager.Builder.__init__",
"name": "__init__",
"signature": "def __init__(... | 3 | null | Implement the Python class `SandwichCommonBuilder` described below.
Class description:
A builder for a graph of tasks, each prepares or invokes a SandwichRunner.
Method signatures and docstrings:
- def __init__(self, android_device, url, output_directory, output_subdirectory): Constructor. Args: android_device: The a... | Implement the Python class `SandwichCommonBuilder` described below.
Class description:
A builder for a graph of tasks, each prepares or invokes a SandwichRunner.
Method signatures and docstrings:
- def __init__(self, android_device, url, output_directory, output_subdirectory): Constructor. Args: android_device: The a... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class SandwichCommonBuilder:
"""A builder for a graph of tasks, each prepares or invokes a SandwichRunner."""
def __init__(self, android_device, url, output_directory, output_subdirectory):
"""Constructor. Args: android_device: The android DeviceUtils to run sandwich on or None to run it l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SandwichCommonBuilder:
"""A builder for a graph of tasks, each prepares or invokes a SandwichRunner."""
def __init__(self, android_device, url, output_directory, output_subdirectory):
"""Constructor. Args: android_device: The android DeviceUtils to run sandwich on or None to run it locally. url: ... | the_stack_v2_python_sparse | tools/android/loading/sandwich_utils.py | metux/chromium-suckless | train | 5 |
b38989d148a7bdbe085c2511acd1689c1b1fa96c | [
"if minfo is None:\n minfo = {}\nsuper(ResetPeerStatsMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = True\nself.IsReliable = True\nself.PeerIDList = minfo.get('PeerIDList', [])\nself.MetricList = minfo.get('MetricList', [])",
"result = super(ResetPeerStatsMessage, self).dump()\nr... | <|body_start_0|>
if minfo is None:
minfo = {}
super(ResetPeerStatsMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = True
self.IsReliable = True
self.PeerIDList = minfo.get('PeerIDList', [])
self.MetricList = minfo.get('Metric... | Reset peer stats messages are sent to a peer node to request it to reset statistics about specified peer connections. Attributes: ResetPeerStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages have special delivery priority rules.... | ResetPeerStatsMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPeerStatsMessage:
"""Reset peer stats messages are sent to a peer node to request it to reset statistics about specified peer connections. Attributes: ResetPeerStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. Syst... | stack_v2_sparse_classes_36k_train_015193 | 13,482 | permissive | [
{
"docstring": "Constructor for the ResetPeerStatsMessage class. Args: minfo (dict): Dictionary of values for message fields.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Dumps a dict containing object attributes. Returns: dict: A mapping of object attri... | 2 | stack_v2_sparse_classes_30k_train_017959 | Implement the Python class `ResetPeerStatsMessage` described below.
Class description:
Reset peer stats messages are sent to a peer node to request it to reset statistics about specified peer connections. Attributes: ResetPeerStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whethe... | Implement the Python class `ResetPeerStatsMessage` described below.
Class description:
Reset peer stats messages are sent to a peer node to request it to reset statistics about specified peer connections. Attributes: ResetPeerStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whethe... | 8f4ca1aab54ef420a0db10c8ca822ec8686cd423 | <|skeleton|>
class ResetPeerStatsMessage:
"""Reset peer stats messages are sent to a peer node to request it to reset statistics about specified peer connections. Attributes: ResetPeerStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. Syst... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResetPeerStatsMessage:
"""Reset peer stats messages are sent to a peer node to request it to reset statistics about specified peer connections. Attributes: ResetPeerStatsMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this is a system message. System messages h... | the_stack_v2_python_sparse | validator/gossip/messages/gossip_debug.py | aludvik/sawtooth-core | train | 0 |
5487bc8755b27e84b41617eb19fed388f71b70d9 | [
"super(FloatingIPInfo, self).__init__()\nself.fixed_ip_address = fixed_ip_address\nself.floating_ip_address = floating_ip_address\nself.floating_network_id = floating_network_id\nself.id_ = id_\nself.port_id = port_id\nself.router_id = router_id\nself.status = status\nself.tenant_id = tenant_id",
"json_dict = jso... | <|body_start_0|>
super(FloatingIPInfo, self).__init__()
self.fixed_ip_address = fixed_ip_address
self.floating_ip_address = floating_ip_address
self.floating_network_id = floating_network_id
self.id_ = id_
self.port_id = port_id
self.router_id = router_id
... | FloatingIPInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatingIPInfo:
def __init__(self, fixed_ip_address=None, floating_ip_address=None, id_=None, port_id=None, router_id=None, status=None, floating_network_id=None, tenant_id=None):
"""Floating IP Info constructor :param fixed_ip_address: (string) - IP Address of port :param floating_ip_ad... | stack_v2_sparse_classes_36k_train_015194 | 3,761 | permissive | [
{
"docstring": "Floating IP Info constructor :param fixed_ip_address: (string) - IP Address of port :param floating_ip_address: (string) - Floating IP Address :param id_: (UUID) UUID of floating IP address :param port_id: (UUID) UUID of neutron port :param router_id: (UUID) UUID of router :param status: (string... | 2 | stack_v2_sparse_classes_30k_train_006469 | Implement the Python class `FloatingIPInfo` described below.
Class description:
Implement the FloatingIPInfo class.
Method signatures and docstrings:
- def __init__(self, fixed_ip_address=None, floating_ip_address=None, id_=None, port_id=None, router_id=None, status=None, floating_network_id=None, tenant_id=None): Fl... | Implement the Python class `FloatingIPInfo` described below.
Class description:
Implement the FloatingIPInfo class.
Method signatures and docstrings:
- def __init__(self, fixed_ip_address=None, floating_ip_address=None, id_=None, port_id=None, router_id=None, status=None, floating_network_id=None, tenant_id=None): Fl... | 1a62bf21adfb047829c7b8c79cfee1f55f9ca350 | <|skeleton|>
class FloatingIPInfo:
def __init__(self, fixed_ip_address=None, floating_ip_address=None, id_=None, port_id=None, router_id=None, status=None, floating_network_id=None, tenant_id=None):
"""Floating IP Info constructor :param fixed_ip_address: (string) - IP Address of port :param floating_ip_ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloatingIPInfo:
def __init__(self, fixed_ip_address=None, floating_ip_address=None, id_=None, port_id=None, router_id=None, status=None, floating_network_id=None, tenant_id=None):
"""Floating IP Info constructor :param fixed_ip_address: (string) - IP Address of port :param floating_ip_address: (string... | the_stack_v2_python_sparse | cloudcafe/networking/networks/extensions/floating_ips/models/response.py | sajuptpm/cloudcafe | train | 0 | |
e22bc529b9e26fc88d294a44c3404195a8792069 | [
"self.component = component\nself.description = description\nself.gateway = gateway\nself.id = id\nself.ip = ip\nself.netmask_bits = netmask_bits\nself.netmask_ip_4 = netmask_ip_4\nself.nfs_access = nfs_access\nself.nfs_all_squash = nfs_all_squash\nself.nfs_root_squash = nfs_root_squash\nself.s3_access = s3_access\... | <|body_start_0|>
self.component = component
self.description = description
self.gateway = gateway
self.id = id
self.ip = ip
self.netmask_bits = netmask_bits
self.netmask_ip_4 = netmask_ip_4
self.nfs_access = nfs_access
self.nfs_all_squash = nfs_all... | Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for this subnet. ip (string): ip is subnet IP address giv... | ClusterConfigProto_Subnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterConfigProto_Subnet:
"""Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for ... | stack_v2_sparse_classes_36k_train_015195 | 4,337 | permissive | [
{
"docstring": "Constructor for the ClusterConfigProto_Subnet class",
"name": "__init__",
"signature": "def __init__(self, component=None, description=None, gateway=None, id=None, ip=None, netmask_bits=None, netmask_ip_4=None, nfs_access=None, nfs_all_squash=None, nfs_root_squash=None, s3_access=None, s... | 2 | null | Implement the Python class `ClusterConfigProto_Subnet` described below.
Class description:
Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Ga... | Implement the Python class `ClusterConfigProto_Subnet` described below.
Class description:
Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Ga... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterConfigProto_Subnet:
"""Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterConfigProto_Subnet:
"""Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for this subnet. ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_config_proto_subnet.py | cohesity/management-sdk-python | train | 24 |
309c7815916bb17e0c8e89b50f0e12b7c04b087e | [
"super(InputData, self).__init__(name=name)\nself.type = 'Input data'\nself.reduction = reduction.lower()\nself.reduction_txt = re.sub('_', ' ', self.reduction).upper()\nself.experiment = experiment\nself.frame = frame\nself.representation = experiment['representations'][reduction]\nself.rec = experiment['record']\... | <|body_start_0|>
super(InputData, self).__init__(name=name)
self.type = 'Input data'
self.reduction = reduction.lower()
self.reduction_txt = re.sub('_', ' ', self.reduction).upper()
self.experiment = experiment
self.frame = frame
self.representation = experiment['... | A class for depicting the content of a dataset as a two dimensional scatter plot. | InputData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputData:
"""A class for depicting the content of a dataset as a two dimensional scatter plot."""
def __init__(self, experiment, frame, name: str='Input data', reduction: str='none', show_badge: bool=True) -> None:
"""Constructor of the class. :param experiment: :param frame: :param... | stack_v2_sparse_classes_36k_train_015196 | 8,435 | no_license | [
{
"docstring": "Constructor of the class. :param experiment: :param frame: :param name: The name of what's being shown. :param reduction: :param show_badge:",
"name": "__init__",
"signature": "def __init__(self, experiment, frame, name: str='Input data', reduction: str='none', show_badge: bool=True) -> ... | 4 | stack_v2_sparse_classes_30k_train_009097 | Implement the Python class `InputData` described below.
Class description:
A class for depicting the content of a dataset as a two dimensional scatter plot.
Method signatures and docstrings:
- def __init__(self, experiment, frame, name: str='Input data', reduction: str='none', show_badge: bool=True) -> None: Construc... | Implement the Python class `InputData` described below.
Class description:
A class for depicting the content of a dataset as a two dimensional scatter plot.
Method signatures and docstrings:
- def __init__(self, experiment, frame, name: str='Input data', reduction: str='none', show_badge: bool=True) -> None: Construc... | e61d34314b64c8047f624f47446351deb755e8a3 | <|skeleton|>
class InputData:
"""A class for depicting the content of a dataset as a two dimensional scatter plot."""
def __init__(self, experiment, frame, name: str='Input data', reduction: str='none', show_badge: bool=True) -> None:
"""Constructor of the class. :param experiment: :param frame: :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputData:
"""A class for depicting the content of a dataset as a two dimensional scatter plot."""
def __init__(self, experiment, frame, name: str='Input data', reduction: str='none', show_badge: bool=True) -> None:
"""Constructor of the class. :param experiment: :param frame: :param name: The na... | the_stack_v2_python_sparse | animate/plotting/Depiction.py | RECHE23/Constellation | train | 1 |
62b0b86d1d50faf3faabe59737bd565f04928442 | [
"flag = None\nself.dos = DosCmd()\nresult = self.dos.excute_cmd_result('netstat -ano | findstr ' + str(port_num))\nif len(result) > 0:\n flag = True\nelse:\n flag = False\nreturn flag",
"port_list = []\nif device_list != None:\n while len(port_list) != len(device_list):\n if self.port_is_used(star... | <|body_start_0|>
flag = None
self.dos = DosCmd()
result = self.dos.excute_cmd_result('netstat -ano | findstr ' + str(port_num))
if len(result) > 0:
flag = True
else:
flag = False
return flag
<|end_body_0|>
<|body_start_1|>
port_list = []
... | Port | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Port:
def port_is_used(self, port_num):
"""检测端口是否被占用"""
<|body_0|>
def creat_port_list(self, start_port, device_list):
"""生成可用端口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
flag = None
self.dos = DosCmd()
result = self.dos.excute... | stack_v2_sparse_classes_36k_train_015197 | 960 | no_license | [
{
"docstring": "检测端口是否被占用",
"name": "port_is_used",
"signature": "def port_is_used(self, port_num)"
},
{
"docstring": "生成可用端口",
"name": "creat_port_list",
"signature": "def creat_port_list(self, start_port, device_list)"
}
] | 2 | null | Implement the Python class `Port` described below.
Class description:
Implement the Port class.
Method signatures and docstrings:
- def port_is_used(self, port_num): 检测端口是否被占用
- def creat_port_list(self, start_port, device_list): 生成可用端口 | Implement the Python class `Port` described below.
Class description:
Implement the Port class.
Method signatures and docstrings:
- def port_is_used(self, port_num): 检测端口是否被占用
- def creat_port_list(self, start_port, device_list): 生成可用端口
<|skeleton|>
class Port:
def port_is_used(self, port_num):
"""检测端口是... | 96b02dfafd3e27203d073f80d024110024658f7c | <|skeleton|>
class Port:
def port_is_used(self, port_num):
"""检测端口是否被占用"""
<|body_0|>
def creat_port_list(self, start_port, device_list):
"""生成可用端口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Port:
def port_is_used(self, port_num):
"""检测端口是否被占用"""
flag = None
self.dos = DosCmd()
result = self.dos.excute_cmd_result('netstat -ano | findstr ' + str(port_num))
if len(result) > 0:
flag = True
else:
flag = False
return flag
... | the_stack_v2_python_sparse | python_old/python/appium_project_test/test_run/port.py | wanyingchao/python | train | 1 | |
52d75c527b4bad17d5c2a2957a4a417fb031c775 | [
"if num_objectives not in (2, 3, 4):\n raise UnsupportedError('GMM only currently supports 2 to 4 objectives.')\nself._ref_point = [-0.2338, -0.2211]\nif num_objectives > 2:\n self._ref_point.append(-0.518)\nif num_objectives > 3:\n self._ref_point.append(-0.1866)\nself.num_objectives = num_objectives\nsup... | <|body_start_0|>
if num_objectives not in (2, 3, 4):
raise UnsupportedError('GMM only currently supports 2 to 4 objectives.')
self._ref_point = [-0.2338, -0.2211]
if num_objectives > 2:
self._ref_point.append(-0.518)
if num_objectives > 3:
self._ref_po... | A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details on this multi-objective problem... | GMM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GMM:
"""A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details ... | stack_v2_sparse_classes_36k_train_015198 | 49,438 | permissive | [
{
"docstring": "Args: noise_std: Standard deviation of the observation noise. negate: If True, negate the objectives. num_objectives: The number of objectives.",
"name": "__init__",
"signature": "def __init__(self, noise_std: Optional[float]=None, negate: bool=False, num_objectives: int=2) -> None"
},... | 2 | stack_v2_sparse_classes_30k_train_012332 | Implement the Python class `GMM` described below.
Class description:
A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objecti... | Implement the Python class `GMM` described below.
Class description:
A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objecti... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class GMM:
"""A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GMM:
"""A test problem where each objective is a Gaussian mixture model. This implementation is adapted from the single objective version (proposed by [Frohlich2020]_) at https://github.com/boschresearch/NoisyInputEntropySearch/blob/master/ core/util/objectives.py. See [Daulton2022]_ for details on this multi... | the_stack_v2_python_sparse | botorch/test_functions/multi_objective.py | pytorch/botorch | train | 2,891 |
d3379215200ae34f2b09ae66246ef6279cbe37c9 | [
"if isinstance(token_indexer, dict):\n self.tokenizer = token_indexer['tokens']._tokenizer\nelse:\n self.tokenizer = token_indexer._tokenizer\nsuper().__init__(token_ann_type=token_ann_type, sentence_ann_type=sentence_ann_type, label_key_function=label_key_function, is_multilabel=is_multilabel, token_indexer=... | <|body_start_0|>
if isinstance(token_indexer, dict):
self.tokenizer = token_indexer['tokens']._tokenizer
else:
self.tokenizer = token_indexer._tokenizer
super().__init__(token_ann_type=token_ann_type, sentence_ann_type=sentence_ann_type, label_key_function=label_key_funct... | TransformerDocumentDatasetReader | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDocumentDatasetReader:
def __init__(self, token_indexer: Union[TokenIndexer, Dict[str, TokenIndexer]], token_ann_type: Type[Token]='Annotation.Token.TransformerInputToken', sentence_ann_type: Optional[Type[Annotation]]=None, label_key_function: Optional[Callable[[AnnotatedText], List[... | stack_v2_sparse_classes_36k_train_015199 | 8,098 | permissive | [
{
"docstring": ":param token_indexer: either a TokenIndexer or a dict of TokenIndexer. If a TokenIndexer, it must have the attribute '_tokenizer'. If a dict of TokenIndexer, it must have an entry with the key 'tokens' whose value is a TokenIndexer that has a '_tokenizer' attribute.",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_008811 | Implement the Python class `TransformerDocumentDatasetReader` described below.
Class description:
Implement the TransformerDocumentDatasetReader class.
Method signatures and docstrings:
- def __init__(self, token_indexer: Union[TokenIndexer, Dict[str, TokenIndexer]], token_ann_type: Type[Token]='Annotation.Token.Tran... | Implement the Python class `TransformerDocumentDatasetReader` described below.
Class description:
Implement the TransformerDocumentDatasetReader class.
Method signatures and docstrings:
- def __init__(self, token_indexer: Union[TokenIndexer, Dict[str, TokenIndexer]], token_ann_type: Type[Token]='Annotation.Token.Tran... | 6dcce09a89d22f805e3d88ec00417c69ca97e2d2 | <|skeleton|>
class TransformerDocumentDatasetReader:
def __init__(self, token_indexer: Union[TokenIndexer, Dict[str, TokenIndexer]], token_ann_type: Type[Token]='Annotation.Token.TransformerInputToken', sentence_ann_type: Optional[Type[Annotation]]=None, label_key_function: Optional[Callable[[AnnotatedText], List[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerDocumentDatasetReader:
def __init__(self, token_indexer: Union[TokenIndexer, Dict[str, TokenIndexer]], token_ann_type: Type[Token]='Annotation.Token.TransformerInputToken', sentence_ann_type: Optional[Type[Annotation]]=None, label_key_function: Optional[Callable[[AnnotatedText], List[str]]]=None, i... | the_stack_v2_python_sparse | cancernlp/model/bert_model.py | microsoft/cancernlp | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.