blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3c55a0f73a5023cf7cbd2e3af41f1532948a4068 | [
"if not root:\n return []\nres = [root.val]\nlevel = [root]\nwhile level:\n tem = []\n for l in level:\n if l:\n for child in [l.left, l.right]:\n tem.append(child)\n res.extend((i.val if i else None for i in tem))\n level = tem\nreturn res",
"if not data:\n retu... | <|body_start_0|>
if not root:
return []
res = [root.val]
level = [root]
while level:
tem = []
for l in level:
if l:
for child in [l.left, l.right]:
tem.append(child)
res.extend((i.... | 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_75kplus_train_069300 | 1,788 | 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_018827 | 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:... | 409d7db811d41dbcc7ce8cda82b77eff35585657 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
res = [root.val]
level = [root]
while level:
tem = []
for l in level:
if l:
... | the_stack_v2_python_sparse | Serialize and Deserialize Binary Tree.py | Windsooon/LeetCode | train | 1 | |
48b6bfdf3841c55d1521e60891df82f07dde1335 | [
"n = len(nums)\n\ndef dfs(a, cur):\n nonlocal res\n if a == (1 << n) - 1:\n res.append(cur)\n for i in range(n):\n if a & 1 << i:\n continue\n dfs(a | 1 << i, cur + [nums[i]])\nres = []\ndfs(0, [])\nreturn res",
"n = len(nums)\n\ndef dfs(start):\n nonlocal res\n if s... | <|body_start_0|>
n = len(nums)
def dfs(a, cur):
nonlocal res
if a == (1 << n) - 1:
res.append(cur)
for i in range(n):
if a & 1 << i:
continue
dfs(a | 1 << i, cur + [nums[i]])
res = []
... | [46. 全排列](https://leetcode-cn.com/problems/permutations/) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""[46. 全排列](https://leetcode-cn.com/problems/permutations/)"""
def permute(self, nums: List[int]) -> List[List[int]]:
"""思路:回溯算法,由于没有重复的数字,每次传一个值,用二进制代表哪个位置被选过"""
<|body_0|>
def permute2(self, nums: List[int]) -> List[List[int]]:
"""思路:回溯算法,大佬的交换法,可以随递... | stack_v2_sparse_classes_75kplus_train_069301 | 1,469 | no_license | [
{
"docstring": "思路:回溯算法,由于没有重复的数字,每次传一个值,用二进制代表哪个位置被选过",
"name": "permute",
"signature": "def permute(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "思路:回溯算法,大佬的交换法,可以随递归深度缩小遍历次数",
"name": "permute2",
"signature": "def permute2(self, nums: List[int]) -> List[List[int]]"
}... | 2 | stack_v2_sparse_classes_30k_train_011282 | Implement the Python class `Solution` described below.
Class description:
[46. 全排列](https://leetcode-cn.com/problems/permutations/)
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: 思路:回溯算法,由于没有重复的数字,每次传一个值,用二进制代表哪个位置被选过
- def permute2(self, nums: List[int]) -> List[List[int]]... | Implement the Python class `Solution` described below.
Class description:
[46. 全排列](https://leetcode-cn.com/problems/permutations/)
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: 思路:回溯算法,由于没有重复的数字,每次传一个值,用二进制代表哪个位置被选过
- def permute2(self, nums: List[int]) -> List[List[int]]... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class Solution:
"""[46. 全排列](https://leetcode-cn.com/problems/permutations/)"""
def permute(self, nums: List[int]) -> List[List[int]]:
"""思路:回溯算法,由于没有重复的数字,每次传一个值,用二进制代表哪个位置被选过"""
<|body_0|>
def permute2(self, nums: List[int]) -> List[List[int]]:
"""思路:回溯算法,大佬的交换法,可以随递... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""[46. 全排列](https://leetcode-cn.com/problems/permutations/)"""
def permute(self, nums: List[int]) -> List[List[int]]:
"""思路:回溯算法,由于没有重复的数字,每次传一个值,用二进制代表哪个位置被选过"""
n = len(nums)
def dfs(a, cur):
nonlocal res
if a == (1 << n) - 1:
... | the_stack_v2_python_sparse | leetcode/1-300/46.py | Rivarrl/leetcode_python | train | 3 |
b29c49d96a74347b0855977fb82301bef2bdf075 | [
"params = NoticesForm(data=request.GET)\nparams.is_valid(raise_exception=True)\ncursor = params.data.get('cursor')\nlimit = params.data.get('limit')\nresponse = dict()\nboard_categories = notices_service.get_categories()\ncategories = NoticeCategorySerializer(board_categories, many=True)\nif cursor == 1:\n respo... | <|body_start_0|>
params = NoticesForm(data=request.GET)
params.is_valid(raise_exception=True)
cursor = params.data.get('cursor')
limit = params.data.get('limit')
response = dict()
board_categories = notices_service.get_categories()
categories = NoticeCategorySeria... | NoticeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoticeView:
def list(self, request):
"""공지사항 리스트"""
<|body_0|>
def retrieve(self, request, pk=None):
"""공지사항"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = NoticesForm(data=request.GET)
params.is_valid(raise_exception=True)
... | stack_v2_sparse_classes_75kplus_train_069302 | 2,349 | no_license | [
{
"docstring": "공지사항 리스트",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "공지사항",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018293 | Implement the Python class `NoticeView` described below.
Class description:
Implement the NoticeView class.
Method signatures and docstrings:
- def list(self, request): 공지사항 리스트
- def retrieve(self, request, pk=None): 공지사항 | Implement the Python class `NoticeView` described below.
Class description:
Implement the NoticeView class.
Method signatures and docstrings:
- def list(self, request): 공지사항 리스트
- def retrieve(self, request, pk=None): 공지사항
<|skeleton|>
class NoticeView:
def list(self, request):
"""공지사항 리스트"""
<|... | 0edc046f57a1c171c10be5dfa4b4e26f440847be | <|skeleton|>
class NoticeView:
def list(self, request):
"""공지사항 리스트"""
<|body_0|>
def retrieve(self, request, pk=None):
"""공지사항"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoticeView:
def list(self, request):
"""공지사항 리스트"""
params = NoticesForm(data=request.GET)
params.is_valid(raise_exception=True)
cursor = params.data.get('cursor')
limit = params.data.get('limit')
response = dict()
board_categories = notices_service.get_... | the_stack_v2_python_sparse | backends/api/v2/notices.py | jmp7786/coins | train | 0 | |
4245b8dd090b10c23e3a190e16d04a677ffff113 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | UpdateStream is the RPC version of binlog.UpdateStream. | UpdateStreamServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateStreamServicer:
"""UpdateStream is the RPC version of binlog.UpdateStream."""
def StreamKeyRange(self, request, context):
"""StreamKeyRange returns the binlog transactions related to the specified Keyrange."""
<|body_0|>
def StreamTables(self, request, context):
... | stack_v2_sparse_classes_75kplus_train_069303 | 2,389 | permissive | [
{
"docstring": "StreamKeyRange returns the binlog transactions related to the specified Keyrange.",
"name": "StreamKeyRange",
"signature": "def StreamKeyRange(self, request, context)"
},
{
"docstring": "StreamTables returns the binlog transactions related to the specified Tables.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_054289 | Implement the Python class `UpdateStreamServicer` described below.
Class description:
UpdateStream is the RPC version of binlog.UpdateStream.
Method signatures and docstrings:
- def StreamKeyRange(self, request, context): StreamKeyRange returns the binlog transactions related to the specified Keyrange.
- def StreamTa... | Implement the Python class `UpdateStreamServicer` described below.
Class description:
UpdateStream is the RPC version of binlog.UpdateStream.
Method signatures and docstrings:
- def StreamKeyRange(self, request, context): StreamKeyRange returns the binlog transactions related to the specified Keyrange.
- def StreamTa... | c873c58fc95bc1b322d788bdb32f2305780cbcfd | <|skeleton|>
class UpdateStreamServicer:
"""UpdateStream is the RPC version of binlog.UpdateStream."""
def StreamKeyRange(self, request, context):
"""StreamKeyRange returns the binlog transactions related to the specified Keyrange."""
<|body_0|>
def StreamTables(self, request, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateStreamServicer:
"""UpdateStream is the RPC version of binlog.UpdateStream."""
def StreamKeyRange(self, request, context):
"""StreamKeyRange returns the binlog transactions related to the specified Keyrange."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_detai... | the_stack_v2_python_sparse | py/vtproto/binlogservice_pb2_grpc.py | HubSpot/vitess | train | 7 |
01f550c486ca73fecd8c98746f1020b9920d78b5 | [
"super().__init__()\nself._offsets = torch.tensor([0] + one_hot_dims, dtype=torch.int).cumsum(0)[:-1]\ninput_dim = sum(one_hot_dims)\nself.one_hot_embed = nn.Embedding(input_dim, output_dim)\nself._input_dim = input_dim",
"x = x + self._offsets.to(x.device)\nx = self.one_hot_embed(x).sum(dim=1)\nreturn x"
] | <|body_start_0|>
super().__init__()
self._offsets = torch.tensor([0] + one_hot_dims, dtype=torch.int).cumsum(0)[:-1]
input_dim = sum(one_hot_dims)
self.one_hot_embed = nn.Embedding(input_dim, output_dim)
self._input_dim = input_dim
<|end_body_0|>
<|body_start_1|>
x = x +... | Linear layer for one hot features. | OneHotLinear | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneHotLinear:
"""Linear layer for one hot features."""
def __init__(self, one_hot_dims, output_dim):
""":param one_hot_dims: List[int], dimensions of one-hot categorical features. :param output_dim: int, output dimension."""
<|body_0|>
def forward(self, x):
""":p... | stack_v2_sparse_classes_75kplus_train_069304 | 943 | permissive | [
{
"docstring": ":param one_hot_dims: List[int], dimensions of one-hot categorical features. :param output_dim: int, output dimension.",
"name": "__init__",
"signature": "def __init__(self, one_hot_dims, output_dim)"
},
{
"docstring": ":param x: Tensor, (n, len(one_hot_dims)). :return: Tensor, (n... | 2 | stack_v2_sparse_classes_30k_val_000788 | Implement the Python class `OneHotLinear` described below.
Class description:
Linear layer for one hot features.
Method signatures and docstrings:
- def __init__(self, one_hot_dims, output_dim): :param one_hot_dims: List[int], dimensions of one-hot categorical features. :param output_dim: int, output dimension.
- def... | Implement the Python class `OneHotLinear` described below.
Class description:
Linear layer for one hot features.
Method signatures and docstrings:
- def __init__(self, one_hot_dims, output_dim): :param one_hot_dims: List[int], dimensions of one-hot categorical features. :param output_dim: int, output dimension.
- def... | 47925be7fb094e3638ae35c25926579d4e6890af | <|skeleton|>
class OneHotLinear:
"""Linear layer for one hot features."""
def __init__(self, one_hot_dims, output_dim):
""":param one_hot_dims: List[int], dimensions of one-hot categorical features. :param output_dim: int, output dimension."""
<|body_0|>
def forward(self, x):
""":p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OneHotLinear:
"""Linear layer for one hot features."""
def __init__(self, one_hot_dims, output_dim):
""":param one_hot_dims: List[int], dimensions of one-hot categorical features. :param output_dim: int, output dimension."""
super().__init__()
self._offsets = torch.tensor([0] + on... | the_stack_v2_python_sparse | recommender/model/module/linear.py | jishuguang/recommender | train | 0 |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"self.prob = prob\nself.flip_axis = flip_axis\nsuper().__init__()",
"if isinstance(self.flip_axis, (tuple, list)):\n flip_axis = self.flip_axis[random.randint(0, len(self.flip_axis) - 1)]\nelse:\n flip_axis = self.flip_axis\nif random.random() < self.prob:\n img = F.flip_3d(img, axis=flip_axis)\n if l... | <|body_start_0|>
self.prob = prob
self.flip_axis = flip_axis
super().__init__()
<|end_body_0|>
<|body_start_1|>
if isinstance(self.flip_axis, (tuple, list)):
flip_axis = self.flip_axis[random.randint(0, len(self.flip_axis) - 1)]
else:
flip_axis = self.fli... | Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1. | RandomFlip3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomFlip3D:
"""Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
<|body_0|>
def __call__(self, img, label=None):
"""Args:... | stack_v2_sparse_classes_75kplus_train_069305 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, prob=0.5, flip_axis=[0, 1, 2])"
},
{
"docstring": "Args: img (numpy ndarray): 3D Image to be flipped. label (numpy ndarray): 3D Label to be flipped. Returns: (np.array). Image after transformation.",
"name": "__call_... | 2 | stack_v2_sparse_classes_30k_train_021468 | Implement the Python class `RandomFlip3D` described below.
Class description:
Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1.
Method signatures and docstrings:
- def __init__(self, prob=0.5, flip_axis=[0, 1, 2]): init
- def __call__(self, im... | Implement the Python class `RandomFlip3D` described below.
Class description:
Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1.
Method signatures and docstrings:
- def __init__(self, prob=0.5, flip_axis=[0, 1, 2]): init
- def __call__(self, im... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomFlip3D:
"""Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
<|body_0|>
def __call__(self, img, label=None):
"""Args:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomFlip3D:
"""Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
self.prob = prob
self.flip_axis = flip_axis
super().__init__()
... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
1864cb01bf4603872053936a47741ae277730906 | [
"body = dict(self._body.dirty)\njob = ExecutableJob.new(**dict(job))\nbody['add_jobs'] = [dict(job._body.dirty)]\nendpoint_override = self.service.get_endpoint_override()\nresponse = session.post('/run-job-flow', headers={}, endpoint_filter=self.service, endpoint_override=endpoint_override, json=dict(body))\nself._... | <|body_start_0|>
body = dict(self._body.dirty)
job = ExecutableJob.new(**dict(job))
body['add_jobs'] = [dict(job._body.dirty)]
endpoint_override = self.service.get_endpoint_override()
response = session.post('/run-job-flow', headers={}, endpoint_filter=self.service, endpoint_over... | HuaWei Cluster extends | ClusterInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterInfo:
"""HuaWei Cluster extends"""
def create_and_run(self, session, job):
"""Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.clus... | stack_v2_sparse_classes_75kplus_train_069306 | 18,095 | permissive | [
{
"docstring": "Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.cluster.ExecutableJob`, comprised of the properties on the ExecutableJob class. :return:",
"name"... | 3 | stack_v2_sparse_classes_30k_train_037831 | Implement the Python class `ClusterInfo` described below.
Class description:
HuaWei Cluster extends
Method signatures and docstrings:
- def create_and_run(self, session, job): Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will ... | Implement the Python class `ClusterInfo` described below.
Class description:
HuaWei Cluster extends
Method signatures and docstrings:
- def create_and_run(self, session, job): Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will ... | 60d75438d71ffb7998f5dc407ffa890cc98d3171 | <|skeleton|>
class ClusterInfo:
"""HuaWei Cluster extends"""
def create_and_run(self, session, job):
"""Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.clus... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterInfo:
"""HuaWei Cluster extends"""
def create_and_run(self, session, job):
"""Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.cluster.Executabl... | the_stack_v2_python_sparse | openstack/map_reduce/v1/cluster.py | huaweicloudsdk/sdk-python | train | 20 |
7beb8f3b3b7b41c64b1faabe2616f80574a8f614 | [
"super().__init__()\nself.sequential = nn.Sequential()\nself.sequential.add_module('B_interaction', FMLayer(fm_dropout_p))\nself.sequential.add_module('Deep', DNNLayer(output_size=1, layer_sizes=deep_layer_sizes, inputs_size=embed_size, dropout_p=deep_dropout_p, activation=deep_activation))\nself.use_bias = use_bia... | <|body_start_0|>
super().__init__()
self.sequential = nn.Sequential()
self.sequential.add_module('B_interaction', FMLayer(fm_dropout_p))
self.sequential.add_module('Deep', DNNLayer(output_size=1, layer_sizes=deep_layer_sizes, inputs_size=embed_size, dropout_p=deep_dropout_p, activation=d... | Model class of Neural Factorization Machine (NFM). Neural Factorization Machine is a model to pool embedding tensors from (B, N, E) to (B, 1, E) with Factorization Machine (FM) as an embedder of Deep Neural Network, i.e. a stack of factorization machine and dense network. :Reference: #. `Xiangnan He et al, 2017. Neural... | NeuralFactorizationMachineModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralFactorizationMachineModel:
"""Model class of Neural Factorization Machine (NFM). Neural Factorization Machine is a model to pool embedding tensors from (B, N, E) to (B, 1, E) with Factorization Machine (FM) as an embedder of Deep Neural Network, i.e. a stack of factorization machine and den... | stack_v2_sparse_classes_75kplus_train_069307 | 3,772 | permissive | [
{
"docstring": "Initialize NeuralFactorizationMachineModel. Args: embed_size (int): size of embedding tensor deep_layer_sizes (List[int]): layer sizes of dense network use_bias (bool, optional): whether the bias constant is concatenated to the input. Defaults to True fm_dropout_p (float, optional): probability ... | 2 | stack_v2_sparse_classes_30k_test_000193 | Implement the Python class `NeuralFactorizationMachineModel` described below.
Class description:
Model class of Neural Factorization Machine (NFM). Neural Factorization Machine is a model to pool embedding tensors from (B, N, E) to (B, 1, E) with Factorization Machine (FM) as an embedder of Deep Neural Network, i.e. a... | Implement the Python class `NeuralFactorizationMachineModel` described below.
Class description:
Model class of Neural Factorization Machine (NFM). Neural Factorization Machine is a model to pool embedding tensors from (B, N, E) to (B, 1, E) with Factorization Machine (FM) as an embedder of Deep Neural Network, i.e. a... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class NeuralFactorizationMachineModel:
"""Model class of Neural Factorization Machine (NFM). Neural Factorization Machine is a model to pool embedding tensors from (B, N, E) to (B, 1, E) with Factorization Machine (FM) as an embedder of Deep Neural Network, i.e. a stack of factorization machine and den... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralFactorizationMachineModel:
"""Model class of Neural Factorization Machine (NFM). Neural Factorization Machine is a model to pool embedding tensors from (B, N, E) to (B, 1, E) with Factorization Machine (FM) as an embedder of Deep Neural Network, i.e. a stack of factorization machine and dense network. :... | the_stack_v2_python_sparse | torecsys/models/ctr/neural_factorization_machine.py | p768lwy3/torecsys | train | 98 |
ad293dcc2c102f1ccbba6cc725c828e65610a318 | [
"super(StartProbLayer, self).__init__()\nself.dropout = nn.Dropout(dropout)\nself.W = nn.Linear(hidden_size, 1)\nutils.init_linear(self.W)\nself.logSoftmax = nn.LogSoftmax()",
"cat = torch.cat([G, M], 2)\nlogits = self.W(cat)\nlogits = self.dropout(logits)\nlogits = logits.squeeze(2)\nlogits = exp_mask_2d(logits,... | <|body_start_0|>
super(StartProbLayer, self).__init__()
self.dropout = nn.Dropout(dropout)
self.W = nn.Linear(hidden_size, 1)
utils.init_linear(self.W)
self.logSoftmax = nn.LogSoftmax()
<|end_body_0|>
<|body_start_1|>
cat = torch.cat([G, M], 2)
logits = self.W(ca... | StartProbLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StartProbLayer:
def __init__(self, hidden_size, dropout=config['dropout']):
""":param hidden_size: 10*d"""
<|body_0|>
def forward(self, M, G, con_lens):
""":param M: (batch, T, 2d) :param G: (batch, T, 8d) :return: (batch, T)"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_069308 | 30,536 | no_license | [
{
"docstring": ":param hidden_size: 10*d",
"name": "__init__",
"signature": "def __init__(self, hidden_size, dropout=config['dropout'])"
},
{
"docstring": ":param M: (batch, T, 2d) :param G: (batch, T, 8d) :return: (batch, T)",
"name": "forward",
"signature": "def forward(self, M, G, con... | 2 | stack_v2_sparse_classes_30k_train_054474 | Implement the Python class `StartProbLayer` described below.
Class description:
Implement the StartProbLayer class.
Method signatures and docstrings:
- def __init__(self, hidden_size, dropout=config['dropout']): :param hidden_size: 10*d
- def forward(self, M, G, con_lens): :param M: (batch, T, 2d) :param G: (batch, T... | Implement the Python class `StartProbLayer` described below.
Class description:
Implement the StartProbLayer class.
Method signatures and docstrings:
- def __init__(self, hidden_size, dropout=config['dropout']): :param hidden_size: 10*d
- def forward(self, M, G, con_lens): :param M: (batch, T, 2d) :param G: (batch, T... | 68809cb162e410dcc5c2c315af66082c57635d43 | <|skeleton|>
class StartProbLayer:
def __init__(self, hidden_size, dropout=config['dropout']):
""":param hidden_size: 10*d"""
<|body_0|>
def forward(self, M, G, con_lens):
""":param M: (batch, T, 2d) :param G: (batch, T, 8d) :return: (batch, T)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StartProbLayer:
def __init__(self, hidden_size, dropout=config['dropout']):
""":param hidden_size: 10*d"""
super(StartProbLayer, self).__init__()
self.dropout = nn.Dropout(dropout)
self.W = nn.Linear(hidden_size, 1)
utils.init_linear(self.W)
self.logSoftmax = nn... | the_stack_v2_python_sparse | bidaf.py | daisyjack/transfer_bidaf | train | 0 | |
543d966e6704765d3accf2ad197d9dcdd23926d4 | [
"self._client = None\nself._domain = domain\nself._sandbox = sandbox\nself._api_key = api_key\nself._sender = sender\nself._recipient = recipient",
"self._client = Client(self._api_key, self._domain, self._sandbox)\n_LOGGER.debug('Mailgun domain: %s', self._client.domain)\nself._domain = self._client.domain\nif n... | <|body_start_0|>
self._client = None
self._domain = domain
self._sandbox = sandbox
self._api_key = api_key
self._sender = sender
self._recipient = recipient
<|end_body_0|>
<|body_start_1|>
self._client = Client(self._api_key, self._domain, self._sandbox)
... | Implement a notification service for the Mailgun mail service. | MailgunNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailgunNotificationService:
"""Implement a notification service for the Mailgun mail service."""
def __init__(self, domain, sandbox, api_key, sender, recipient):
"""Initialize the service."""
<|body_0|>
def initialize_client(self):
"""Initialize the connection to... | stack_v2_sparse_classes_75kplus_train_069309 | 3,470 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, domain, sandbox, api_key, sender, recipient)"
},
{
"docstring": "Initialize the connection to Mailgun.",
"name": "initialize_client",
"signature": "def initialize_client(self)"
},
{
"do... | 4 | stack_v2_sparse_classes_30k_test_000418 | Implement the Python class `MailgunNotificationService` described below.
Class description:
Implement a notification service for the Mailgun mail service.
Method signatures and docstrings:
- def __init__(self, domain, sandbox, api_key, sender, recipient): Initialize the service.
- def initialize_client(self): Initial... | Implement the Python class `MailgunNotificationService` described below.
Class description:
Implement a notification service for the Mailgun mail service.
Method signatures and docstrings:
- def __init__(self, domain, sandbox, api_key, sender, recipient): Initialize the service.
- def initialize_client(self): Initial... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MailgunNotificationService:
"""Implement a notification service for the Mailgun mail service."""
def __init__(self, domain, sandbox, api_key, sender, recipient):
"""Initialize the service."""
<|body_0|>
def initialize_client(self):
"""Initialize the connection to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MailgunNotificationService:
"""Implement a notification service for the Mailgun mail service."""
def __init__(self, domain, sandbox, api_key, sender, recipient):
"""Initialize the service."""
self._client = None
self._domain = domain
self._sandbox = sandbox
self._a... | the_stack_v2_python_sparse | homeassistant/components/mailgun/notify.py | home-assistant/core | train | 35,501 |
c83e8df70834f713f1f51bbcaac6363520891375 | [
"user = get_object_or_404(User, email=request.user.email)\ninfo = {'gold': user.gold}\nreturn Response(info, status=status.HTTP_200_OK)",
"user = get_object_or_404(User, email=request.user.email)\nuser.gold = int(request.data['gold'])\nuser.save()\ninfo = {'gold': user.gold}\nreturn Response(info, status=status.H... | <|body_start_0|>
user = get_object_or_404(User, email=request.user.email)
info = {'gold': user.gold}
return Response(info, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
user = get_object_or_404(User, email=request.user.email)
user.gold = int(request.data['gold'])
... | Gold | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gold:
def get(self, request):
"""get your(user's) gold /return => {gold : yourgold(int)}"""
<|body_0|>
def put(self, request):
"""change your gold after calculating /return => {gold : yourgold(int, after calculating)}"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_069310 | 9,686 | no_license | [
{
"docstring": "get your(user's) gold /return => {gold : yourgold(int)}",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "change your gold after calculating /return => {gold : yourgold(int, after calculating)}",
"name": "put",
"signature": "def put(self, request)"... | 2 | stack_v2_sparse_classes_30k_train_028271 | Implement the Python class `Gold` described below.
Class description:
Implement the Gold class.
Method signatures and docstrings:
- def get(self, request): get your(user's) gold /return => {gold : yourgold(int)}
- def put(self, request): change your gold after calculating /return => {gold : yourgold(int, after calcul... | Implement the Python class `Gold` described below.
Class description:
Implement the Gold class.
Method signatures and docstrings:
- def get(self, request): get your(user's) gold /return => {gold : yourgold(int)}
- def put(self, request): change your gold after calculating /return => {gold : yourgold(int, after calcul... | 291ec9e7304772769be7bf52ca8511791485bffe | <|skeleton|>
class Gold:
def get(self, request):
"""get your(user's) gold /return => {gold : yourgold(int)}"""
<|body_0|>
def put(self, request):
"""change your gold after calculating /return => {gold : yourgold(int, after calculating)}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gold:
def get(self, request):
"""get your(user's) gold /return => {gold : yourgold(int)}"""
user = get_object_or_404(User, email=request.user.email)
info = {'gold': user.gold}
return Response(info, status=status.HTTP_200_OK)
def put(self, request):
"""change your g... | the_stack_v2_python_sparse | backend/Django/accounts/views.py | starseek34/DailyTown | train | 0 | |
a0fc2a004c5fc5729cc65ad401b69da46a9d029b | [
"samples = [sample]\ncollate_task = collate_macrobes.s(samples, False)\npersist_task = persist_result.s(sample['analysis_result'], MODULE_NAME)\ntask_chain = chain(collate_task, persist_task)\nresult = task_chain.delay()\nreturn result",
"collate_task = collate_macrobes.s(samples, True)\npersist_task = persist_re... | <|body_start_0|>
samples = [sample]
collate_task = collate_macrobes.s(samples, False)
persist_task = persist_result.s(sample['analysis_result'], MODULE_NAME)
task_chain = chain(collate_task, persist_task)
result = task_chain.delay()
return result
<|end_body_0|>
<|body_st... | Tasks for generating virulence results. | MacrobeWrangler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacrobeWrangler:
"""Tasks for generating virulence results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
<|body_0|>
def run_sample_group(cls, sample_group, samples):
"""Gather and process samples."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_069311 | 2,268 | permissive | [
{
"docstring": "Gather single sample and process.",
"name": "run_sample",
"signature": "def run_sample(cls, sample_id, sample)"
},
{
"docstring": "Gather and process samples.",
"name": "run_sample_group",
"signature": "def run_sample_group(cls, sample_group, samples)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011481 | Implement the Python class `MacrobeWrangler` described below.
Class description:
Tasks for generating virulence results.
Method signatures and docstrings:
- def run_sample(cls, sample_id, sample): Gather single sample and process.
- def run_sample_group(cls, sample_group, samples): Gather and process samples. | Implement the Python class `MacrobeWrangler` described below.
Class description:
Tasks for generating virulence results.
Method signatures and docstrings:
- def run_sample(cls, sample_id, sample): Gather single sample and process.
- def run_sample_group(cls, sample_group, samples): Gather and process samples.
<|skel... | 609cd57c626c857c8efde8237a1f22f4d1e6065d | <|skeleton|>
class MacrobeWrangler:
"""Tasks for generating virulence results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
<|body_0|>
def run_sample_group(cls, sample_group, samples):
"""Gather and process samples."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MacrobeWrangler:
"""Tasks for generating virulence results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
samples = [sample]
collate_task = collate_macrobes.s(samples, False)
persist_task = persist_result.s(sample['analysis_result'], MO... | the_stack_v2_python_sparse | app/display_modules/macrobes/wrangler.py | MetaGenScope/metagenscope-server | train | 0 |
75316ed6b1e36d938bea1e10466f3ba774ddac00 | [
"check_arg(dirpath, u._('Directory path'), str)\ndirpath = safe_decode(dirpath)\nif not os.path.exists(dirpath):\n raise InvalidArgument(u._('Directory path: {path} does not exist').format(path=dirpath))\ndumpfile_path = dump(dirpath)\nreturn dumpfile_path",
"check_arg(dirpath, u._('Directory path'), str)\ndir... | <|body_start_0|>
check_arg(dirpath, u._('Directory path'), str)
dirpath = safe_decode(dirpath)
if not os.path.exists(dirpath):
raise InvalidArgument(u._('Directory path: {path} does not exist').format(path=dirpath))
dumpfile_path = dump(dirpath)
return dumpfile_path
<... | SupportApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportApi:
def support_dump(self, dirpath):
"""Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :t... | stack_v2_sparse_classes_75kplus_train_069312 | 3,067 | permissive | [
{
"docstring": "Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :type dirpath: string :return: path to dump file :rtype: s... | 2 | stack_v2_sparse_classes_30k_test_000596 | Implement the Python class `SupportApi` described below.
Class description:
Implement the SupportApi class.
Method signatures and docstrings:
- def support_dump(self, dirpath): Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / developm... | Implement the Python class `SupportApi` described below.
Class description:
Implement the SupportApi class.
Method signatures and docstrings:
- def support_dump(self, dirpath): Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / developm... | dc38107ff2462f62124b5feab275fa369e223169 | <|skeleton|>
class SupportApi:
def support_dump(self, dirpath):
"""Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SupportApi:
def support_dump(self, dirpath):
"""Dumps configuration data for debugging. Dumps most files in /etc/kolla and /usr/share/kolla into a tar file so be given to support / development to help with debugging problems. :param dirpath: path to directory where dump will be placed :type dirpath: s... | the_stack_v2_python_sparse | kolla_cli/api/support.py | iputra/kolla-cli | train | 0 | |
3d2ad88486120b1fc4ea2d98217c8305ca03d652 | [
"cache_directory = self.config['cache_directory']\nsimulation_state = SimulationState()\nsimulation_state.set_current_time(year)\nsimulation_state.set_cache_directory(cache_directory)\nyear_config = self.config['travel_model_configuration'][year]\nbank_path = os.path.sep.join([self.get_emme2_base_dir()] + self.conf... | <|body_start_0|>
cache_directory = self.config['cache_directory']
simulation_state = SimulationState()
simulation_state.set_current_time(year)
simulation_state.set_cache_directory(cache_directory)
year_config = self.config['travel_model_configuration'][year]
bank_path = o... | Class to get skims from emme4 into the UrbanSim cache. | GetEmme4DataIntoCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetEmme4DataIntoCache:
"""Class to get skims from emme4 into the UrbanSim cache."""
def run(self, year):
"""Like its parent, but report files have different format and there are no banks. Zones are assumed to have no gaps."""
<|body_0|>
def get_needed_matrices_from_emme4... | stack_v2_sparse_classes_75kplus_train_069313 | 5,156 | no_license | [
{
"docstring": "Like its parent, but report files have different format and there are no banks. Zones are assumed to have no gaps.",
"name": "run",
"signature": "def run(self, year)"
},
{
"docstring": "Copies the specified emme4 matrices into the specified travel_data variable names.",
"name... | 3 | stack_v2_sparse_classes_30k_train_040381 | Implement the Python class `GetEmme4DataIntoCache` described below.
Class description:
Class to get skims from emme4 into the UrbanSim cache.
Method signatures and docstrings:
- def run(self, year): Like its parent, but report files have different format and there are no banks. Zones are assumed to have no gaps.
- de... | Implement the Python class `GetEmme4DataIntoCache` described below.
Class description:
Class to get skims from emme4 into the UrbanSim cache.
Method signatures and docstrings:
- def run(self, year): Like its parent, but report files have different format and there are no banks. Zones are assumed to have no gaps.
- de... | c392d15b35aa1d47bbc185ed76314f8e6dd9f92f | <|skeleton|>
class GetEmme4DataIntoCache:
"""Class to get skims from emme4 into the UrbanSim cache."""
def run(self, year):
"""Like its parent, but report files have different format and there are no banks. Zones are assumed to have no gaps."""
<|body_0|>
def get_needed_matrices_from_emme4... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetEmme4DataIntoCache:
"""Class to get skims from emme4 into the UrbanSim cache."""
def run(self, year):
"""Like its parent, but report files have different format and there are no banks. Zones are assumed to have no gaps."""
cache_directory = self.config['cache_directory']
simula... | the_stack_v2_python_sparse | psrc_parcel/emme/models/get_emme4_data_into_cache.py | psrc/urbansim | train | 4 |
532aba3c7e28d6494a69c4ab8cb87067e1f26673 | [
"Instrument.__init__(self, cle)\nself.precision = 10\nself.etendre_editeur('r', 'précision', Uniligne, self, 'precision')",
"precision = enveloppes['r']\nprecision.apercu = '{objet.precision}'\nprecision.prompt = 'Précision (en degré) de la boussole : '\nprecision.aide_courte = 'Entrez la |ent|précision|ff| de la... | <|body_start_0|>
Instrument.__init__(self, cle)
self.precision = 10
self.etendre_editeur('r', 'précision', Uniligne, self, 'precision')
<|end_body_0|>
<|body_start_1|>
precision = enveloppes['r']
precision.apercu = '{objet.precision}'
precision.prompt = 'Précision (en de... | Type d'objet: boussole. | Boussole | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Boussole:
"""Type d'objet: boussole."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
def regarder(self, personnage):
"""Quand on ... | stack_v2_sparse_classes_75kplus_train_069314 | 4,065 | permissive | [
{
"docstring": "Constructeur de l'objet",
"name": "__init__",
"signature": "def __init__(self, cle='')"
},
{
"docstring": "Travail sur les enveloppes",
"name": "travailler_enveloppes",
"signature": "def travailler_enveloppes(self, enveloppes)"
},
{
"docstring": "Quand on regarde ... | 3 | stack_v2_sparse_classes_30k_train_046052 | Implement the Python class `Boussole` described below.
Class description:
Type d'objet: boussole.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
- def regarder(self, personnage): Quand on regarde la bous... | Implement the Python class `Boussole` described below.
Class description:
Type d'objet: boussole.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
- def regarder(self, personnage): Quand on regarde la bous... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class Boussole:
"""Type d'objet: boussole."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
def regarder(self, personnage):
"""Quand on ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Boussole:
"""Type d'objet: boussole."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
Instrument.__init__(self, cle)
self.precision = 10
self.etendre_editeur('r', 'précision', Uniligne, self, 'precision')
def travailler_enveloppes(self, enveloppes):
... | the_stack_v2_python_sparse | src/secondaires/navigation/types/boussole.py | vincent-lg/tsunami | train | 5 |
31c5914468bb68ee2d043b09d11d6d55f9ba1a92 | [
"if not isinstance(source, dict):\n source = vars(source)\nself.source = source",
"result = self.source.get(key, None)\nif result is None:\n raise ValueError('%s: no such symbol')\nif not callable(result):\n raise ValueError('value of %s is not callable (type is %s)' % (key, type(result)))\nreturn Functi... | <|body_start_0|>
if not isinstance(source, dict):
source = vars(source)
self.source = source
<|end_body_0|>
<|body_start_1|>
result = self.source.get(key, None)
if result is None:
raise ValueError('%s: no such symbol')
if not callable(result):
... | Automatically curry functions when accessed as attributes. This class wraps a dictionary mapping keys to values. When an attribute is accessed, the class looks up the attribute in the dictionary and wraps it (curries it) using Function(...). When wrapped around existing modules implementing TensorFlow functions or laye... | AutoFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoFunction:
"""Automatically curry functions when accessed as attributes. This class wraps a dictionary mapping keys to values. When an attribute is accessed, the class looks up the attribute in the dictionary and wraps it (curries it) using Function(...). When wrapped around existing modules i... | stack_v2_sparse_classes_75kplus_train_069315 | 7,680 | permissive | [
{
"docstring": "Creates an AutoFunction wrapper for a module. Args: source: A dictionary or a module.",
"name": "__init__",
"signature": "def __init__(self, source)"
},
{
"docstring": "Looks up the key in the source dictionary and curries the result. Args: key: The symbol name to look up. Return... | 2 | stack_v2_sparse_classes_30k_train_045209 | Implement the Python class `AutoFunction` described below.
Class description:
Automatically curry functions when accessed as attributes. This class wraps a dictionary mapping keys to values. When an attribute is accessed, the class looks up the attribute in the dictionary and wraps it (curries it) using Function(...).... | Implement the Python class `AutoFunction` described below.
Class description:
Automatically curry functions when accessed as attributes. This class wraps a dictionary mapping keys to values. When an attribute is accessed, the class looks up the attribute in the dictionary and wraps it (curries it) using Function(...).... | f536d3d0b91f7f07f8e4a3978d362cd21bad832c | <|skeleton|>
class AutoFunction:
"""Automatically curry functions when accessed as attributes. This class wraps a dictionary mapping keys to values. When an attribute is accessed, the class looks up the attribute in the dictionary and wraps it (curries it) using Function(...). When wrapped around existing modules i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoFunction:
"""Automatically curry functions when accessed as attributes. This class wraps a dictionary mapping keys to values. When an attribute is accessed, the class looks up the attribute in the dictionary and wraps it (curries it) using Function(...). When wrapped around existing modules implementing T... | the_stack_v2_python_sparse | tensorflow/contrib/specs/python/specs_lib.py | lidenghui1110/tensorflow-0.12.0-fpga | train | 3 |
832729c8c3ad0fc1485e61d08ac5859d67779c87 | [
"amount_sold = deserialize_asset_amount(csv_row['Sell Amount'])\namount_bought = deserialize_asset_amount(csv_row['Buy Amount'])\nasset, fee, fee_currency, location, timestamp = process_rotki_generic_import_csv_fields(csv_row, 'Base Currency')\ntrade = Trade(timestamp=ts_ms_to_sec(timestamp), location=location, fee... | <|body_start_0|>
amount_sold = deserialize_asset_amount(csv_row['Sell Amount'])
amount_bought = deserialize_asset_amount(csv_row['Buy Amount'])
asset, fee, fee_currency, location, timestamp = process_rotki_generic_import_csv_fields(csv_row, 'Base Currency')
trade = Trade(timestamp=ts_ms_... | RotkiGenericTradesImporter | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotkiGenericTradesImporter:
def _consume_rotki_trades(self, write_cursor: DBCursor, csv_row: dict[str, Any]) -> None:
"""Consume rotki generic trades import CSV file. May raise: - DeserializationError - UnknownAsset - KeyError - DivisionByZero if `amount_bought` is ZERO"""
<|body... | stack_v2_sparse_classes_75kplus_train_069316 | 3,563 | permissive | [
{
"docstring": "Consume rotki generic trades import CSV file. May raise: - DeserializationError - UnknownAsset - KeyError - DivisionByZero if `amount_bought` is ZERO",
"name": "_consume_rotki_trades",
"signature": "def _consume_rotki_trades(self, write_cursor: DBCursor, csv_row: dict[str, Any]) -> None"... | 2 | stack_v2_sparse_classes_30k_train_037309 | Implement the Python class `RotkiGenericTradesImporter` described below.
Class description:
Implement the RotkiGenericTradesImporter class.
Method signatures and docstrings:
- def _consume_rotki_trades(self, write_cursor: DBCursor, csv_row: dict[str, Any]) -> None: Consume rotki generic trades import CSV file. May ra... | Implement the Python class `RotkiGenericTradesImporter` described below.
Class description:
Implement the RotkiGenericTradesImporter class.
Method signatures and docstrings:
- def _consume_rotki_trades(self, write_cursor: DBCursor, csv_row: dict[str, Any]) -> None: Consume rotki generic trades import CSV file. May ra... | 496948458b89afc41458f19d1cba0e971ab67c8b | <|skeleton|>
class RotkiGenericTradesImporter:
def _consume_rotki_trades(self, write_cursor: DBCursor, csv_row: dict[str, Any]) -> None:
"""Consume rotki generic trades import CSV file. May raise: - DeserializationError - UnknownAsset - KeyError - DivisionByZero if `amount_bought` is ZERO"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RotkiGenericTradesImporter:
def _consume_rotki_trades(self, write_cursor: DBCursor, csv_row: dict[str, Any]) -> None:
"""Consume rotki generic trades import CSV file. May raise: - DeserializationError - UnknownAsset - KeyError - DivisionByZero if `amount_bought` is ZERO"""
amount_sold = deseri... | the_stack_v2_python_sparse | rotkehlchen/data_import/importers/rotki_trades.py | LefterisJP/rotkehlchen | train | 0 | |
63eed6235fcbd320eb4281074d85cb279c3c3c1f | [
"def gotResults(results):\n for name, url, id in results:\n yield (u'\\x02%s\\x02: <%s>;' % (name, url))\n\ndef outputResults(results):\n source.reply(u' '.join(results))\nreturn imdb.searchByTitle(title, exact=False).addCallback(gotResults).addCallback(outputResults)",
"def gotInfo(info):\n sourc... | <|body_start_0|>
def gotResults(results):
for name, url, id in results:
yield (u'\x02%s\x02: <%s>;' % (name, url))
def outputResults(results):
source.reply(u' '.join(results))
return imdb.searchByTitle(title, exact=False).addCallback(gotResults).addCallba... | IMDB | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IMDB:
def cmd_search(self, source, title):
"""Search IMDB for artifacts whose titles match <title>."""
<|body_0|>
def cmd_plot(self, source, id):
"""Retrieve the plot information for an IMDB title with <id>."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069317 | 1,477 | permissive | [
{
"docstring": "Search IMDB for artifacts whose titles match <title>.",
"name": "cmd_search",
"signature": "def cmd_search(self, source, title)"
},
{
"docstring": "Retrieve the plot information for an IMDB title with <id>.",
"name": "cmd_plot",
"signature": "def cmd_plot(self, source, id... | 2 | stack_v2_sparse_classes_30k_train_001597 | Implement the Python class `IMDB` described below.
Class description:
Implement the IMDB class.
Method signatures and docstrings:
- def cmd_search(self, source, title): Search IMDB for artifacts whose titles match <title>.
- def cmd_plot(self, source, id): Retrieve the plot information for an IMDB title with <id>. | Implement the Python class `IMDB` described below.
Class description:
Implement the IMDB class.
Method signatures and docstrings:
- def cmd_search(self, source, title): Search IMDB for artifacts whose titles match <title>.
- def cmd_plot(self, source, id): Retrieve the plot information for an IMDB title with <id>.
<... | 11c80c7024548ce7c41800b077d3d0a738a04875 | <|skeleton|>
class IMDB:
def cmd_search(self, source, title):
"""Search IMDB for artifacts whose titles match <title>."""
<|body_0|>
def cmd_plot(self, source, id):
"""Retrieve the plot information for an IMDB title with <id>."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IMDB:
def cmd_search(self, source, title):
"""Search IMDB for artifacts whose titles match <title>."""
def gotResults(results):
for name, url, id in results:
yield (u'\x02%s\x02: <%s>;' % (name, url))
def outputResults(results):
source.reply(u' ... | the_stack_v2_python_sparse | eridanusstd/plugindefs/imdb.py | mithrandi/eridanus | train | 0 | |
095480442682eb779a5446babc7d689ed39d6e1d | [
"QTreeView.__init__(self, parent_widget)\nself.setAnimated(True)\nself.setMinimumHeight(200)\nself.setExpandsOnDoubleClick(False)",
"index = self.model().index_for_item(item)\nif item.node.get('setexpanded') == 'True':\n self.expand(index)\nfor child_item in item.child_items:\n self._expand_subnodes(child_i... | <|body_start_0|>
QTreeView.__init__(self, parent_widget)
self.setAnimated(True)
self.setMinimumHeight(200)
self.setExpandsOnDoubleClick(False)
<|end_body_0|>
<|body_start_1|>
index = self.model().index_for_item(item)
if item.node.get('setexpanded') == 'True':
... | TreeView for viewing XML data. | XmlView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlView:
"""TreeView for viewing XML data."""
def __init__(self, parent_widget):
"""Tree view for displaying data in a XmlModel @param parent_widget (QWidget): Parent widget"""
<|body_0|>
def _expand_subnodes(self, item):
"""Recursively expands all items under (a... | stack_v2_sparse_classes_75kplus_train_069318 | 1,602 | no_license | [
{
"docstring": "Tree view for displaying data in a XmlModel @param parent_widget (QWidget): Parent widget",
"name": "__init__",
"signature": "def __init__(self, parent_widget)"
},
{
"docstring": "Recursively expands all items under (and including) a given index. Items are expanded only if \"sete... | 3 | stack_v2_sparse_classes_30k_train_048867 | Implement the Python class `XmlView` described below.
Class description:
TreeView for viewing XML data.
Method signatures and docstrings:
- def __init__(self, parent_widget): Tree view for displaying data in a XmlModel @param parent_widget (QWidget): Parent widget
- def _expand_subnodes(self, item): Recursively expan... | Implement the Python class `XmlView` described below.
Class description:
TreeView for viewing XML data.
Method signatures and docstrings:
- def __init__(self, parent_widget): Tree view for displaying data in a XmlModel @param parent_widget (QWidget): Parent widget
- def _expand_subnodes(self, item): Recursively expan... | c392d15b35aa1d47bbc185ed76314f8e6dd9f92f | <|skeleton|>
class XmlView:
"""TreeView for viewing XML data."""
def __init__(self, parent_widget):
"""Tree view for displaying data in a XmlModel @param parent_widget (QWidget): Parent widget"""
<|body_0|>
def _expand_subnodes(self, item):
"""Recursively expands all items under (a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XmlView:
"""TreeView for viewing XML data."""
def __init__(self, parent_widget):
"""Tree view for displaying data in a XmlModel @param parent_widget (QWidget): Parent widget"""
QTreeView.__init__(self, parent_widget)
self.setAnimated(True)
self.setMinimumHeight(200)
... | the_stack_v2_python_sparse | opus_gui/abstract_manager/views/xml_view.py | psrc/urbansim | train | 4 |
421e352bf699b6285250c370ded0aae3bd217dc6 | [
"self.params = {}\nself.reg = reg\nself.params['W1'] = np.random.normal(scale=weight_scale, size=(input_dim, hidden_dim))\nself.params['b1'] = np.zeros(hidden_dim)\nself.params['W2'] = np.random.normal(scale=weight_scale, size=(hidden_dim, num_classes))\nself.params['b2'] = np.zeros(num_classes)",
"scores = None\... | <|body_start_0|>
self.params = {}
self.reg = reg
self.params['W1'] = np.random.normal(scale=weight_scale, size=(input_dim, hidden_dim))
self.params['b1'] = np.zeros(hidden_dim)
self.params['W2'] = np.random.normal(scale=weight_scale, size=(hidden_dim, num_classes))
self.p... | A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this class does not implement ... | TwoLayerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. N... | stack_v2_sparse_classes_75kplus_train_069319 | 28,835 | no_license | [
{
"docstring": "Initialize a new network. Inputs: - input_dim: An integer giving the size of the input - hidden_dim: An integer giving the size of the hidden layer - num_classes: An integer giving the number of classes to classify - dropout: Scalar between 0 and 1 giving dropout strength. - weight_scale: Scalar... | 2 | stack_v2_sparse_classes_30k_train_050608 | Implement the Python class `TwoLayerNet` described below.
Class description:
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should... | Implement the Python class `TwoLayerNet` described below.
Class description:
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should... | 56dd27f676c0e19f8a72010353205be9b2dee9cc | <|skeleton|>
class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this... | the_stack_v2_python_sparse | Assignment 2/fcNet.py | DataDan01/CS231n-Notes | train | 0 |
c1665d8d2a01d0e3ccafc635a5f7c1bccf37967f | [
"self.tc = TConfig()\nself.p = MPDPool(self)\nself.get_genres()",
"self.genres = set()\ntry:\n m = self.p.connect()\n all_tracks = m.listallinfo()\n for t in all_tracks:\n if not 'genre' in t:\n continue\n if type(t['genre']) == list:\n track_genres = t['genre']\n ... | <|body_start_0|>
self.tc = TConfig()
self.p = MPDPool(self)
self.get_genres()
<|end_body_0|>
<|body_start_1|>
self.genres = set()
try:
m = self.p.connect()
all_tracks = m.listallinfo()
for t in all_tracks:
if not 'genre' in t:
... | Globals acts as a container for objects available throughout the life of the application | Globals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Globals:
"""Globals acts as a container for objects available throughout the life of the application"""
def __init__(self):
"""One instance of Globals is created during application initialization and is available during requests via the 'g' variable"""
<|body_0|>
def get... | stack_v2_sparse_classes_75kplus_train_069320 | 1,325 | permissive | [
{
"docstring": "One instance of Globals is created during application initialization and is available during requests via the 'g' variable",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "load all tracks and create a list of every unique genre in the database",
"nam... | 2 | stack_v2_sparse_classes_30k_train_048448 | Implement the Python class `Globals` described below.
Class description:
Globals acts as a container for objects available throughout the life of the application
Method signatures and docstrings:
- def __init__(self): One instance of Globals is created during application initialization and is available during request... | Implement the Python class `Globals` described below.
Class description:
Globals acts as a container for objects available throughout the life of the application
Method signatures and docstrings:
- def __init__(self): One instance of Globals is created during application initialization and is available during request... | 9a30e2687f955e99feee87592d6db96ff4af46f9 | <|skeleton|>
class Globals:
"""Globals acts as a container for objects available throughout the life of the application"""
def __init__(self):
"""One instance of Globals is created during application initialization and is available during requests via the 'g' variable"""
<|body_0|>
def get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Globals:
"""Globals acts as a container for objects available throughout the life of the application"""
def __init__(self):
"""One instance of Globals is created during application initialization and is available during requests via the 'g' variable"""
self.tc = TConfig()
self.p =... | the_stack_v2_python_sparse | theory/lib/app_globals.py | spookylukey/theory | train | 0 |
5777296b894b4b56347dc16a6290550e3ae30462 | [
"self.name = name\nself.time_avg = time_avg\nself.time_dev = time_dev\nself.cv = cv\nself.sample_num = samples\nself.lines = lines",
"lines = []\nif self.sample_num > 1:\n lines.append('{}: {:.5f} σ={:.5f}ms with n={} cv={}'.format(self.name, self.time_avg, self.time_dev, self.sample_num, self.cv))\nelse:\n ... | <|body_start_0|>
self.name = name
self.time_avg = time_avg
self.time_dev = time_dev
self.cv = cv
self.sample_num = samples
self.lines = lines
<|end_body_0|>
<|body_start_1|>
lines = []
if self.sample_num > 1:
lines.append('{}: {:.5f} σ={:.5f}m... | TestStats | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStats:
def __init__(self, name: str, time_avg: float, time_dev: float, cv: float, samples: int, lines: List[LineStats]) -> None:
"""Represents a summary of relevant statistics for a list of tests. Args: name (str): The name of the test whose runs are being averaged. time_avg (float):... | stack_v2_sparse_classes_75kplus_train_069321 | 13,376 | permissive | [
{
"docstring": "Represents a summary of relevant statistics for a list of tests. Args: name (str): The name of the test whose runs are being averaged. time_avg (float): The average time to execute the test. time_dev (float): The standard deviation in the mean. cv (float): The coefficient of variance of the popu... | 2 | stack_v2_sparse_classes_30k_val_001287 | Implement the Python class `TestStats` described below.
Class description:
Implement the TestStats class.
Method signatures and docstrings:
- def __init__(self, name: str, time_avg: float, time_dev: float, cv: float, samples: int, lines: List[LineStats]) -> None: Represents a summary of relevant statistics for a list... | Implement the Python class `TestStats` described below.
Class description:
Implement the TestStats class.
Method signatures and docstrings:
- def __init__(self, name: str, time_avg: float, time_dev: float, cv: float, samples: int, lines: List[LineStats]) -> None: Represents a summary of relevant statistics for a list... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class TestStats:
def __init__(self, name: str, time_avg: float, time_dev: float, cv: float, samples: int, lines: List[LineStats]) -> None:
"""Represents a summary of relevant statistics for a list of tests. Args: name (str): The name of the test whose runs are being averaged. time_avg (float):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStats:
def __init__(self, name: str, time_avg: float, time_dev: float, cv: float, samples: int, lines: List[LineStats]) -> None:
"""Represents a summary of relevant statistics for a list of tests. Args: name (str): The name of the test whose runs are being averaged. time_avg (float): The average t... | the_stack_v2_python_sparse | tools/fuchsia/comparative_tester/generate_perf_report.py | chromium/chromium | train | 17,408 | |
c37709554a9dfab9315af5ed9ef1549b8efd92e4 | [
"ip = IndexPage(class_env)\nnum = ip.pending_triage_patients_num()\nip.click_newPatient()\nnp = NewPatient(class_env)\nnp.send_information(cardnum=data['cardnum'], fullname=data['fullname'], birthday=data['birthday'])\nnp.new_patient_draf()\nassert np.save_suc()\nip.return_homepage()\nnew_num = ip.pending_triage_pa... | <|body_start_0|>
ip = IndexPage(class_env)
num = ip.pending_triage_patients_num()
ip.click_newPatient()
np = NewPatient(class_env)
np.send_information(cardnum=data['cardnum'], fullname=data['fullname'], birthday=data['birthday'])
np.new_patient_draf()
assert np.sa... | 测试新增患者暂存和保存以及统计的人数变化 | TestNewPatient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNewPatient:
"""测试新增患者暂存和保存以及统计的人数变化"""
def test_new_patient_def(self, data, class_env):
"""新增患者暂存 :param data: 患者数据 :param class_env: driver :return:"""
<|body_0|>
def test_new_patient_save(self, data, class_env):
"""#新增患者保存 :param data: 患者数据 ip = IndexPage(c... | stack_v2_sparse_classes_75kplus_train_069322 | 2,086 | no_license | [
{
"docstring": "新增患者暂存 :param data: 患者数据 :param class_env: driver :return:",
"name": "test_new_patient_def",
"signature": "def test_new_patient_def(self, data, class_env)"
},
{
"docstring": "#新增患者保存 :param data: 患者数据 ip = IndexPage(class_env) num = ip.separated_patients_num() # 点击新增患者 ip.click_n... | 2 | null | Implement the Python class `TestNewPatient` described below.
Class description:
测试新增患者暂存和保存以及统计的人数变化
Method signatures and docstrings:
- def test_new_patient_def(self, data, class_env): 新增患者暂存 :param data: 患者数据 :param class_env: driver :return:
- def test_new_patient_save(self, data, class_env): #新增患者保存 :param data: ... | Implement the Python class `TestNewPatient` described below.
Class description:
测试新增患者暂存和保存以及统计的人数变化
Method signatures and docstrings:
- def test_new_patient_def(self, data, class_env): 新增患者暂存 :param data: 患者数据 :param class_env: driver :return:
- def test_new_patient_save(self, data, class_env): #新增患者保存 :param data: ... | 10f8ea61b30572915be39ada44b30e47d65d1d70 | <|skeleton|>
class TestNewPatient:
"""测试新增患者暂存和保存以及统计的人数变化"""
def test_new_patient_def(self, data, class_env):
"""新增患者暂存 :param data: 患者数据 :param class_env: driver :return:"""
<|body_0|>
def test_new_patient_save(self, data, class_env):
"""#新增患者保存 :param data: 患者数据 ip = IndexPage(c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestNewPatient:
"""测试新增患者暂存和保存以及统计的人数变化"""
def test_new_patient_def(self, data, class_env):
"""新增患者暂存 :param data: 患者数据 :param class_env: driver :return:"""
ip = IndexPage(class_env)
num = ip.pending_triage_patients_num()
ip.click_newPatient()
np = NewPatient(class... | the_stack_v2_python_sparse | TestCases/test_1_triage/test_0_add_patient.py | 2353501820/ecsProject | train | 0 |
5969474fa3c92f5089d35dbfabadb8e6b0364fb8 | [
"kth = None\ncnt = 0\n\ndef find_kth_smallest(node):\n if not node:\n return False\n if find_kth_smallest(node.left):\n return True\n nonlocal cnt, kth\n cnt += 1\n if cnt == k:\n kth = node.val\n return True\n return find_kth_smallest(node.right)\nfind_kth_smallest(roo... | <|body_start_0|>
kth = None
cnt = 0
def find_kth_smallest(node):
if not node:
return False
if find_kth_smallest(node.left):
return True
nonlocal cnt, kth
cnt += 1
if cnt == k:
kth = node.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""08/25/2019 16:16"""
<|body_0|>
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
"""05/01/2022 19:49"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kth = None
... | stack_v2_sparse_classes_75kplus_train_069323 | 2,893 | no_license | [
{
"docstring": "08/25/2019 16:16",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: TreeNode, k: int) -> int"
},
{
"docstring": "05/01/2022 19:49",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: Optional[TreeNode], k: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_052108 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: 08/25/2019 16:16
- def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 05/01/2022 19:49 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: 08/25/2019 16:16
- def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 05/01/2022 19:49
<|skeleton|>
class Solu... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""08/25/2019 16:16"""
<|body_0|>
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
"""05/01/2022 19:49"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""08/25/2019 16:16"""
kth = None
cnt = 0
def find_kth_smallest(node):
if not node:
return False
if find_kth_smallest(node.left):
return True
non... | the_stack_v2_python_sparse | leetcode/solved/230_Kth_Smallest_Element_in_a_BST/solution.py | sungminoh/algorithms | train | 0 | |
c81f20de23917627ad29d0d062a6fd876772a9c4 | [
"if isinstance(file_object, BufferedReader) or isinstance(file_object, InMemoryUploadedFile) or isinstance(file_object, TemporaryUploadedFile) or isinstance(file_object, ImageFieldFile):\n super(Photo, self).__init__(file_object)\n self.obj = file_object\n self.pillow_image = self.convert()\nelse:\n rai... | <|body_start_0|>
if isinstance(file_object, BufferedReader) or isinstance(file_object, InMemoryUploadedFile) or isinstance(file_object, TemporaryUploadedFile) or isinstance(file_object, ImageFieldFile):
super(Photo, self).__init__(file_object)
self.obj = file_object
self.pill... | Class to manipulate image data References https://docs.djangoproject.com/en/1.10/_modules/django/core/files/uploadedfile/#InMemoryUploadedFile http://stackoverflow.com/questions/36417049/how-to-convert-an-inmemoryuploadedfile-in-django-to-a-fomat-for-flickr-api http://stackoverflow.com/questions/24373341/django-image-r... | Photo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Photo:
"""Class to manipulate image data References https://docs.djangoproject.com/en/1.10/_modules/django/core/files/uploadedfile/#InMemoryUploadedFile http://stackoverflow.com/questions/36417049/how-to-convert-an-inmemoryuploadedfile-in-django-to-a-fomat-for-flickr-api http://stackoverflow.com/... | stack_v2_sparse_classes_75kplus_train_069324 | 7,546 | no_license | [
{
"docstring": "Constructor :param file_object: object created using Python's open() :return: None",
"name": "__init__",
"signature": "def __init__(self, file_object)"
},
{
"docstring": "Return whether or not the image contains an icc_profile for ProPhoto RGB (ROMM) or AdobeRGB (1998) :param ima... | 6 | stack_v2_sparse_classes_30k_train_047325 | Implement the Python class `Photo` described below.
Class description:
Class to manipulate image data References https://docs.djangoproject.com/en/1.10/_modules/django/core/files/uploadedfile/#InMemoryUploadedFile http://stackoverflow.com/questions/36417049/how-to-convert-an-inmemoryuploadedfile-in-django-to-a-fomat-f... | Implement the Python class `Photo` described below.
Class description:
Class to manipulate image data References https://docs.djangoproject.com/en/1.10/_modules/django/core/files/uploadedfile/#InMemoryUploadedFile http://stackoverflow.com/questions/36417049/how-to-convert-an-inmemoryuploadedfile-in-django-to-a-fomat-f... | 38a09ce2fe68312338c8cb597a341853901eeaa3 | <|skeleton|>
class Photo:
"""Class to manipulate image data References https://docs.djangoproject.com/en/1.10/_modules/django/core/files/uploadedfile/#InMemoryUploadedFile http://stackoverflow.com/questions/36417049/how-to-convert-an-inmemoryuploadedfile-in-django-to-a-fomat-for-flickr-api http://stackoverflow.com/... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Photo:
"""Class to manipulate image data References https://docs.djangoproject.com/en/1.10/_modules/django/core/files/uploadedfile/#InMemoryUploadedFile http://stackoverflow.com/questions/36417049/how-to-convert-an-inmemoryuploadedfile-in-django-to-a-fomat-for-flickr-api http://stackoverflow.com/questions/243... | the_stack_v2_python_sparse | apps/photo/photo.py | AOV-Team/aov-py-backend | train | 0 |
9493280b40e7ed202a6d586bb602962a14286424 | [
"def creatTree(nums, l, r):\n if l > r:\n return None\n if l == r:\n node = Node(l, r)\n node.sum = nums[l]\n return node\n mid = (l + r) // 2\n root = Node(l, r)\n root.left = creatTree(nums, l, mid)\n root.right = creatTree(nums, mid + 1, r)\n root.sum = root.left.... | <|body_start_0|>
def creatTree(nums, l, r):
if l > r:
return None
if l == r:
node = Node(l, r)
node.sum = nums[l]
return node
mid = (l + r) // 2
root = Node(l, r)
root.left = creatTree(num... | Trickery Answer def __init__(self, nums): self.update = nums.__setitem__ self.sumRange = lambda i, j: sum(nums[i:j+1]) | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
"""Trickery Answer def __init__(self, nums): self.update = nums.__setitem__ self.sumRange = lambda i, j: sum(nums[i:j+1])"""
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype... | stack_v2_sparse_classes_75kplus_train_069325 | 2,486 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_007346 | Implement the Python class `NumArray` described below.
Class description:
Trickery Answer def __init__(self, nums): self.update = nums.__setitem__ self.sumRange = lambda i, j: sum(nums[i:j+1])
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int ... | Implement the Python class `NumArray` described below.
Class description:
Trickery Answer def __init__(self, nums): self.update = nums.__setitem__ self.sumRange = lambda i, j: sum(nums[i:j+1])
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int ... | 215d12703b2cac4c1ad49d5a0e1060948fbbacd2 | <|skeleton|>
class NumArray:
"""Trickery Answer def __init__(self, nums): self.update = nums.__setitem__ self.sumRange = lambda i, j: sum(nums[i:j+1])"""
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
"""Trickery Answer def __init__(self, nums): self.update = nums.__setitem__ self.sumRange = lambda i, j: sum(nums[i:j+1])"""
def __init__(self, nums):
""":type nums: List[int]"""
def creatTree(nums, l, r):
if l > r:
return None
if l == r:
... | the_stack_v2_python_sparse | 307. Range Sum Query - Mutable.py | Garacc/LeetCode | train | 0 |
796581fd81ee91aea76180e8a2ba839bf56cd1e4 | [
"self.G = G.copy()\nself.S = import_simplices(map(tuple, list(nx.find_cliques(self.G))))\nself.v = list(n_faces(self.S, 0))\nself.e = list(n_faces(self.S, 1))\nself.tri = list(n_faces(self.S, 2))\nself.tetra = list(n_faces(self.S, 3))",
"forman_dict = dict()\nif p > 1:\n for i in range(len(self.S)):\n i... | <|body_start_0|>
self.G = G.copy()
self.S = import_simplices(map(tuple, list(nx.find_cliques(self.G))))
self.v = list(n_faces(self.S, 0))
self.e = list(n_faces(self.S, 1))
self.tri = list(n_faces(self.S, 2))
self.tetra = list(n_faces(self.S, 3))
<|end_body_0|>
<|body_sta... | GeneralisedFormanRicci | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralisedFormanRicci:
def __init__(self, G: nx.Graph):
"""A class to compute Generalised Forman-Ricci curvature for a Vietoris Rips Complex from a given NetworkX graph up to a specified p-dimensional simplex. Parameters ---------- G : NetworkX graph"""
<|body_0|>
def compu... | stack_v2_sparse_classes_75kplus_train_069326 | 5,326 | no_license | [
{
"docstring": "A class to compute Generalised Forman-Ricci curvature for a Vietoris Rips Complex from a given NetworkX graph up to a specified p-dimensional simplex. Parameters ---------- G : NetworkX graph",
"name": "__init__",
"signature": "def __init__(self, G: nx.Graph)"
},
{
"docstring": "... | 2 | null | Implement the Python class `GeneralisedFormanRicci` described below.
Class description:
Implement the GeneralisedFormanRicci class.
Method signatures and docstrings:
- def __init__(self, G: nx.Graph): A class to compute Generalised Forman-Ricci curvature for a Vietoris Rips Complex from a given NetworkX graph up to a... | Implement the Python class `GeneralisedFormanRicci` described below.
Class description:
Implement the GeneralisedFormanRicci class.
Method signatures and docstrings:
- def __init__(self, G: nx.Graph): A class to compute Generalised Forman-Ricci curvature for a Vietoris Rips Complex from a given NetworkX graph up to a... | e6fc0dcf3795834b3b065ea75f443aee81e28718 | <|skeleton|>
class GeneralisedFormanRicci:
def __init__(self, G: nx.Graph):
"""A class to compute Generalised Forman-Ricci curvature for a Vietoris Rips Complex from a given NetworkX graph up to a specified p-dimensional simplex. Parameters ---------- G : NetworkX graph"""
<|body_0|>
def compu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeneralisedFormanRicci:
def __init__(self, G: nx.Graph):
"""A class to compute Generalised Forman-Ricci curvature for a Vietoris Rips Complex from a given NetworkX graph up to a specified p-dimensional simplex. Parameters ---------- G : NetworkX graph"""
self.G = G.copy()
self.S = impo... | the_stack_v2_python_sparse | lhx/res/10.6/files/ExpectozJJ/GeneralisedFormanRicci/c5274e7/GeneralisedFormanRicci.py | xinhecuican/githubDB_work | train | 0 | |
6d48dd19fccb3862c220a504691e97539bddc793 | [
"offset = request.args.get('offset', 0)\nlimit = request.args.get('limit', 10)\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nsearch_params = get_search_params(request.args, ['title', 'description'])\nreturn dal.project.paged(offset, limit, order_by, order, search_params)"... | <|body_start_0|>
offset = request.args.get('offset', 0)
limit = request.args.get('limit', 10)
order_by = request.args.get('order_by', 'id')
order = request.args.get('order', 'ASC')
search_params = get_search_params(request.args, ['title', 'description'])
return dal.projec... | ProjectsCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsCollection:
def get(self):
"""Returns list of projects."""
<|body_0|>
def post(self):
"""Creates a new provider."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
offset = request.args.get('offset', 0)
limit = request.args.get('limit',... | stack_v2_sparse_classes_75kplus_train_069327 | 7,995 | no_license | [
{
"docstring": "Returns list of projects.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates a new provider.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041649 | Implement the Python class `ProjectsCollection` described below.
Class description:
Implement the ProjectsCollection class.
Method signatures and docstrings:
- def get(self): Returns list of projects.
- def post(self): Creates a new provider. | Implement the Python class `ProjectsCollection` described below.
Class description:
Implement the ProjectsCollection class.
Method signatures and docstrings:
- def get(self): Returns list of projects.
- def post(self): Creates a new provider.
<|skeleton|>
class ProjectsCollection:
def get(self):
"""Retu... | 527231a4a2747ffc87ed86299cc02b8361d49c9c | <|skeleton|>
class ProjectsCollection:
def get(self):
"""Returns list of projects."""
<|body_0|>
def post(self):
"""Creates a new provider."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectsCollection:
def get(self):
"""Returns list of projects."""
offset = request.args.get('offset', 0)
limit = request.args.get('limit', 10)
order_by = request.args.get('order_by', 'id')
order = request.args.get('order', 'ASC')
search_params = get_search_para... | the_stack_v2_python_sparse | obras/service/genl/endpoints/projects.py | pianodaemon/SJO | train | 0 | |
8e91477659ed84e3aa93bf99df0ce0fb1a7f1df4 | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nl, h = bounds\nself.X_s = np.linspace(l, h, num=ac_samples)[:, np.newaxis]\nself.xsi = xsi\nself.minimize = minimize",
"from scipy.stats import norm\nmu, sigma = self.gp.predict(self.X_s)\nmu_sample, _ = self.gp.predict(self.gp.X)\nif self.minimize is True:\n... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
l, h = bounds
self.X_s = np.linspace(l, h, num=ac_samples)[:, np.newaxis]
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
from scipy.stats import norm
mu, sigma =... | performs Bayesian optimization on a noiseless 1D Gaussian process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""f is the black-box function to be optimized X_init ndarray (t, 1) inputs already sample... | stack_v2_sparse_classes_75kplus_train_069328 | 3,329 | no_license | [
{
"docstring": "f is the black-box function to be optimized X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of black-box function for each input in X_init t is the number of initial samples bounds tuple (min, max) representing the bounds of the space in which t... | 2 | null | Implement the Python class `BayesianOptimization` described below.
Class description:
performs Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): f is the black-box function to... | Implement the Python class `BayesianOptimization` described below.
Class description:
performs Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): f is the black-box function to... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class BayesianOptimization:
"""performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""f is the black-box function to be optimized X_init ndarray (t, 1) inputs already sample... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesianOptimization:
"""performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""f is the black-box function to be optimized X_init ndarray (t, 1) inputs already sampled with black-... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/4-bayes_opt.py | icculp/holbertonschool-machine_learning | train | 0 |
b92cfcd02a639f8d00ee8806c67415a63e09dccc | [
"username = getpass.getuser()\nself.root_directory = general.root_directory()\nself.infoset_user_exists = True\nself.infoset_user = None\nself.running_as_root = False\nif username == 'root':\n self.running_as_root = True\n try:\n self.infoset_user = input('Please enter the username under which infoset-... | <|body_start_0|>
username = getpass.getuser()
self.root_directory = general.root_directory()
self.infoset_user_exists = True
self.infoset_user = None
self.running_as_root = False
if username == 'root':
self.running_as_root = True
try:
... | Class to setup infoset-ng daemon. | _Daemon | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Daemon:
"""Class to setup infoset-ng daemon."""
def __init__(self):
"""Function for intializing the class. Args: None Returns: None"""
<|body_0|>
def setup(self):
"""Setup daemon scripts and file permissions. Args: None Returns: None"""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_069329 | 20,450 | permissive | [
{
"docstring": "Function for intializing the class. Args: None Returns: None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Setup daemon scripts and file permissions. Args: None Returns: None",
"name": "setup",
"signature": "def setup(self)"
},
{
"docs... | 5 | stack_v2_sparse_classes_30k_train_025486 | Implement the Python class `_Daemon` described below.
Class description:
Class to setup infoset-ng daemon.
Method signatures and docstrings:
- def __init__(self): Function for intializing the class. Args: None Returns: None
- def setup(self): Setup daemon scripts and file permissions. Args: None Returns: None
- def _... | Implement the Python class `_Daemon` described below.
Class description:
Class to setup infoset-ng daemon.
Method signatures and docstrings:
- def __init__(self): Function for intializing the class. Args: None Returns: None
- def setup(self): Setup daemon scripts and file permissions. Args: None Returns: None
- def _... | bac6f7e2157bea76ce882e8dab320d24b66bb718 | <|skeleton|>
class _Daemon:
"""Class to setup infoset-ng daemon."""
def __init__(self):
"""Function for intializing the class. Args: None Returns: None"""
<|body_0|>
def setup(self):
"""Setup daemon scripts and file permissions. Args: None Returns: None"""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Daemon:
"""Class to setup infoset-ng daemon."""
def __init__(self):
"""Function for intializing the class. Args: None Returns: None"""
username = getpass.getuser()
self.root_directory = general.root_directory()
self.infoset_user_exists = True
self.infoset_user = N... | the_stack_v2_python_sparse | setup.py | Quantum99/infoset-ng | train | 1 |
e95597e1994587cf9ce83131016915ae184582ed | [
"include = option.search if option.search else include\nif include:\n match = True if self.isIp(include, True) else match\nahost, nhost = ({}, {})\nhost_key = ['name', 'ip', 'user', 'passwd', 'port', 'sudo']\nkey, ikey = (1, 1)\nincludes = self.getArgs(include)\nwith open(self.sshfile) as rhost:\n for line in... | <|body_start_0|>
include = option.search if option.search else include
if include:
match = True if self.isIp(include, True) else match
ahost, nhost = ({}, {})
host_key = ['name', 'ip', 'user', 'passwd', 'port', 'sudo']
key, ikey = (1, 1)
includes = self.getArg... | 暂时保留 | BaseHandle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHandle:
"""暂时保留"""
def oldGetHost(self, include=None, pattern=False, match=False):
"""获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)"""
<|body_0|>
def searchHost(self, include=None, pattern=False, match=False):
"""... | stack_v2_sparse_classes_75kplus_train_069330 | 5,633 | no_license | [
{
"docstring": "获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)",
"name": "oldGetHost",
"signature": "def oldGetHost(self, include=None, pattern=False, match=False)"
},
{
"docstring": "获取主机信息, 基于sqlite3 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) m... | 2 | stack_v2_sparse_classes_30k_train_051697 | Implement the Python class `BaseHandle` described below.
Class description:
暂时保留
Method signatures and docstrings:
- def oldGetHost(self, include=None, pattern=False, match=False): 获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)
- def searchHost(self, include=None, pattern=... | Implement the Python class `BaseHandle` described below.
Class description:
暂时保留
Method signatures and docstrings:
- def oldGetHost(self, include=None, pattern=False, match=False): 获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)
- def searchHost(self, include=None, pattern=... | 2a4e1e71c9ac3ad3fceeaf9828a0f39d8f205bd8 | <|skeleton|>
class BaseHandle:
"""暂时保留"""
def oldGetHost(self, include=None, pattern=False, match=False):
"""获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)"""
<|body_0|>
def searchHost(self, include=None, pattern=False, match=False):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseHandle:
"""暂时保留"""
def oldGetHost(self, include=None, pattern=False, match=False):
"""获取主机信息,old数据 include : 用于过滤列表 pattern : 开启返回空字典,默认False(不返回) match : 开启精确匹配模式,默认False(模糊匹配)"""
include = option.search if option.search else include
if include:
match = True if se... | the_stack_v2_python_sparse | build/lib/antshell/install.py | ooppwwqq0/AntShell | train | 5 |
fe6aaff3bab333725621fdcdc7462e3a655d458a | [
"super().__init__(inp_n, lin_after_hidden_size, lin_before_hidden_size, lin_before_num_layers, lstm_hidden_size, lstm_num_layers, lin_after_hidden_size, lin_after_num_layers, activation_fn)\nlstm_in_n = lin_before_hidden_size if lin_before_num_layers > 0 else inp_n\nself.lstm = nn.LSTM(lstm_in_n, lin_after_hidden_s... | <|body_start_0|>
super().__init__(inp_n, lin_after_hidden_size, lin_before_hidden_size, lin_before_num_layers, lstm_hidden_size, lstm_num_layers, lin_after_hidden_size, lin_after_num_layers, activation_fn)
lstm_in_n = lin_before_hidden_size if lin_before_num_layers > 0 else inp_n
self.lstm = nn.... | A LSTM policy wth a gaussian head. | LSTMGaussianPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMGaussianPolicy:
"""A LSTM policy wth a gaussian head."""
def __init__(self, inp_n: int, out_n: int, lin_before_hidden_size: int, lin_before_num_layers: int, lstm_hidden_size: int, lstm_num_layers: int, lin_after_hidden_size: int, lin_after_num_layers: int, activation_fn: nn.Module, squis... | stack_v2_sparse_classes_75kplus_train_069331 | 10,329 | permissive | [
{
"docstring": "Creates the LSTM policy with a guassian head, with a linear policy before and after it. The LSTM is batch major. Args: inp_n: The number of input units. out_n: The number of output units. lin_before_hidden_size: The number of hidden units in the linear network before the LSTM. lin_before_num_lay... | 2 | null | Implement the Python class `LSTMGaussianPolicy` described below.
Class description:
A LSTM policy wth a gaussian head.
Method signatures and docstrings:
- def __init__(self, inp_n: int, out_n: int, lin_before_hidden_size: int, lin_before_num_layers: int, lstm_hidden_size: int, lstm_num_layers: int, lin_after_hidden_s... | Implement the Python class `LSTMGaussianPolicy` described below.
Class description:
A LSTM policy wth a gaussian head.
Method signatures and docstrings:
- def __init__(self, inp_n: int, out_n: int, lin_before_hidden_size: int, lin_before_num_layers: int, lstm_hidden_size: int, lstm_num_layers: int, lin_after_hidden_s... | cde3be1c69bfd76fe4a78fa529e851d0a78318c7 | <|skeleton|>
class LSTMGaussianPolicy:
"""A LSTM policy wth a gaussian head."""
def __init__(self, inp_n: int, out_n: int, lin_before_hidden_size: int, lin_before_num_layers: int, lstm_hidden_size: int, lstm_num_layers: int, lin_after_hidden_size: int, lin_after_num_layers: int, activation_fn: nn.Module, squis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTMGaussianPolicy:
"""A LSTM policy wth a gaussian head."""
def __init__(self, inp_n: int, out_n: int, lin_before_hidden_size: int, lin_before_num_layers: int, lstm_hidden_size: int, lstm_num_layers: int, lin_after_hidden_size: int, lin_after_num_layers: int, activation_fn: nn.Module, squished: Optional... | the_stack_v2_python_sparse | hlrl/torch/policies/recurrent.py | Chainso/HLRL | train | 3 |
0d5b0980006d7d84f441efd1bf72c8524f437176 | [
"super().__init__(parent=parent)\nself._plot = self.plotBar()\nself._title_template = Template(f'ROI Histogram (mean: $mean, median: $median, std: $std)')\nself.updateTitle()\nself.setLabel('left', 'Counts')\nself.setLabel('bottom', 'Pixel value')",
"hist = data.roi.hist\nif hist.hist is None:\n self.reset()\n... | <|body_start_0|>
super().__init__(parent=parent)
self._plot = self.plotBar()
self._title_template = Template(f'ROI Histogram (mean: $mean, median: $median, std: $std)')
self.updateTitle()
self.setLabel('left', 'Counts')
self.setLabel('bottom', 'Pixel value')
<|end_body_0|... | RoiHist class. Widget for visualizing the ROI histogram. | RoiHist | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoiHist:
"""RoiHist class. Widget for visualizing the ROI histogram."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def updateF(self, data):
"""Override."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(p... | stack_v2_sparse_classes_75kplus_train_069332 | 8,044 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, *, parent=None)"
},
{
"docstring": "Override.",
"name": "updateF",
"signature": "def updateF(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011452 | Implement the Python class `RoiHist` described below.
Class description:
RoiHist class. Widget for visualizing the ROI histogram.
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def updateF(self, data): Override. | Implement the Python class `RoiHist` described below.
Class description:
RoiHist class. Widget for visualizing the ROI histogram.
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def updateF(self, data): Override.
<|skeleton|>
class RoiHist:
"""RoiHist class. Widget for v... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class RoiHist:
"""RoiHist class. Widget for visualizing the ROI histogram."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def updateF(self, data):
"""Override."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoiHist:
"""RoiHist class. Widget for visualizing the ROI histogram."""
def __init__(self, *, parent=None):
"""Initialization."""
super().__init__(parent=parent)
self._plot = self.plotBar()
self._title_template = Template(f'ROI Histogram (mean: $mean, median: $median, std:... | the_stack_v2_python_sparse | extra_foam/gui/image_tool/corrected_view.py | European-XFEL/EXtra-foam | train | 8 |
078054ea8dfff7f4f7c5215f4990ff59e8fdcb94 | [
"if not hasattr(self, 'profile'):\n '将这行这整行数据挂到self身上,这行数据成了self的属性,例:self.profile.dating_gender'\n self.profile, _ = Profile.objects.get_or_create(id=self.id)\nreturn self.profile",
"\"\"\"检查当前会员是否过期\"\"\"\nnow = datetime.datetime.now()\nif now > self.vip_end:\n self.set_vip(1)\nif not hasattr(self, '_v... | <|body_start_0|>
if not hasattr(self, 'profile'):
'将这行这整行数据挂到self身上,这行数据成了self的属性,例:self.profile.dating_gender'
self.profile, _ = Profile.objects.get_or_create(id=self.id)
return self.profile
<|end_body_0|>
<|body_start_1|>
"""检查当前会员是否过期"""
now = datetime.datetim... | User | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def get_profile(self):
"""判断self身上是否有这个属性,如果没有说明是第一次,正常查询数据库,如果有就不必再次查询数据库,直接在属性例获取"""
<|body_0|>
def vip(self):
"""找到当前用户对应的VIP"""
<|body_1|>
def set_vip(self, vip_id):
"""设置当前用户的vip"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_069333 | 3,441 | permissive | [
{
"docstring": "判断self身上是否有这个属性,如果没有说明是第一次,正常查询数据库,如果有就不必再次查询数据库,直接在属性例获取",
"name": "get_profile",
"signature": "def get_profile(self)"
},
{
"docstring": "找到当前用户对应的VIP",
"name": "vip",
"signature": "def vip(self)"
},
{
"docstring": "设置当前用户的vip",
"name": "set_vip",
"signat... | 3 | stack_v2_sparse_classes_30k_test_000581 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def get_profile(self): 判断self身上是否有这个属性,如果没有说明是第一次,正常查询数据库,如果有就不必再次查询数据库,直接在属性例获取
- def vip(self): 找到当前用户对应的VIP
- def set_vip(self, vip_id): 设置当前用户的vip | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def get_profile(self): 判断self身上是否有这个属性,如果没有说明是第一次,正常查询数据库,如果有就不必再次查询数据库,直接在属性例获取
- def vip(self): 找到当前用户对应的VIP
- def set_vip(self, vip_id): 设置当前用户的vip
<|skeleton|>
class User:
def ... | 9d6653f07be0f6d1d8726cce15789e4fae729725 | <|skeleton|>
class User:
def get_profile(self):
"""判断self身上是否有这个属性,如果没有说明是第一次,正常查询数据库,如果有就不必再次查询数据库,直接在属性例获取"""
<|body_0|>
def vip(self):
"""找到当前用户对应的VIP"""
<|body_1|>
def set_vip(self, vip_id):
"""设置当前用户的vip"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User:
def get_profile(self):
"""判断self身上是否有这个属性,如果没有说明是第一次,正常查询数据库,如果有就不必再次查询数据库,直接在属性例获取"""
if not hasattr(self, 'profile'):
'将这行这整行数据挂到self身上,这行数据成了self的属性,例:self.profile.dating_gender'
self.profile, _ = Profile.objects.get_or_create(id=self.id)
return self.pr... | the_stack_v2_python_sparse | my_tt/UserApp/models.py | tanproject/tantan | train | 0 | |
5feb3dbf5dd1eb928654efc54b3027f2c7ee8866 | [
"self.nums = 0\nself.data = []\nself.dataSet = {}",
"if val not in self.dataSet:\n self.data.append(val)\n self.dataSet[val] = val\n self.nums += 1\n return True\nelse:\n return False",
"if val in self.dataSet:\n self.data.remove(val)\n del self.dataSet[val]\n self.nums -= 1\n return ... | <|body_start_0|>
self.nums = 0
self.data = []
self.dataSet = {}
<|end_body_0|>
<|body_start_1|>
if val not in self.dataSet:
self.data.append(val)
self.dataSet[val] = val
self.nums += 1
return True
else:
return False
<|e... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_75kplus_train_069334 | 1,475 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element.",
"name": "insert",
"signature": "def insert(self, val: int) ... | 4 | stack_v2_sparse_classes_30k_train_010956 | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | a42f45213c94d529f69a61f0bda92eddfe5bdfea | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.nums = 0
self.data = []
self.dataSet = {}
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""... | the_stack_v2_python_sparse | chap9/14.设计RamdomPool结构/O(N)_RandomizedSet.py | huang-jingwei/Coding-Interview-Guide | train | 6 | |
a6832174d98cc2b267356fe91659782d18214009 | [
"if self.column_to_check[self.column_to_check.isnull()].empty:\n if self.column_to_check[self.column_to_check == ''].empty:\n return True\n else:\n return False\nelse:\n return False",
"df_check_column = self.column_to_check.to_frame()\ndf_ref_column = self.ref_column.to_frame()\ndf_check_s... | <|body_start_0|>
if self.column_to_check[self.column_to_check.isnull()].empty:
if self.column_to_check[self.column_to_check == ''].empty:
return True
else:
return False
else:
return False
<|end_body_0|>
<|body_start_1|>
df_chec... | Check object represents a specific check on the data to be done having attributes as follows: - mandatory: a boolean attribute to indicate whether the check is mandatory to be passed or if it is just a warning - passed: A boolean attribute indicating if the check has passed or not. - type: one of the specified type che... | Check | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Check:
"""Check object represents a specific check on the data to be done having attributes as follows: - mandatory: a boolean attribute to indicate whether the check is mandatory to be passed or if it is just a warning - passed: A boolean attribute indicating if the check has passed or not. - ty... | stack_v2_sparse_classes_75kplus_train_069335 | 2,018 | no_license | [
{
"docstring": "check if all rows have values in them, i.e. neither empty nor none :return:",
"name": "rows_filled_check",
"signature": "def rows_filled_check(self)"
},
{
"docstring": ":return:",
"name": "fk_existence_check",
"signature": "def fk_existence_check(self)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_002955 | Implement the Python class `Check` described below.
Class description:
Check object represents a specific check on the data to be done having attributes as follows: - mandatory: a boolean attribute to indicate whether the check is mandatory to be passed or if it is just a warning - passed: A boolean attribute indicati... | Implement the Python class `Check` described below.
Class description:
Check object represents a specific check on the data to be done having attributes as follows: - mandatory: a boolean attribute to indicate whether the check is mandatory to be passed or if it is just a warning - passed: A boolean attribute indicati... | 84401e245b40f0a6412e14928f0a6d63a7ab2412 | <|skeleton|>
class Check:
"""Check object represents a specific check on the data to be done having attributes as follows: - mandatory: a boolean attribute to indicate whether the check is mandatory to be passed or if it is just a warning - passed: A boolean attribute indicating if the check has passed or not. - ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Check:
"""Check object represents a specific check on the data to be done having attributes as follows: - mandatory: a boolean attribute to indicate whether the check is mandatory to be passed or if it is just a warning - passed: A boolean attribute indicating if the check has passed or not. - type: one of th... | the_stack_v2_python_sparse | BTalaqa/Helpers/Check.py | driad91/BTalaqa | train | 0 |
596bc8597536b9a9f1e62cedb9af4b39ee6b70e8 | [
"dp = [amount + 1] * (amount + 1)\ndp[0] = 0\nfor i in range(amount):\n for j in range(len(coins)):\n if i + coins[j] > amount:\n continue\n dp[i + coins[j]] = min(dp[i] + 1, dp[i + coins[j]])\nreturn dp[-1] if dp[-1] <= amount else -1",
"level = 0\nqueue = [amount]\ncoins = sorted(coi... | <|body_start_0|>
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for i in range(amount):
for j in range(len(coins)):
if i + coins[j] > amount:
continue
dp[i + coins[j]] = min(dp[i] + 1, dp[i + coins[j]])
return dp[-1] if dp[-1] <... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int :BFS solution"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_069336 | 2,496 | permissive | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int :BFS solution",
"name": "coinChange2",
"signature": "def coinChange2(sel... | 2 | stack_v2_sparse_classes_30k_train_025652 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | aec1ddd0c51b619c1bae1e05f940d9ed587aa82f | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int :BFS solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for i in range(amount):
for j in range(len(coins)):
if i + coins[j] > amount:
con... | the_stack_v2_python_sparse | Python/leetcode/coinChange.py | darrencheng0817/AlgorithmLearning | train | 2 | |
02cd8633c51b3ecd6cf4086d14c5984a7cdb34c5 | [
"processed_dict = {}\nfor key, value in request.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nalipay = AliPay(appid=ALI_APP_ID, app_notify_url=ALIPAY_NOTIFY_URL, app_private_key_path=PRIVATE_KEY_PATH, alipay_public_key_path=ALI_PUB_KEY_PATH, debug=DEBUG, return_url=ALIPAY_R... | <|body_start_0|>
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid=ALI_APP_ID, app_notify_url=ALIPAY_NOTIFY_URL, app_private_key_path=PRIVATE_KEY_PATH, alipay_public_key_path=AL... | AlipayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlipayView:
def get(self, request, format=None):
"""处理支付宝的return_url返回 :param request: :return:"""
<|body_0|>
def post(self, request, format=None):
"""处理支付宝的notify_url :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processe... | stack_v2_sparse_classes_75kplus_train_069337 | 10,057 | no_license | [
{
"docstring": "处理支付宝的return_url返回 :param request: :return:",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "处理支付宝的notify_url :param request: :return:",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036428 | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request, format=None): 处理支付宝的return_url返回 :param request: :return:
- def post(self, request, format=None): 处理支付宝的notify_url :param request: :return: | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request, format=None): 处理支付宝的return_url返回 :param request: :return:
- def post(self, request, format=None): 处理支付宝的notify_url :param request: :return:
<|skeleton... | 25a568c5203d05a00bce139d084da6d7622b9956 | <|skeleton|>
class AlipayView:
def get(self, request, format=None):
"""处理支付宝的return_url返回 :param request: :return:"""
<|body_0|>
def post(self, request, format=None):
"""处理支付宝的notify_url :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlipayView:
def get(self, request, format=None):
"""处理支付宝的return_url返回 :param request: :return:"""
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid=ALI_APP_ID... | the_stack_v2_python_sparse | apps/trade/views.py | 846468230/store | train | 0 | |
5e4bbd1b4507232d0f71572761641c2777e26fee | [
"self.name = name\nself.emp_x = emp_x\nself.emp_n = emp_n\nself.chi2 = 0\nself.Ei = []",
"n = sum(self.emp_n)\nfor i in range(len(self.emp_x) - 1):\n tmp = norm(mean, math.sqrt(var)).cdf(self.emp_x[i]) * n\n tmp_1 = norm(mean, math.sqrt(var)).cdf(self.emp_x[i + 1]) * n\n self.Ei.append(tmp_1 - tmp)\ny = ... | <|body_start_0|>
self.name = name
self.emp_x = emp_x
self.emp_n = emp_n
self.chi2 = 0
self.Ei = []
<|end_body_0|>
<|body_start_1|>
n = sum(self.emp_n)
for i in range(len(self.emp_x) - 1):
tmp = norm(mean, math.sqrt(var)).cdf(self.emp_x[i]) * n
... | ChiSquare | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiSquare:
def __init__(self, emp_x, emp_n, name='default'):
"""Initialize chi square test with observations and their frequency. :param emp_x: observation values (bins) :param emp_n: frequency :param name: name for better distinction of tests"""
<|body_0|>
def test_distribu... | stack_v2_sparse_classes_75kplus_train_069338 | 2,833 | no_license | [
{
"docstring": "Initialize chi square test with observations and their frequency. :param emp_x: observation values (bins) :param emp_n: frequency :param name: name for better distinction of tests",
"name": "__init__",
"signature": "def __init__(self, emp_x, emp_n, name='default')"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_029116 | Implement the Python class `ChiSquare` described below.
Class description:
Implement the ChiSquare class.
Method signatures and docstrings:
- def __init__(self, emp_x, emp_n, name='default'): Initialize chi square test with observations and their frequency. :param emp_x: observation values (bins) :param emp_n: freque... | Implement the Python class `ChiSquare` described below.
Class description:
Implement the ChiSquare class.
Method signatures and docstrings:
- def __init__(self, emp_x, emp_n, name='default'): Initialize chi square test with observations and their frequency. :param emp_x: observation values (bins) :param emp_n: freque... | 1a5936c8c0fcd0d74b61941504f2c58669154c15 | <|skeleton|>
class ChiSquare:
def __init__(self, emp_x, emp_n, name='default'):
"""Initialize chi square test with observations and their frequency. :param emp_x: observation values (bins) :param emp_n: frequency :param name: name for better distinction of tests"""
<|body_0|>
def test_distribu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChiSquare:
def __init__(self, emp_x, emp_n, name='default'):
"""Initialize chi square test with observations and their frequency. :param emp_x: observation values (bins) :param emp_n: frequency :param name: name for better distinction of tests"""
self.name = name
self.emp_x = emp_x
... | the_stack_v2_python_sparse | DES_part6_03694565/DES_part6_03694565/statistictests.py | gundoganalperen/ams-des | train | 4 | |
526ad4e156c5957852e6b78b40c8bfd3dbefd133 | [
"loader = self.loader(self)\nobj = loader.get_object_from_deployfish(self.app.pargs.pk, factory_kwargs={'load_secrets': False})\ntasks = []\nconfig = self.app.deployfish_config.cooked\nif 'tasks' in config:\n for task_data in config['tasks']:\n if 'service' in task_data:\n if task_data['service... | <|body_start_0|>
loader = self.loader(self)
obj = loader.get_object_from_deployfish(self.app.pargs.pk, factory_kwargs={'load_secrets': False})
tasks = []
config = self.app.deployfish_config.cooked
if 'tasks' in config:
for task_data in config['tasks']:
... | ECSServiceStandaloneTasks | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ECSServiceStandaloneTasks:
def list_related_tasks(self):
"""List StandaloneTasks related to a Service from what we have in our deployfish.yml file. NOTE: This lists tasks defined under the top level 'tasks:' section in deployfish.yml. ServiceHelperTasks -- those defined by a 'tasks:' sec... | stack_v2_sparse_classes_75kplus_train_069339 | 16,032 | permissive | [
{
"docstring": "List StandaloneTasks related to a Service from what we have in our deployfish.yml file. NOTE: This lists tasks defined under the top level 'tasks:' section in deployfish.yml. ServiceHelperTasks -- those defined by a 'tasks:' section under the Service definition will not be listed here. IDENTIFIE... | 2 | null | Implement the Python class `ECSServiceStandaloneTasks` described below.
Class description:
Implement the ECSServiceStandaloneTasks class.
Method signatures and docstrings:
- def list_related_tasks(self): List StandaloneTasks related to a Service from what we have in our deployfish.yml file. NOTE: This lists tasks def... | Implement the Python class `ECSServiceStandaloneTasks` described below.
Class description:
Implement the ECSServiceStandaloneTasks class.
Method signatures and docstrings:
- def list_related_tasks(self): List StandaloneTasks related to a Service from what we have in our deployfish.yml file. NOTE: This lists tasks def... | caa4698da812f5291a47366f307c1abebb4a989c | <|skeleton|>
class ECSServiceStandaloneTasks:
def list_related_tasks(self):
"""List StandaloneTasks related to a Service from what we have in our deployfish.yml file. NOTE: This lists tasks defined under the top level 'tasks:' section in deployfish.yml. ServiceHelperTasks -- those defined by a 'tasks:' sec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ECSServiceStandaloneTasks:
def list_related_tasks(self):
"""List StandaloneTasks related to a Service from what we have in our deployfish.yml file. NOTE: This lists tasks defined under the top level 'tasks:' section in deployfish.yml. ServiceHelperTasks -- those defined by a 'tasks:' section under the... | the_stack_v2_python_sparse | deployfish/controllers/service.py | caltechads/deployfish | train | 98 | |
e1f1adea0a74380a433b20370dd4ef4fb09bf4b9 | [
"self.pathCKPT = PATH_TO_CKPT\nself.pathLabels = PATH_TO_LABELS\nself.numClasses = 3",
"with tf.device('/device:GPU:0'):\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(self.pathCKPT, 'rb') as fid:\n serialized... | <|body_start_0|>
self.pathCKPT = PATH_TO_CKPT
self.pathLabels = PATH_TO_LABELS
self.numClasses = 3
<|end_body_0|>
<|body_start_1|>
with tf.device('/device:GPU:0'):
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.G... | The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lights :ivar numClasses: number of classes used :iv... | TrafficLightDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lig... | stack_v2_sparse_classes_75kplus_train_069340 | 3,854 | no_license | [
{
"docstring": "Sets the paths to any necessary files for the neural network to function",
"name": "__init__",
"signature": "def __init__(self, PATH_TO_CKPT='tf/frozen_inference_graph.pb', PATH_TO_LABELS='tf/traffic_light.pbtxt')"
},
{
"docstring": "Performs all of the operations to set up the n... | 3 | stack_v2_sparse_classes_30k_train_025578 | Implement the Python class `TrafficLightDetector` described below.
Class description:
The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLab... | Implement the Python class `TrafficLightDetector` described below.
Class description:
The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLab... | 576b799fd6f85768cc4e0ad44b0a787fb5c80b29 | <|skeleton|>
class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lig... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lights :ivar num... | the_stack_v2_python_sparse | MV/trafficLightDetector.py | bohongbobo/draft-GUI | train | 0 |
0d88ef04ffd5c68290e2af0f5ae28d531353c4ad | [
"self.input_directory = input_directory\nself.save_directory = save_directory\nself.file_paths = []\nself.number_of_files = 0\nself.__folder_controller()\nself.__delete_non_merge_files()",
"for root, directory, files in os.walk(self.input_directory):\n for direc in directory:\n directory_path = os.path.... | <|body_start_0|>
self.input_directory = input_directory
self.save_directory = save_directory
self.file_paths = []
self.number_of_files = 0
self.__folder_controller()
self.__delete_non_merge_files()
<|end_body_0|>
<|body_start_1|>
for root, directory, files in os.... | Merge | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Merge:
def __init__(self, input_directory: str, save_directory: str):
"""This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatena... | stack_v2_sparse_classes_75kplus_train_069341 | 7,079 | no_license | [
{
"docstring": "This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatenate_files will perform the actual concatenation of files self.__folder_controller ... | 6 | stack_v2_sparse_classes_30k_train_007213 | Implement the Python class `Merge` described below.
Class description:
Implement the Merge class.
Method signatures and docstrings:
- def __init__(self, input_directory: str, save_directory: str): This class is responsible for methods that will combine multiple text files in one folder to create one file self.__creat... | Implement the Python class `Merge` described below.
Class description:
Implement the Merge class.
Method signatures and docstrings:
- def __init__(self, input_directory: str, save_directory: str): This class is responsible for methods that will combine multiple text files in one folder to create one file self.__creat... | 9ab650a460785adab085af523dec8ee8fa2105ba | <|skeleton|>
class Merge:
def __init__(self, input_directory: str, save_directory: str):
"""This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatena... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Merge:
def __init__(self, input_directory: str, save_directory: str):
"""This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatenate_files will ... | the_stack_v2_python_sparse | Scripts/MergeFiles.py | JoshLoecker/ARS | train | 0 | |
e113f9a749a04e5804511235165abd68c0e58f2a | [
"left = right = max_length = 0\nfor i in range(len(string)):\n if string[i] == '(':\n left += 1\n else:\n right += 1\n if left == right:\n max_length = max(max_length, right * 2)\n elif right > left:\n left = right = 0\nleft = right = 0\nfor i in range(len(string) - 1, -1, -1... | <|body_start_0|>
left = right = max_length = 0
for i in range(len(string)):
if string[i] == '(':
left += 1
else:
right += 1
if left == right:
max_length = max(max_length, right * 2)
elif right > left:
... | Parentheses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parentheses:
def find_longest_valid_parentheses(self, string: str) -> int:
"""Approach: Using 2 pointers with no extra space Time Complexity: O(n) Space Complexity: O(1) :param string: :return:"""
<|body_0|>
def find_longest_valid_parentheses_(self, string: str) -> int:
... | stack_v2_sparse_classes_75kplus_train_069342 | 3,465 | no_license | [
{
"docstring": "Approach: Using 2 pointers with no extra space Time Complexity: O(n) Space Complexity: O(1) :param string: :return:",
"name": "find_longest_valid_parentheses",
"signature": "def find_longest_valid_parentheses(self, string: str) -> int"
},
{
"docstring": "Approach: Using Stack Tim... | 3 | stack_v2_sparse_classes_30k_train_042777 | Implement the Python class `Parentheses` described below.
Class description:
Implement the Parentheses class.
Method signatures and docstrings:
- def find_longest_valid_parentheses(self, string: str) -> int: Approach: Using 2 pointers with no extra space Time Complexity: O(n) Space Complexity: O(1) :param string: :re... | Implement the Python class `Parentheses` described below.
Class description:
Implement the Parentheses class.
Method signatures and docstrings:
- def find_longest_valid_parentheses(self, string: str) -> int: Approach: Using 2 pointers with no extra space Time Complexity: O(n) Space Complexity: O(1) :param string: :re... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Parentheses:
def find_longest_valid_parentheses(self, string: str) -> int:
"""Approach: Using 2 pointers with no extra space Time Complexity: O(n) Space Complexity: O(1) :param string: :return:"""
<|body_0|>
def find_longest_valid_parentheses_(self, string: str) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parentheses:
def find_longest_valid_parentheses(self, string: str) -> int:
"""Approach: Using 2 pointers with no extra space Time Complexity: O(n) Space Complexity: O(1) :param string: :return:"""
left = right = max_length = 0
for i in range(len(string)):
if string[i] == '(... | the_stack_v2_python_sparse | math_and_srings/longest_valid_parantheses.py | Shiv2157k/leet_code | train | 1 | |
173fb484727d9a786ec78d415450b70bf551dd0e | [
"from collections import deque\nstack = deque()\nprev = TreeNode(float('-inf'))\nwhile root or len(stack) > 0:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n if prev.val >= root.val:\n return False\n prev = root\n root = root.right\nreturn True",
"... | <|body_start_0|>
from collections import deque
stack = deque()
prev = TreeNode(float('-inf'))
while root or len(stack) > 0:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if prev.val >= root.val:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""Iterative solution (Inorder traversal)"""
<|body_0|>
def isValidBST_2(self, root: TreeNode) -> bool:
"""Recursive solution, with INT_MAX and INT_MIN"""
<|body_1|>
def isValidBST(self, root: TreeN... | stack_v2_sparse_classes_75kplus_train_069343 | 1,551 | no_license | [
{
"docstring": "Iterative solution (Inorder traversal)",
"name": "isValidBST",
"signature": "def isValidBST(self, root: TreeNode) -> bool"
},
{
"docstring": "Recursive solution, with INT_MAX and INT_MIN",
"name": "isValidBST_2",
"signature": "def isValidBST_2(self, root: TreeNode) -> boo... | 3 | stack_v2_sparse_classes_30k_train_012121 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root: TreeNode) -> bool: Iterative solution (Inorder traversal)
- def isValidBST_2(self, root: TreeNode) -> bool: Recursive solution, with INT_MAX and INT_MI... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root: TreeNode) -> bool: Iterative solution (Inorder traversal)
- def isValidBST_2(self, root: TreeNode) -> bool: Recursive solution, with INT_MAX and INT_MI... | 20a48021be5e5348d681e910c843e734df98b596 | <|skeleton|>
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""Iterative solution (Inorder traversal)"""
<|body_0|>
def isValidBST_2(self, root: TreeNode) -> bool:
"""Recursive solution, with INT_MAX and INT_MIN"""
<|body_1|>
def isValidBST(self, root: TreeN... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""Iterative solution (Inorder traversal)"""
from collections import deque
stack = deque()
prev = TreeNode(float('-inf'))
while root or len(stack) > 0:
while root:
stack.append(root)
... | the_stack_v2_python_sparse | validate_bst/validate_bst.py | narnat/leetcode | train | 0 | |
790b9423c40f65c36525e9231df26abb27a7b0a4 | [
"opto = optometre_public_page.OptometrePublicPage(self.driver)\nopto.to_opto_sale()\ntime.sleep(1)\nself.sendKeys(self.user, text=user_name)\ntime.sleep(2)\nself.sendKeys(self.user, Keys.DOWN)\ntime.sleep(1)\nself.sendKeys(self.user, Keys.ENTER)",
"self.click(self.to_sale)\ntime.sleep(1)\nself.click(self.add_pro)... | <|body_start_0|>
opto = optometre_public_page.OptometrePublicPage(self.driver)
opto.to_opto_sale()
time.sleep(1)
self.sendKeys(self.user, text=user_name)
time.sleep(2)
self.sendKeys(self.user, Keys.DOWN)
time.sleep(1)
self.sendKeys(self.user, Keys.ENTER)
<... | 视光销售页面相关元素 | OptometreSalesPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptometreSalesPage:
"""视光销售页面相关元素"""
def query_users(self, user_name='测试012'):
"""查询用户"""
<|body_0|>
def draw_a_bill(self):
"""销售开单"""
<|body_1|>
def add_optometry_record(self, near_od='+12.00', near_os='+12.00'):
"""新增验光记录"""
<|body_... | stack_v2_sparse_classes_75kplus_train_069344 | 5,702 | no_license | [
{
"docstring": "查询用户",
"name": "query_users",
"signature": "def query_users(self, user_name='测试012')"
},
{
"docstring": "销售开单",
"name": "draw_a_bill",
"signature": "def draw_a_bill(self)"
},
{
"docstring": "新增验光记录",
"name": "add_optometry_record",
"signature": "def add_op... | 5 | stack_v2_sparse_classes_30k_train_046844 | Implement the Python class `OptometreSalesPage` described below.
Class description:
视光销售页面相关元素
Method signatures and docstrings:
- def query_users(self, user_name='测试012'): 查询用户
- def draw_a_bill(self): 销售开单
- def add_optometry_record(self, near_od='+12.00', near_os='+12.00'): 新增验光记录
- def delete_optometry_record(sel... | Implement the Python class `OptometreSalesPage` described below.
Class description:
视光销售页面相关元素
Method signatures and docstrings:
- def query_users(self, user_name='测试012'): 查询用户
- def draw_a_bill(self): 销售开单
- def add_optometry_record(self, near_od='+12.00', near_os='+12.00'): 新增验光记录
- def delete_optometry_record(sel... | 8616e6a320462747006a8ed9a7066e367660a7c5 | <|skeleton|>
class OptometreSalesPage:
"""视光销售页面相关元素"""
def query_users(self, user_name='测试012'):
"""查询用户"""
<|body_0|>
def draw_a_bill(self):
"""销售开单"""
<|body_1|>
def add_optometry_record(self, near_od='+12.00', near_os='+12.00'):
"""新增验光记录"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptometreSalesPage:
"""视光销售页面相关元素"""
def query_users(self, user_name='测试012'):
"""查询用户"""
opto = optometre_public_page.OptometrePublicPage(self.driver)
opto.to_opto_sale()
time.sleep(1)
self.sendKeys(self.user, text=user_name)
time.sleep(2)
self.sen... | the_stack_v2_python_sparse | uitest/pages/optometry/sale_management/optometre_sales_page.py | QWJ77/big | train | 0 |
d399e0bb128610d03b40bebb7217c88931c6c54c | [
"super().__init__(parent)\nself.gui = parent.parent()\nQTimer.singleShot(200, self.style_me)",
"self.horizontalHeader().show()\nself.verticalHeader().hide()\nself.setAutoScroll(False)\nself.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)\nself.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)",
... | <|body_start_0|>
super().__init__(parent)
self.gui = parent.parent()
QTimer.singleShot(200, self.style_me)
<|end_body_0|>
<|body_start_1|>
self.horizontalHeader().show()
self.verticalHeader().hide()
self.setAutoScroll(False)
self.setVerticalScrollMode(QAbstractIt... | Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView | RightClickView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RightClickView:
"""Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView"""
def __init__(self, parent):
"""Provide access to GUI QMain... | stack_v2_sparse_classes_75kplus_train_069345 | 4,207 | permissive | [
{
"docstring": "Provide access to GUI QMainWindow via parent.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Style this widget.",
"name": "style_me",
"signature": "def style_me(self)"
},
{
"docstring": "Create options for drop-down context menu... | 6 | stack_v2_sparse_classes_30k_test_000648 | Implement the Python class `RightClickView` described below.
Class description:
Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView
Method signatures and docstrings:
... | Implement the Python class `RightClickView` described below.
Class description:
Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView
Method signatures and docstrings:
... | 24c58d192a576f25acb8d4208a92a317d0ebb2fd | <|skeleton|>
class RightClickView:
"""Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView"""
def __init__(self, parent):
"""Provide access to GUI QMain... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RightClickView:
"""Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView"""
def __init__(self, parent):
"""Provide access to GUI QMainWindow via pa... | the_stack_v2_python_sparse | qiskit_metal/_gui/widgets/variable_table/right_click_table_view.py | jessica-angel7/qiskit-metal | train | 1 |
8a533219aa03c524c720b82351c1350bae4d5db5 | [
"self._image = str(image)\nself._nodes = int(nodes)\nself._cores_per_node = int(cores_per_node)\nself._mem_per_core = str(mem_per_core)\nself._gpus_per_node = int(gpus_per_node)\nif shape is not None:\n self._shape = str(shape)\nelse:\n self._shape = None\nself._tmp_disk_per_node = str(tmp_disk_per_node)\nsel... | <|body_start_0|>
self._image = str(image)
self._nodes = int(nodes)
self._cores_per_node = int(cores_per_node)
self._mem_per_core = str(mem_per_core)
self._gpus_per_node = int(gpus_per_node)
if shape is not None:
self._shape = str(shape)
else:
... | This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc. | Resources | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resources:
"""This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc."""
... | stack_v2_sparse_classes_75kplus_train_069346 | 2,450 | permissive | [
{
"docstring": "Construct a set of resources specifying everything that may be needed to obtain sufficient resource to run a job",
"name": "__init__",
"signature": "def __init__(self, image=None, nodes=1, cores_per_node=1, mem_per_core='100MB', gpus_per_node=0, shape=None, tmp_disk_per_node='4GB', scrat... | 3 | stack_v2_sparse_classes_30k_train_028883 | Implement the Python class `Resources` described below.
Class description:
This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the am... | Implement the Python class `Resources` described below.
Class description:
This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the am... | fe4c9cb2b90374b386d5ea38e514faa96661701a | <|skeleton|>
class Resources:
"""This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resources:
"""This class holds the full set of requestable resources needed for a Job submitted to the system. This includes the container URL for any container images used by the job, the number of nodes and processors, the amount of memory per node, the amount of disk space needed etc."""
def __init__(... | the_stack_v2_python_sparse | Acquire/Client/_resources.py | chryswoods/acquire | train | 21 |
ad348972f1000131c537436478b1d79b9c00950b | [
"self.num_filters = num_filters\nself._build_layer_components()\nsuper(ReductionA, self).__init__(**kwargs)",
"self.max_pool1 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid')\nself.conv_block1 = [Conv2D(int(self.num_filters * 1.5), kernel_size=(3, 3), strides=2, padding='valid', activation=tf.nn.relu)]\n... | <|body_start_0|>
self.num_filters = num_filters
self._build_layer_components()
super(ReductionA, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
self.max_pool1 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid')
self.conv_block1 = [Conv2D(int(self.num_filters * 1.... | Variant A of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers. | ReductionA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReductionA:
"""Variant A of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers."... | stack_v2_sparse_classes_75kplus_train_069347 | 17,354 | permissive | [
{
"docstring": "Parameters ---------- num_filters: int, Number of convolutional filters",
"name": "__init__",
"signature": "def __init__(self, num_filters, **kwargs)"
},
{
"docstring": "Builds the layers components and set _layers attribute.",
"name": "_build_layer_components",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_052642 | Implement the Python class `ReductionA` described below.
Class description:
Variant A of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computati... | Implement the Python class `ReductionA` described below.
Class description:
Variant A of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computati... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class ReductionA:
"""Variant A of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReductionA:
"""Variant A of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers."""
def _... | the_stack_v2_python_sparse | deepchem/models/chemnet_layers.py | deepchem/deepchem | train | 4,876 |
50ffd45f9ec308ec095f64d039174c1f931aa207 | [
"if hasattr(self, 'action_serializers'):\n if self.action in self.action_serializers:\n return self.action_serializers[self.action]\nreturn super(AppointmentView, self).get_serializer_class()",
"queryset = self.filter_queryset(self.get_queryset())\nif get_boolean_value(request.GET.get('paginate', 'true'... | <|body_start_0|>
if hasattr(self, 'action_serializers'):
if self.action in self.action_serializers:
return self.action_serializers[self.action]
return super(AppointmentView, self).get_serializer_class()
<|end_body_0|>
<|body_start_1|>
queryset = self.filter_queryset(... | Appointment View | AppointmentView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppointmentView:
"""Appointment View"""
def get_serializer_class(self):
"""Retrieve the appropriate serializer for every request method"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List Appointments"""
<|body_1|>
def create(self, reques... | stack_v2_sparse_classes_75kplus_train_069348 | 3,399 | no_license | [
{
"docstring": "Retrieve the appropriate serializer for every request method",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List Appointments",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_003250 | Implement the Python class `AppointmentView` described below.
Class description:
Appointment View
Method signatures and docstrings:
- def get_serializer_class(self): Retrieve the appropriate serializer for every request method
- def list(self, request, *args, **kwargs): List Appointments
- def create(self, request, *... | Implement the Python class `AppointmentView` described below.
Class description:
Appointment View
Method signatures and docstrings:
- def get_serializer_class(self): Retrieve the appropriate serializer for every request method
- def list(self, request, *args, **kwargs): List Appointments
- def create(self, request, *... | 3a849556e44eb2a12debc9ee2b0b31f5b98905b1 | <|skeleton|>
class AppointmentView:
"""Appointment View"""
def get_serializer_class(self):
"""Retrieve the appropriate serializer for every request method"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List Appointments"""
<|body_1|>
def create(self, reques... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppointmentView:
"""Appointment View"""
def get_serializer_class(self):
"""Retrieve the appropriate serializer for every request method"""
if hasattr(self, 'action_serializers'):
if self.action in self.action_serializers:
return self.action_serializers[self.act... | the_stack_v2_python_sparse | app_appointment/views.py | hachiman144/bookdoc-api | train | 0 |
3724d6f00822427e3252c6c4eadfc53cd90bdc30 | [
"m = len(y)\nsum_of_square_errors = np.square(np.dot(X, self.w) - y).sum()\ncost = sum_of_square_errors / (2 * m)\nreturn cost",
"tic = time.time()\nif self.train_type == 'Parallel':\n self.w = self.w_hat\n count = 0\n tic = time.time()\n for i in range(self.torque):\n count += 1\n loss ... | <|body_start_0|>
m = len(y)
sum_of_square_errors = np.square(np.dot(X, self.w) - y).sum()
cost = sum_of_square_errors / (2 * m)
return cost
<|end_body_0|>
<|body_start_1|>
tic = time.time()
if self.train_type == 'Parallel':
self.w = self.w_hat
cou... | LinearRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegression:
def compute_loss(self, X, y):
"""Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss"""
<|body_0|>
def fit(self, X, y):
"""Implement l2-linear regression by Grad... | stack_v2_sparse_classes_75kplus_train_069349 | 2,582 | no_license | [
{
"docstring": "Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss",
"name": "compute_loss",
"signature": "def compute_loss(self, X, y)"
},
{
"docstring": "Implement l2-linear regression by Gradient descent.... | 2 | stack_v2_sparse_classes_30k_train_040380 | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def compute_loss(self, X, y): Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Return... | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def compute_loss(self, X, y): Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Return... | 4d1e09ddbb84b7fdc23e030edd8cd833824c1b9f | <|skeleton|>
class LinearRegression:
def compute_loss(self, X, y):
"""Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss"""
<|body_0|>
def fit(self, X, y):
"""Implement l2-linear regression by Grad... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearRegression:
def compute_loss(self, X, y):
"""Computing loss according to OLS Args: X: Features, shape = (# of samples, # of features) y: Target, shape = (1, # of samples) Returns: loss"""
m = len(y)
sum_of_square_errors = np.square(np.dot(X, self.w) - y).sum()
cost = sum_... | the_stack_v2_python_sparse | classifier/linearRegression.py | BiggyBing/Parallel | train | 2 | |
4deb60a43cdf0d480ae614b0e67c28b0b242d8e0 | [
"if len(labels.shape) <= 2:\n return self._gather_unbatched(labels, match_indices, mask, mask_val)\nelif len(labels.shape) == 3:\n return self._gather_batched(labels, match_indices, mask, mask_val)\nelse:\n raise ValueError('`TargetGather` does not support `labels` with rank larger than 3, got {}'.format(l... | <|body_start_0|>
if len(labels.shape) <= 2:
return self._gather_unbatched(labels, match_indices, mask, mask_val)
elif len(labels.shape) == 3:
return self._gather_batched(labels, match_indices, mask, mask_val)
else:
raise ValueError('`TargetGather` does not sup... | Targer gather for dense object detector. | TargetGather | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetGather:
"""Targer gather for dense object detector."""
def __call__(self, labels, match_indices, mask=None, mask_val=0.0):
"""Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ..... | stack_v2_sparse_classes_75kplus_train_069350 | 4,035 | permissive | [
{
"docstring": "Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ...] representing groundtruth labels. match_indices: An integer tensor with shape [M] or [B, M] representing match label index. mask: An boolean t... | 3 | stack_v2_sparse_classes_30k_train_015319 | Implement the Python class `TargetGather` described below.
Class description:
Targer gather for dense object detector.
Method signatures and docstrings:
- def __call__(self, labels, match_indices, mask=None, mask_val=0.0): Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: la... | Implement the Python class `TargetGather` described below.
Class description:
Targer gather for dense object detector.
Method signatures and docstrings:
- def __call__(self, labels, match_indices, mask=None, mask_val=0.0): Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: la... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class TargetGather:
"""Targer gather for dense object detector."""
def __call__(self, labels, match_indices, mask=None, mask_val=0.0):
"""Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ..... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TargetGather:
"""Targer gather for dense object detector."""
def __call__(self, labels, match_indices, mask=None, mask_val=0.0):
"""Labels anchors with ground truth inputs. B: batch_size N: number of groundtruth boxes. Args: labels: An integer tensor with shape [N, dims] or [B, N, ...] representi... | the_stack_v2_python_sparse | models/official/vision/keras_cv/ops/target_gather.py | aboerzel/German_License_Plate_Recognition | train | 34 |
3964b6d4e04d40c472c1ebb22f14b9c7fa01fce7 | [
"lines = self._read_tsv(os.path.join(data_dir, 'train.tsv'))\nexamples = []\nfor i, line in enumerate(lines):\n guid = '%s-%s' % ('train', i)\n text_a = line[0]\n label = line[1].split(' ')\n examples.append(NERInputExample(guid=guid, text_a=text_a, label=label))\nreturn examples",
"lines = self._read... | <|body_start_0|>
lines = self._read_tsv(os.path.join(data_dir, 'train.tsv'))
examples = []
for i, line in enumerate(lines):
guid = '%s-%s' % ('train', i)
text_a = line[0]
label = line[1].split(' ')
examples.append(NERInputExample(guid=guid, text_a=... | WeiboNerProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeiboNerProcessor:
def get_train_examples(self, data_dir):
"""See base class."""
<|body_0|>
def get_test_examples(self, data_dir, file_name):
"""See base class."""
<|body_1|>
def get_labels(self, data_dir):
"""See base class."""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_069351 | 14,627 | no_license | [
{
"docstring": "See base class.",
"name": "get_train_examples",
"signature": "def get_train_examples(self, data_dir)"
},
{
"docstring": "See base class.",
"name": "get_test_examples",
"signature": "def get_test_examples(self, data_dir, file_name)"
},
{
"docstring": "See base clas... | 3 | stack_v2_sparse_classes_30k_train_018274 | Implement the Python class `WeiboNerProcessor` described below.
Class description:
Implement the WeiboNerProcessor class.
Method signatures and docstrings:
- def get_train_examples(self, data_dir): See base class.
- def get_test_examples(self, data_dir, file_name): See base class.
- def get_labels(self, data_dir): Se... | Implement the Python class `WeiboNerProcessor` described below.
Class description:
Implement the WeiboNerProcessor class.
Method signatures and docstrings:
- def get_train_examples(self, data_dir): See base class.
- def get_test_examples(self, data_dir, file_name): See base class.
- def get_labels(self, data_dir): Se... | aa40410ddd23706157c33f0df648880adfff4610 | <|skeleton|>
class WeiboNerProcessor:
def get_train_examples(self, data_dir):
"""See base class."""
<|body_0|>
def get_test_examples(self, data_dir, file_name):
"""See base class."""
<|body_1|>
def get_labels(self, data_dir):
"""See base class."""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeiboNerProcessor:
def get_train_examples(self, data_dir):
"""See base class."""
lines = self._read_tsv(os.path.join(data_dir, 'train.tsv'))
examples = []
for i, line in enumerate(lines):
guid = '%s-%s' % ('train', i)
text_a = line[0]
label =... | the_stack_v2_python_sparse | bert_kaggle/prepro.py | htrekker/tianchi-contest | train | 0 | |
eaa320e938be09cb305c2264b867fc230b4d064d | [
"super().__init__(n)\nself.pin_A = None\nself.pin_B = None",
"if self.pin_A == None:\n return int(input('Enter Pin A input for gate {} --> '.format(self.get_label())))\nelse:\n return self.pin_A.get_from().get_output()",
"if self.pin_B == None:\n return int(input('Enter Pin B input for gate {} --> '.fo... | <|body_start_0|>
super().__init__(n)
self.pin_A = None
self.pin_B = None
<|end_body_0|>
<|body_start_1|>
if self.pin_A == None:
return int(input('Enter Pin A input for gate {} --> '.format(self.get_label())))
else:
return self.pin_A.get_from().get_output(... | Binary gate class. Args: n (str): Logic gate label description Attributes: pin_A (LogicGate): Logic gate reference pin_B (LogicGate): Logic gate reference | BinaryGate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryGate:
"""Binary gate class. Args: n (str): Logic gate label description Attributes: pin_A (LogicGate): Logic gate reference pin_B (LogicGate): Logic gate reference"""
def __init__(self, n):
"""Binnary gate __init__ method Args: n (str): Logic gate label description"""
<... | stack_v2_sparse_classes_75kplus_train_069352 | 9,556 | no_license | [
{
"docstring": "Binnary gate __init__ method Args: n (str): Logic gate label description",
"name": "__init__",
"signature": "def __init__(self, n)"
},
{
"docstring": "Returns pin A logic gate reference. Returns: (LogicGate): Returns pin A logic gate",
"name": "get_pin_A",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_005253 | Implement the Python class `BinaryGate` described below.
Class description:
Binary gate class. Args: n (str): Logic gate label description Attributes: pin_A (LogicGate): Logic gate reference pin_B (LogicGate): Logic gate reference
Method signatures and docstrings:
- def __init__(self, n): Binnary gate __init__ method... | Implement the Python class `BinaryGate` described below.
Class description:
Binary gate class. Args: n (str): Logic gate label description Attributes: pin_A (LogicGate): Logic gate reference pin_B (LogicGate): Logic gate reference
Method signatures and docstrings:
- def __init__(self, n): Binnary gate __init__ method... | a9e0f8a7c77ff5b6a3befca5ab93030a9ae35313 | <|skeleton|>
class BinaryGate:
"""Binary gate class. Args: n (str): Logic gate label description Attributes: pin_A (LogicGate): Logic gate reference pin_B (LogicGate): Logic gate reference"""
def __init__(self, n):
"""Binnary gate __init__ method Args: n (str): Logic gate label description"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryGate:
"""Binary gate class. Args: n (str): Logic gate label description Attributes: pin_A (LogicGate): Logic gate reference pin_B (LogicGate): Logic gate reference"""
def __init__(self, n):
"""Binnary gate __init__ method Args: n (str): Logic gate label description"""
super().__init... | the_stack_v2_python_sparse | Section1_Introduction/logic_gates.py | miguel-osuna/PS-Algos-and-DS-using-Python | train | 0 |
ad422fdcaba8c2f233ca5431133dc9790b3d8267 | [
"self.loss_func = loss_func\nself.epsilon = epsilon\nself.num_steps = num_steps\nself.step_size = step_size\nself.rand = random_start\nloss = loss_func\nself.x_input = x_input\nself.y_input = y_input\nself.grad = tf.gradients(loss, self.x_input)[0]\ngrad_l2_norm = tf.sqrt(tf.reduce_sum(tf.square(self.grad), axis=[1... | <|body_start_0|>
self.loss_func = loss_func
self.epsilon = epsilon
self.num_steps = num_steps
self.step_size = step_size
self.rand = random_start
loss = loss_func
self.x_input = x_input
self.y_input = y_input
self.grad = tf.gradients(loss, self.x_i... | LinfPGDAttack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinfPGDAttack:
def __init__(self, loss_func, x_input, y_input, epsilon, num_steps, step_size, random_start):
"""Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point."""
<|body_0|>
def perturb(self,... | stack_v2_sparse_classes_75kplus_train_069353 | 7,367 | no_license | [
{
"docstring": "Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point.",
"name": "__init__",
"signature": "def __init__(self, loss_func, x_input, y_input, epsilon, num_steps, step_size, random_start)"
},
{
"docstring": ... | 3 | null | Implement the Python class `LinfPGDAttack` described below.
Class description:
Implement the LinfPGDAttack class.
Method signatures and docstrings:
- def __init__(self, loss_func, x_input, y_input, epsilon, num_steps, step_size, random_start): Attack parameter initialization. The attack performs k steps of size a, wh... | Implement the Python class `LinfPGDAttack` described below.
Class description:
Implement the LinfPGDAttack class.
Method signatures and docstrings:
- def __init__(self, loss_func, x_input, y_input, epsilon, num_steps, step_size, random_start): Attack parameter initialization. The attack performs k steps of size a, wh... | fce2aedc511f925e8033c523e9a3a64a9a1abd17 | <|skeleton|>
class LinfPGDAttack:
def __init__(self, loss_func, x_input, y_input, epsilon, num_steps, step_size, random_start):
"""Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point."""
<|body_0|>
def perturb(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinfPGDAttack:
def __init__(self, loss_func, x_input, y_input, epsilon, num_steps, step_size, random_start):
"""Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point."""
self.loss_func = loss_func
self.epsilon... | the_stack_v2_python_sparse | code/pgd_attack.py | JerishDansolBalala/FeatureSpaceAtk | train | 1 | |
446bf7099ab4ed6cb081b1b6c553ef8b568e75e1 | [
"super().__init__(description.key, api, coordinator)\nself.field = description.field\nself.entity_description = description\nself.data_type = description.field.field_type\nself.raw_format = description.raw_format",
"all_data = self.coordinator.data\nvalue = self.api.get_field_value(all_data, self.field.name)\nif ... | <|body_start_0|>
super().__init__(description.key, api, coordinator)
self.field = description.field
self.entity_description = description
self.data_type = description.field.field_type
self.raw_format = description.raw_format
<|end_body_0|>
<|body_start_1|>
all_data = sel... | Get a sensor data from the Renson API and store it in the state of the class. | RensonSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RensonSensor:
"""Get a sensor data from the Renson API and store it in the state of the class."""
def __init__(self, description: RensonSensorEntityDescription, api: RensonVentilation, coordinator: RensonCoordinator) -> None:
"""Initialize class."""
<|body_0|>
def _handl... | stack_v2_sparse_classes_75kplus_train_069354 | 10,303 | permissive | [
{
"docstring": "Initialize class.",
"name": "__init__",
"signature": "def __init__(self, description: RensonSensorEntityDescription, api: RensonVentilation, coordinator: RensonCoordinator) -> None"
},
{
"docstring": "Handle updated data from the coordinator.",
"name": "_handle_coordinator_up... | 2 | stack_v2_sparse_classes_30k_train_014721 | Implement the Python class `RensonSensor` described below.
Class description:
Get a sensor data from the Renson API and store it in the state of the class.
Method signatures and docstrings:
- def __init__(self, description: RensonSensorEntityDescription, api: RensonVentilation, coordinator: RensonCoordinator) -> None... | Implement the Python class `RensonSensor` described below.
Class description:
Get a sensor data from the Renson API and store it in the state of the class.
Method signatures and docstrings:
- def __init__(self, description: RensonSensorEntityDescription, api: RensonVentilation, coordinator: RensonCoordinator) -> None... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RensonSensor:
"""Get a sensor data from the Renson API and store it in the state of the class."""
def __init__(self, description: RensonSensorEntityDescription, api: RensonVentilation, coordinator: RensonCoordinator) -> None:
"""Initialize class."""
<|body_0|>
def _handl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RensonSensor:
"""Get a sensor data from the Renson API and store it in the state of the class."""
def __init__(self, description: RensonSensorEntityDescription, api: RensonVentilation, coordinator: RensonCoordinator) -> None:
"""Initialize class."""
super().__init__(description.key, api, ... | the_stack_v2_python_sparse | homeassistant/components/renson/sensor.py | home-assistant/core | train | 35,501 |
221d3c789e5e6580f94d2daabddf663f1d249883 | [
"Component.__init__(self, name, ReduceTensor, config)\nself.key_inputs = self.stream_keys['inputs']\nself.key_outputs = self.stream_keys['outputs']\nself.num_inputs_dims = self.config['num_inputs_dims']\nself.input_size = self.globals['input_size']\nself.dim = self.config['reduction_dim']\nself.keepdim = self.confi... | <|body_start_0|>
Component.__init__(self, name, ReduceTensor, config)
self.key_inputs = self.stream_keys['inputs']
self.key_outputs = self.stream_keys['outputs']
self.num_inputs_dims = self.config['num_inputs_dims']
self.input_size = self.globals['input_size']
self.dim = ... | Class responsible for reducing tensor using indicated reduction method along a given dimension. | ReduceTensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReduceTensor:
"""Class responsible for reducing tensor using indicated reduction method along a given dimension."""
def __init__(self, name, config):
"""Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionar... | stack_v2_sparse_classes_75kplus_train_069355 | 4,905 | permissive | [
{
"docstring": "Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionary of parameters (read from the configuration ``.yaml`` file). :type config: :py:class:`ptp.configuration.ConfigInterface`",
"name": "__init__",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_044392 | Implement the Python class `ReduceTensor` described below.
Class description:
Class responsible for reducing tensor using indicated reduction method along a given dimension.
Method signatures and docstrings:
- def __init__(self, name, config): Initializes object. :param name: Name of the component loaded from the con... | Implement the Python class `ReduceTensor` described below.
Class description:
Class responsible for reducing tensor using indicated reduction method along a given dimension.
Method signatures and docstrings:
- def __init__(self, name, config): Initializes object. :param name: Name of the component loaded from the con... | 9cb17271666061cb19fe24197ecd5e4c8d32c5da | <|skeleton|>
class ReduceTensor:
"""Class responsible for reducing tensor using indicated reduction method along a given dimension."""
def __init__(self, name, config):
"""Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReduceTensor:
"""Class responsible for reducing tensor using indicated reduction method along a given dimension."""
def __init__(self, name, config):
"""Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionary of paramete... | the_stack_v2_python_sparse | ptp/components/transforms/reduce_tensor.py | ConnectionMaster/pytorchpipe | train | 1 |
1d88b43fff2ba6fbcc7aea4487bec281b30f0328 | [
"self.use_cuda = use_cuda\nif self.use_cuda is True and cuda_installed is False:\n self.use_cuda = False\n print('** Cuda not available for Fourier transform.')\n print('** Performing the Fourier transform on the CPU.')\nself.use_mkl = mkl_installed\nif self.use_cuda:\n copy_tpb = (8, 32) if cuda_gpu_mo... | <|body_start_0|>
self.use_cuda = use_cuda
if self.use_cuda is True and cuda_installed is False:
self.use_cuda = False
print('** Cuda not available for Fourier transform.')
print('** Performing the Fourier transform on the CPU.')
self.use_mkl = mkl_installed
... | Object that performs Fourier transform of 2D arrays along the z axis, (axis 0) either on the CPU (using pyfftw) or on the GPU (using cufft) See the methods `transform` and `inverse transform` for more information | FFT | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFT:
"""Object that performs Fourier transform of 2D arrays along the z axis, (axis 0) either on the CPU (using pyfftw) or on the GPU (using cufft) See the methods `transform` and `inverse transform` for more information"""
def __init__(self, Nr, Nz, use_cuda=False, nthreads=None):
"... | stack_v2_sparse_classes_75kplus_train_069356 | 6,780 | permissive | [
{
"docstring": "Initialize an FFT object Parameters ---------- Nr: int Number of grid points along the r axis (axis -1) Nz: int Number of grid points along the z axis (axis 0) use_cuda: bool, optional Whether to perform the Fourier transform on the z axis nthreads : int, optional Number of threads for the FFTW ... | 3 | stack_v2_sparse_classes_30k_test_000141 | Implement the Python class `FFT` described below.
Class description:
Object that performs Fourier transform of 2D arrays along the z axis, (axis 0) either on the CPU (using pyfftw) or on the GPU (using cufft) See the methods `transform` and `inverse transform` for more information
Method signatures and docstrings:
- ... | Implement the Python class `FFT` described below.
Class description:
Object that performs Fourier transform of 2D arrays along the z axis, (axis 0) either on the CPU (using pyfftw) or on the GPU (using cufft) See the methods `transform` and `inverse transform` for more information
Method signatures and docstrings:
- ... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class FFT:
"""Object that performs Fourier transform of 2D arrays along the z axis, (axis 0) either on the CPU (using pyfftw) or on the GPU (using cufft) See the methods `transform` and `inverse transform` for more information"""
def __init__(self, Nr, Nz, use_cuda=False, nthreads=None):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FFT:
"""Object that performs Fourier transform of 2D arrays along the z axis, (axis 0) either on the CPU (using pyfftw) or on the GPU (using cufft) See the methods `transform` and `inverse transform` for more information"""
def __init__(self, Nr, Nz, use_cuda=False, nthreads=None):
"""Initialize ... | the_stack_v2_python_sparse | fbpic/fields/spectral_transform/fourier.py | fbpic/fbpic | train | 163 |
f682471c8334d0bce8937db89c7e3075d206cfd7 | [
"if not super().is_valid():\n return False\nare_types_valid = all([type(self.build_time_sec) is int, type(self.hit_points) is int])\nif not are_types_valid:\n return False\nare_values_valid = all([0 <= self.build_time_sec <= MAX_VALUE_LIMIT, 0 < self.hit_points <= MAX_VALUE_LIMIT])\nreturn are_values_valid",
... | <|body_start_0|>
if not super().is_valid():
return False
are_types_valid = all([type(self.build_time_sec) is int, type(self.hit_points) is int])
if not are_types_valid:
return False
are_values_valid = all([0 <= self.build_time_sec <= MAX_VALUE_LIMIT, 0 < self.hit_... | Refers to a constructable building in aoe2 | Structure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Structure:
"""Refers to a constructable building in aoe2"""
def is_valid(self) -> bool:
"""Check if the structure object is valid :return: Boolean, True if valid, False otherwise"""
<|body_0|>
def from_str(data):
"""Parse a string to object a Structure"""
... | stack_v2_sparse_classes_75kplus_train_069357 | 1,746 | no_license | [
{
"docstring": "Check if the structure object is valid :return: Boolean, True if valid, False otherwise",
"name": "is_valid",
"signature": "def is_valid(self) -> bool"
},
{
"docstring": "Parse a string to object a Structure",
"name": "from_str",
"signature": "def from_str(data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019278 | Implement the Python class `Structure` described below.
Class description:
Refers to a constructable building in aoe2
Method signatures and docstrings:
- def is_valid(self) -> bool: Check if the structure object is valid :return: Boolean, True if valid, False otherwise
- def from_str(data): Parse a string to object a... | Implement the Python class `Structure` described below.
Class description:
Refers to a constructable building in aoe2
Method signatures and docstrings:
- def is_valid(self) -> bool: Check if the structure object is valid :return: Boolean, True if valid, False otherwise
- def from_str(data): Parse a string to object a... | 31df8c3c17b28ed02920f92bfddca25d1d169762 | <|skeleton|>
class Structure:
"""Refers to a constructable building in aoe2"""
def is_valid(self) -> bool:
"""Check if the structure object is valid :return: Boolean, True if valid, False otherwise"""
<|body_0|>
def from_str(data):
"""Parse a string to object a Structure"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Structure:
"""Refers to a constructable building in aoe2"""
def is_valid(self) -> bool:
"""Check if the structure object is valid :return: Boolean, True if valid, False otherwise"""
if not super().is_valid():
return False
are_types_valid = all([type(self.build_time_sec... | the_stack_v2_python_sparse | aoe2_api/models/structure.py | agiletelescope/aoe2-api | train | 1 |
01a524607ec41e5692e124edb478dfa4ff289165 | [
"super().__init__('WallFollowController')\nself.Kp = Kp\nself.Kd = Kd\nself.Kth = Kth\nself.target_distance = target_distance\nself.speed = speed\nif side == 'left':\n self.side = 1\nelif side == 'right':\n self.side = -1\nelse:\n raise ValueError(\"Can't follow side other than left or right?!\")\nself.__s... | <|body_start_0|>
super().__init__('WallFollowController')
self.Kp = Kp
self.Kd = Kd
self.Kth = Kth
self.target_distance = target_distance
self.speed = speed
if side == 'left':
self.side = 1
elif side == 'right':
self.side = -1
... | A ROS node for implementing wall following using a simple PD controller. C.f. https://syrotek.felk.cvut.cz/course/ROS_CPP_INTRO/exercise/ROS_CPP_WALLFOLLOWING | WallFollowController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WallFollowController:
"""A ROS node for implementing wall following using a simple PD controller. C.f. https://syrotek.felk.cvut.cz/course/ROS_CPP_INTRO/exercise/ROS_CPP_WALLFOLLOWING"""
def __init__(self, lidar_topic, control_topic, speed=5.0, target_distance=5, Kp=1.0, Kd=1.0, Kth=1.0, sid... | stack_v2_sparse_classes_75kplus_train_069358 | 3,685 | no_license | [
{
"docstring": "Creates a wall following node. :param lidar_topic: The topic publishing LIDAR messages. :param control_topic: The topic to publish twist messages to. :param Kp: The proportional gain. :param Kd: The derivative gain. :param Kth: The proportional gain for the angular velocity. :param side: The sid... | 3 | stack_v2_sparse_classes_30k_train_037988 | Implement the Python class `WallFollowController` described below.
Class description:
A ROS node for implementing wall following using a simple PD controller. C.f. https://syrotek.felk.cvut.cz/course/ROS_CPP_INTRO/exercise/ROS_CPP_WALLFOLLOWING
Method signatures and docstrings:
- def __init__(self, lidar_topic, contr... | Implement the Python class `WallFollowController` described below.
Class description:
A ROS node for implementing wall following using a simple PD controller. C.f. https://syrotek.felk.cvut.cz/course/ROS_CPP_INTRO/exercise/ROS_CPP_WALLFOLLOWING
Method signatures and docstrings:
- def __init__(self, lidar_topic, contr... | ed94fe25f55b0f1d5e3eef4f96755ca826e63881 | <|skeleton|>
class WallFollowController:
"""A ROS node for implementing wall following using a simple PD controller. C.f. https://syrotek.felk.cvut.cz/course/ROS_CPP_INTRO/exercise/ROS_CPP_WALLFOLLOWING"""
def __init__(self, lidar_topic, control_topic, speed=5.0, target_distance=5, Kp=1.0, Kd=1.0, Kth=1.0, sid... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WallFollowController:
"""A ROS node for implementing wall following using a simple PD controller. C.f. https://syrotek.felk.cvut.cz/course/ROS_CPP_INTRO/exercise/ROS_CPP_WALLFOLLOWING"""
def __init__(self, lidar_topic, control_topic, speed=5.0, target_distance=5, Kp=1.0, Kd=1.0, Kth=1.0, side='left'):
... | the_stack_v2_python_sparse | robotics/nodes/motion/wall_follow.py | Notgnoshi/robotics | train | 0 |
36086d4de941145178fae3bd339d5413578aef88 | [
"hc, wc = (sorted(hc), sorted(wc))\nhc.append(h)\nwc.append(w)\nmax_height = max_width = prev_height = prev_width = 0\nfor height in hc:\n max_height = max(max_height, height - prev_height)\n prev_width = height\nfor width in wc:\n max_width = max(max_width, width - prev_width)\n prev_width = width\nret... | <|body_start_0|>
hc, wc = (sorted(hc), sorted(wc))
hc.append(h)
wc.append(w)
max_height = max_width = prev_height = prev_width = 0
for height in hc:
max_height = max(max_height, height - prev_height)
prev_width = height
for width in wc:
... | Cake | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cake:
def max_area(self, h: int, w: int, hc: List[int], wc: List[int]) -> int:
"""Approach: Optimized (max height * max width) Time Complexity: O(N log N) Space Complexity: O(1) :param h: :param w: :param hc: :param wc: :return:"""
<|body_0|>
def max_area_(self, h: int, w: i... | stack_v2_sparse_classes_75kplus_train_069359 | 1,720 | no_license | [
{
"docstring": "Approach: Optimized (max height * max width) Time Complexity: O(N log N) Space Complexity: O(1) :param h: :param w: :param hc: :param wc: :return:",
"name": "max_area",
"signature": "def max_area(self, h: int, w: int, hc: List[int], wc: List[int]) -> int"
},
{
"docstring": "Naive... | 2 | null | Implement the Python class `Cake` described below.
Class description:
Implement the Cake class.
Method signatures and docstrings:
- def max_area(self, h: int, w: int, hc: List[int], wc: List[int]) -> int: Approach: Optimized (max height * max width) Time Complexity: O(N log N) Space Complexity: O(1) :param h: :param ... | Implement the Python class `Cake` described below.
Class description:
Implement the Cake class.
Method signatures and docstrings:
- def max_area(self, h: int, w: int, hc: List[int], wc: List[int]) -> int: Approach: Optimized (max height * max width) Time Complexity: O(N log N) Space Complexity: O(1) :param h: :param ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Cake:
def max_area(self, h: int, w: int, hc: List[int], wc: List[int]) -> int:
"""Approach: Optimized (max height * max width) Time Complexity: O(N log N) Space Complexity: O(1) :param h: :param w: :param hc: :param wc: :return:"""
<|body_0|>
def max_area_(self, h: int, w: i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cake:
def max_area(self, h: int, w: int, hc: List[int], wc: List[int]) -> int:
"""Approach: Optimized (max height * max width) Time Complexity: O(N log N) Space Complexity: O(1) :param h: :param w: :param hc: :param wc: :return:"""
hc, wc = (sorted(hc), sorted(wc))
hc.append(h)
... | the_stack_v2_python_sparse | revisited_2021/2d_array/max_area_of_piece_of_cake_after_cuts.py | Shiv2157k/leet_code | train | 1 | |
bbc8bbe5f3b378a00afdf8535dae35e8e71d68f1 | [
"ledger_list = [u'业务管理', u'渠道资源管理', u'台账管理']\nself.click_button_for_one(ledger_list[0])\nsleep(2)\nself.click_more_button_for_one(ledger_list[1:])\nsleep(2)",
"if ledger_list[0] != u'':\n self.input_text_message_for_inside_text(u'请输入仓库名称', ledger_list[0])\nif ledger_list[1] != u'':\n self.click_option_by_in... | <|body_start_0|>
ledger_list = [u'业务管理', u'渠道资源管理', u'台账管理']
self.click_button_for_one(ledger_list[0])
sleep(2)
self.click_more_button_for_one(ledger_list[1:])
sleep(2)
<|end_body_0|>
<|body_start_1|>
if ledger_list[0] != u'':
self.input_text_message_for_insi... | 台账管理页面 | LedgerManagePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LedgerManagePage:
"""台账管理页面"""
def open_ledger_manage(self):
"""打开台账管理页面"""
<|body_0|>
def input_ledger_search_info(self, ledger_list):
"""输入账单查询信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ledger_list = [u'业务管理', u'渠道资源管理', u'台账管理']
... | stack_v2_sparse_classes_75kplus_train_069360 | 1,255 | no_license | [
{
"docstring": "打开台账管理页面",
"name": "open_ledger_manage",
"signature": "def open_ledger_manage(self)"
},
{
"docstring": "输入账单查询信息",
"name": "input_ledger_search_info",
"signature": "def input_ledger_search_info(self, ledger_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038739 | Implement the Python class `LedgerManagePage` described below.
Class description:
台账管理页面
Method signatures and docstrings:
- def open_ledger_manage(self): 打开台账管理页面
- def input_ledger_search_info(self, ledger_list): 输入账单查询信息 | Implement the Python class `LedgerManagePage` described below.
Class description:
台账管理页面
Method signatures and docstrings:
- def open_ledger_manage(self): 打开台账管理页面
- def input_ledger_search_info(self, ledger_list): 输入账单查询信息
<|skeleton|>
class LedgerManagePage:
"""台账管理页面"""
def open_ledger_manage(self):
... | dcae68955b2857bbfe411145432865c57561c9ef | <|skeleton|>
class LedgerManagePage:
"""台账管理页面"""
def open_ledger_manage(self):
"""打开台账管理页面"""
<|body_0|>
def input_ledger_search_info(self, ledger_list):
"""输入账单查询信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LedgerManagePage:
"""台账管理页面"""
def open_ledger_manage(self):
"""打开台账管理页面"""
ledger_list = [u'业务管理', u'渠道资源管理', u'台账管理']
self.click_button_for_one(ledger_list[0])
sleep(2)
self.click_more_button_for_one(ledger_list[1:])
sleep(2)
def input_ledger_search_... | the_stack_v2_python_sparse | genlot_vlt2/pages/Business_management/channel_resource_manage_page/channel_resource_manage_ledger_manage_page.py | bbwdi/auto | train | 1 |
b8f78be36e80b18f38ff260de07d9748cec55b2b | [
"super().__init__()\nself.mode = mode\nself.qubit_names = qubit_names",
"if self.mode == FilterMode.INCLUDE:\n return not all([qb_name in self.qubit_names for qb_name in qubit_names])\nelif self.mode == FilterMode.EXCLUDE:\n return not any([qb_name in self.qubit_names for qb_name in qubit_names])",
"if no... | <|body_start_0|>
super().__init__()
self.mode = mode
self.qubit_names = qubit_names
<|end_body_0|>
<|body_start_1|>
if self.mode == FilterMode.INCLUDE:
return not all([qb_name in self.qubit_names for qb_name in qubit_names])
elif self.mode == FilterMode.EXCLUDE:
... | A filter class to filter based on value nodes' `qubit` field | QubitFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QubitFilter:
"""A filter class to filter based on value nodes' `qubit` field"""
def __init__(self, mode: FilterMode=FilterMode.EXCLUDE, qubit_names=[]):
"""Creates a QubitFilter instance All qubit names in a node's `qubits` field must be in/or not in `self.qubit_names`; based on `mod... | stack_v2_sparse_classes_75kplus_train_069361 | 7,968 | permissive | [
{
"docstring": "Creates a QubitFilter instance All qubit names in a node's `qubits` field must be in/or not in `self.qubit_names`; based on `mode`. For example, if `mode=FilterMode.INCLUDE`, a value node will be filtered if any qubit name in `node['qubits']` is not in `qubit_names`. Args: mode (Filtermode, opti... | 3 | stack_v2_sparse_classes_30k_train_043421 | Implement the Python class `QubitFilter` described below.
Class description:
A filter class to filter based on value nodes' `qubit` field
Method signatures and docstrings:
- def __init__(self, mode: FilterMode=FilterMode.EXCLUDE, qubit_names=[]): Creates a QubitFilter instance All qubit names in a node's `qubits` fie... | Implement the Python class `QubitFilter` described below.
Class description:
A filter class to filter based on value nodes' `qubit` field
Method signatures and docstrings:
- def __init__(self, mode: FilterMode=FilterMode.EXCLUDE, qubit_names=[]): Creates a QubitFilter instance All qubit names in a node's `qubits` fie... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class QubitFilter:
"""A filter class to filter based on value nodes' `qubit` field"""
def __init__(self, mode: FilterMode=FilterMode.EXCLUDE, qubit_names=[]):
"""Creates a QubitFilter instance All qubit names in a node's `qubits` field must be in/or not in `self.qubit_names`; based on `mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QubitFilter:
"""A filter class to filter based on value nodes' `qubit` field"""
def __init__(self, mode: FilterMode=FilterMode.EXCLUDE, qubit_names=[]):
"""Creates a QubitFilter instance All qubit names in a node's `qubits` field must be in/or not in `self.qubit_names`; based on `mode`. For examp... | the_stack_v2_python_sparse | pycqed/utilities/devicedb/filters.py | QudevETH/PycQED_py3 | train | 8 |
f691b8caf413b604fcdc092feb9c29ac87dc6b91 | [
"self.version = c_uint32(version)\nself.filesize = c_uint32(16)\nself.name = set_string_range(name, 100).encode('ascii')\nself.report_dir = set_string_range(report_dir, 100).encode('ascii')\nself.myriad_params = myriad_params\nself.network = network\nself.stage_count = c_uint32(self.network.count)\nself.VCS_Fix = T... | <|body_start_0|>
self.version = c_uint32(version)
self.filesize = c_uint32(16)
self.name = set_string_range(name, 100).encode('ascii')
self.report_dir = set_string_range(report_dir, 100).encode('ascii')
self.myriad_params = myriad_params
self.network = network
sel... | Blob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blob:
def __init__(self, version, name, report_dir, myriad_params, network, blob_name):
"""This object contains all the information required for a blob file + some additional info for processing. :param version: The version of the toolkit used to generate this blob. Useful for the potent... | stack_v2_sparse_classes_75kplus_train_069362 | 3,163 | permissive | [
{
"docstring": "This object contains all the information required for a blob file + some additional info for processing. :param version: The version of the toolkit used to generate this blob. Useful for the potential of having backwards compatibility - although it's easier to regenerate your file. :param name: ... | 2 | null | Implement the Python class `Blob` described below.
Class description:
Implement the Blob class.
Method signatures and docstrings:
- def __init__(self, version, name, report_dir, myriad_params, network, blob_name): This object contains all the information required for a blob file + some additional info for processing.... | Implement the Python class `Blob` described below.
Class description:
Implement the Blob class.
Method signatures and docstrings:
- def __init__(self, version, name, report_dir, myriad_params, network, blob_name): This object contains all the information required for a blob file + some additional info for processing.... | 5ce5eb7f84654aecf6840de773188f436219559d | <|skeleton|>
class Blob:
def __init__(self, version, name, report_dir, myriad_params, network, blob_name):
"""This object contains all the information required for a blob file + some additional info for processing. :param version: The version of the toolkit used to generate this blob. Useful for the potent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Blob:
def __init__(self, version, name, report_dir, myriad_params, network, blob_name):
"""This object contains all the information required for a blob file + some additional info for processing. :param version: The version of the toolkit used to generate this blob. Useful for the potential of having ... | the_stack_v2_python_sparse | tool/Models/Blob.py | HornedSungem/SungemSDK-Python | train | 14 | |
ee891056af3f8dd379ccc72070af6e3b7de37bb1 | [
"if len(strs) == 0:\n return ''\nt = ''\nfor s in strs:\n l = len(s)\n t += str(l) + '#' + s\nreturn t",
"if s == '':\n return []\nstrs = []\ni = 0\nl = ''\nwhile i < len(s):\n if s[i] == '#':\n l = int(l)\n newS = s[i + 1:i + 1 + l]\n strs.append(newS)\n i = i + 1 + l\n... | <|body_start_0|>
if len(strs) == 0:
return ''
t = ''
for s in strs:
l = len(s)
t += str(l) + '#' + s
return t
<|end_body_0|>
<|body_start_1|>
if s == '':
return []
strs = []
i = 0
l = ''
while i < le... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_069363 | 691 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_000562 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 15f012927dc34b5d751af6633caa5e8882d26ff7 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
if len(strs) == 0:
return ''
t = ''
for s in strs:
l = len(s)
t += str(l) + '#' + s
return t
def decode(self, s)... | the_stack_v2_python_sparse | python/271.EncodeAndDecodeStrings_2.py | MaxPoon/Leetcode | train | 15 | |
eb299685a7600c50392160f2b05fcf206e69b985 | [
"path = path or tempfile.mkdtemp()\nwith open(os.path.join(path, cls.MODEL_FILENAME), 'wb') as f:\n cpickle.dump(estimator, f)\ncheckpoint = cls.from_directory(path)\nif preprocessor:\n checkpoint.set_preprocessor(preprocessor)\nreturn checkpoint",
"with self.as_directory() as checkpoint_path:\n estimato... | <|body_start_0|>
path = path or tempfile.mkdtemp()
with open(os.path.join(path, cls.MODEL_FILENAME), 'wb') as f:
cpickle.dump(estimator, f)
checkpoint = cls.from_directory(path)
if preprocessor:
checkpoint.set_preprocessor(preprocessor)
return checkpoint
<... | A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality. | SklearnCheckpoint | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnCheckpoint:
"""A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality."""
def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor']=None) -> 'SklearnCheckpoint':
"""Create a :py:class:`~ray.... | stack_v2_sparse_classes_75kplus_train_069364 | 2,206 | permissive | [
{
"docstring": "Create a :py:class:`~ray.train.Checkpoint` that stores an sklearn ``Estimator``. Args: estimator: The ``Estimator`` to store in the checkpoint. path: The directory where the checkpoint will be stored. Defaults to a temporary directory. preprocessor: A fitted preprocessor to be applied before inf... | 2 | stack_v2_sparse_classes_30k_train_020454 | Implement the Python class `SklearnCheckpoint` described below.
Class description:
A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality.
Method signatures and docstrings:
- def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor'... | Implement the Python class `SklearnCheckpoint` described below.
Class description:
A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality.
Method signatures and docstrings:
- def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor'... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class SklearnCheckpoint:
"""A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality."""
def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor']=None) -> 'SklearnCheckpoint':
"""Create a :py:class:`~ray.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SklearnCheckpoint:
"""A :py:class:`~ray.train.Checkpoint` with sklearn-specific functionality."""
def from_estimator(cls, estimator: BaseEstimator, *, path: Union[str, os.PathLike]=None, preprocessor: Optional['Preprocessor']=None) -> 'SklearnCheckpoint':
"""Create a :py:class:`~ray.train.Checkpo... | the_stack_v2_python_sparse | python/ray/train/sklearn/sklearn_checkpoint.py | ray-project/ray | train | 29,482 |
5d433f0c4223a91a4f9a8c4767e3bad561be10e0 | [
"super(Actor, self).__init__()\nself.state_dim = state_dim\nself.action_dim = action_dim\nself.action_lim = action_lim\nself.fc1 = nn.Linear(state_dim, 256)\nself.fc1.weight.data = fanin_init(self.fc1.weight.data.size())\nself.fc2 = nn.Linear(256, 128)\nself.fc2.weight.data = fanin_init(self.fc2.weight.data.size())... | <|body_start_0|>
super(Actor, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.action_lim = action_lim
self.fc1 = nn.Linear(state_dim, 256)
self.fc1.weight.data = fanin_init(self.fc1.weight.data.size())
self.fc2 = nn.Linear(256, 128)
... | Actor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
def __init__(self, state_dim, action_dim, action_lim):
""":param state_dim: Dimension of input state (int) :param action_dim: Dimension of output action (int) :param action_lim: Used to limit action in [-action_lim,action_lim] :return:"""
<|body_0|>
def forward(self, ... | stack_v2_sparse_classes_75kplus_train_069365 | 11,540 | permissive | [
{
"docstring": ":param state_dim: Dimension of input state (int) :param action_dim: Dimension of output action (int) :param action_lim: Used to limit action in [-action_lim,action_lim] :return:",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim, action_lim)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_041971 | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, action_lim): :param state_dim: Dimension of input state (int) :param action_dim: Dimension of output action (int) :param action_lim: Used to l... | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, action_lim): :param state_dim: Dimension of input state (int) :param action_dim: Dimension of output action (int) :param action_lim: Used to l... | 32a7e0b32bad75a9102f1fbb76ff16bfd7eb3390 | <|skeleton|>
class Actor:
def __init__(self, state_dim, action_dim, action_lim):
""":param state_dim: Dimension of input state (int) :param action_dim: Dimension of output action (int) :param action_lim: Used to limit action in [-action_lim,action_lim] :return:"""
<|body_0|>
def forward(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Actor:
def __init__(self, state_dim, action_dim, action_lim):
""":param state_dim: Dimension of input state (int) :param action_dim: Dimension of output action (int) :param action_lim: Used to limit action in [-action_lim,action_lim] :return:"""
super(Actor, self).__init__()
self.state... | the_stack_v2_python_sparse | rl/ddpg.py | zkcys001/distracting_feature | train | 31 | |
6fdd43631b3fa73d82bbf8a6afeb5c4a45fbf017 | [
"schema = MusicSchema(many=True)\nquery = Music.query\nreturn paginate(query, schema)",
"schema = MusicSchema()\nmusic = schema.load(request.json)\nreturn save_new_music(music)"
] | <|body_start_0|>
schema = MusicSchema(many=True)
query = Music.query
return paginate(query, schema)
<|end_body_0|>
<|body_start_1|>
schema = MusicSchema()
music = schema.load(request.json)
return save_new_music(music)
<|end_body_1|>
| MusicList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MusicList:
def get(self):
"""List all musics"""
<|body_0|>
def post(self) -> Tuple[Dict[str, str], int]:
"""Creates a new Music"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
schema = MusicSchema(many=True)
query = Music.query
retur... | stack_v2_sparse_classes_75kplus_train_069366 | 2,433 | no_license | [
{
"docstring": "List all musics",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates a new Music",
"name": "post",
"signature": "def post(self) -> Tuple[Dict[str, str], int]"
}
] | 2 | null | Implement the Python class `MusicList` described below.
Class description:
Implement the MusicList class.
Method signatures and docstrings:
- def get(self): List all musics
- def post(self) -> Tuple[Dict[str, str], int]: Creates a new Music | Implement the Python class `MusicList` described below.
Class description:
Implement the MusicList class.
Method signatures and docstrings:
- def get(self): List all musics
- def post(self) -> Tuple[Dict[str, str], int]: Creates a new Music
<|skeleton|>
class MusicList:
def get(self):
"""List all musics... | 4082579b26a36e2d5b6d4cd7d861b896fda27a1e | <|skeleton|>
class MusicList:
def get(self):
"""List all musics"""
<|body_0|>
def post(self) -> Tuple[Dict[str, str], int]:
"""Creates a new Music"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MusicList:
def get(self):
"""List all musics"""
schema = MusicSchema(many=True)
query = Music.query
return paginate(query, schema)
def post(self) -> Tuple[Dict[str, str], int]:
"""Creates a new Music"""
schema = MusicSchema()
music = schema.load(req... | the_stack_v2_python_sparse | app/main/controller/music_controller.py | Jieszs/restx-demo | train | 1 | |
08383286f37f34f683898e2b0b196b1cc9d8de5a | [
"if len(chordProgression) < 4:\n print('ERROR IN ChordProgression 2')\n return None\nelse:\n keysForReturn = []\n tempChords = []\n for chord in chordProgression:\n tempChords.append(chord[0])\n tempChords = np.array(tempChords)\n chords = [[tempChords[0], tempChords[1]], [tempChords[2],... | <|body_start_0|>
if len(chordProgression) < 4:
print('ERROR IN ChordProgression 2')
return None
else:
keysForReturn = []
tempChords = []
for chord in chordProgression:
tempChords.append(chord[0])
tempChords = np.arra... | SubMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
<|body_0|>
def cherryB(self, keyProgression, chordProgression):
"""サビで使われているメソッド"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(chordProgression) < 4... | stack_v2_sparse_classes_75kplus_train_069367 | 12,440 | no_license | [
{
"docstring": "INTROで使われているメソッド",
"name": "cherryIntro",
"signature": "def cherryIntro(self, keyProgression, chordProgression)"
},
{
"docstring": "サビで使われているメソッド",
"name": "cherryB",
"signature": "def cherryB(self, keyProgression, chordProgression)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019055 | Implement the Python class `SubMethods` described below.
Class description:
Implement the SubMethods class.
Method signatures and docstrings:
- def cherryIntro(self, keyProgression, chordProgression): INTROで使われているメソッド
- def cherryB(self, keyProgression, chordProgression): サビで使われているメソッド | Implement the Python class `SubMethods` described below.
Class description:
Implement the SubMethods class.
Method signatures and docstrings:
- def cherryIntro(self, keyProgression, chordProgression): INTROで使われているメソッド
- def cherryB(self, keyProgression, chordProgression): サビで使われているメソッド
<|skeleton|>
class SubMethods:... | 172f486048825d989aac69945c463dd150b84a88 | <|skeleton|>
class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
<|body_0|>
def cherryB(self, keyProgression, chordProgression):
"""サビで使われているメソッド"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubMethods:
def cherryIntro(self, keyProgression, chordProgression):
"""INTROで使われているメソッド"""
if len(chordProgression) < 4:
print('ERROR IN ChordProgression 2')
return None
else:
keysForReturn = []
tempChords = []
for chord in c... | the_stack_v2_python_sparse | SongGenerator/mikakunin/Composer/ChordProgression.py | ku70t6h1k6r1/auto_music | train | 0 | |
4f476d8c6f8b9d97d4ef1b1b81c52e5673e1cd75 | [
"left = 0\nright = len(A) - 1\nwhile left < right:\n mid = (left + right) // 2\n peak = self.isPeak(A, mid)\n if peak == 0:\n return mid\n if peak > 0:\n left = mid + 1\n else:\n right = mid - 1\nreturn left",
"ls = False\nrs = False\nif i == 0 or A[i - 1] < A[i]:\n ls = Tru... | <|body_start_0|>
left = 0
right = len(A) - 1
while left < right:
mid = (left + right) // 2
peak = self.isPeak(A, mid)
if peak == 0:
return mid
if peak > 0:
left = mid + 1
else:
right = mid... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def isPeak(self, A, i):
""":return 0:peak, 1:increasing, -1:decreasing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left = 0
right = len(A) -... | stack_v2_sparse_classes_75kplus_train_069368 | 839 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "peakIndexInMountainArray",
"signature": "def peakIndexInMountainArray(self, A)"
},
{
"docstring": ":return 0:peak, 1:increasing, -1:decreasing",
"name": "isPeak",
"signature": "def isPeak(self, A, i)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, A): :type A: List[int] :rtype: int
- def isPeak(self, A, i): :return 0:peak, 1:increasing, -1:decreasing | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, A): :type A: List[int] :rtype: int
- def isPeak(self, A, i): :return 0:peak, 1:increasing, -1:decreasing
<|skeleton|>
class Solution:
def... | 88afef5388e308e6da5703b66e07324fb1723731 | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def isPeak(self, A, i):
""":return 0:peak, 1:increasing, -1:decreasing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
left = 0
right = len(A) - 1
while left < right:
mid = (left + right) // 2
peak = self.isPeak(A, mid)
if peak == 0:
return mid
if... | the_stack_v2_python_sparse | 852-peak-index-in-a-mountain-array.py | tiaotiao/leetcode | train | 0 | |
7981b61e2c50c6b750abdbc8fa3289776ba2292d | [
"self.cp = cp\nself.alpha = alpha\nself.g = g\nself.Ts = Ts\nself.approx = kwargs.get('approx', 'constant variables')\nif self.approx == 'constant variables':\n self.approx_scheme = 0\nelif self.approx == 'constant variables and gradient':\n self.approx_scheme = 1\nelse:\n raise NotImplementedError()",
"... | <|body_start_0|>
self.cp = cp
self.alpha = alpha
self.g = g
self.Ts = Ts
self.approx = kwargs.get('approx', 'constant variables')
if self.approx == 'constant variables':
self.approx_scheme = 0
elif self.approx == 'constant variables and gradient':
... | Class for getting the mantle adiabatic temperature Attributs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature | MANTLE_ADIABAT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MANTLE_ADIABAT:
"""Class for getting the mantle adiabatic temperature Attributs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature"""
def __init__(self, cp, alpha, g, Ts, **kwargs):
"""Initiation Inputs: cp - heat capacit... | stack_v2_sparse_classes_75kplus_train_069369 | 10,712 | no_license | [
{
"docstring": "Initiation Inputs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature kwargs: approx - type of approximation approx_scheme - the index of this approximation",
"name": "__init__",
"signature": "def __init__(self, cp, alpha, g, ... | 2 | stack_v2_sparse_classes_30k_train_053026 | Implement the Python class `MANTLE_ADIABAT` described below.
Class description:
Class for getting the mantle adiabatic temperature Attributs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature
Method signatures and docstrings:
- def __init__(self, cp, alph... | Implement the Python class `MANTLE_ADIABAT` described below.
Class description:
Class for getting the mantle adiabatic temperature Attributs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature
Method signatures and docstrings:
- def __init__(self, cp, alph... | d919cadce2b57811351c0615d94da5c6ebfff800 | <|skeleton|>
class MANTLE_ADIABAT:
"""Class for getting the mantle adiabatic temperature Attributs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature"""
def __init__(self, cp, alpha, g, Ts, **kwargs):
"""Initiation Inputs: cp - heat capacit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MANTLE_ADIABAT:
"""Class for getting the mantle adiabatic temperature Attributs: cp - heat capacity alpha - thermal expansivity g - gravitational acceleration Ts = surface adiabatic temperature"""
def __init__(self, cp, alpha, g, Ts, **kwargs):
"""Initiation Inputs: cp - heat capacity alpha - the... | the_stack_v2_python_sparse | shilofue/ThermalModel.py | lhy11009/aspectLib | train | 0 |
5b76b72d700f0a5ed68175400226f26b63f65eb4 | [
"self._config = ConfigParser.ConfigParser()\nself.logger = SEKLogger(__name__, 'INFO')\nself.fileUtil = SEKFileUtil()\nself.dbUtil = SEKDBUtil()\nself.cursor = None\nconfigFilePath = '~/.smart-inverter.cfg'\nif self.fileUtil.isMoreThanOwnerReadableAndWritable(os.path.expanduser(configFilePath)):\n self.logger.lo... | <|body_start_0|>
self._config = ConfigParser.ConfigParser()
self.logger = SEKLogger(__name__, 'INFO')
self.fileUtil = SEKFileUtil()
self.dbUtil = SEKDBUtil()
self.cursor = None
configFilePath = '~/.smart-inverter.cfg'
if self.fileUtil.isMoreThanOwnerReadableAndWri... | Supports site-level config for the Smart Grid PV Inverter project. The default path is ~/.smart-inverter.cfg. Usage: configer = SIConfiger() | SIConfiger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SIConfiger:
"""Supports site-level config for the Smart Grid PV Inverter project. The default path is ~/.smart-inverter.cfg. Usage: configer = SIConfiger()"""
def __init__(self):
"""Constructor."""
<|body_0|>
def configOptionValue(self, section, option):
"""Get a... | stack_v2_sparse_classes_75kplus_train_069370 | 2,381 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get a configuration value from the local configuration file. :param section: String of section in config file. :param option: String of option in config file. :returns: The value contained in ... | 2 | stack_v2_sparse_classes_30k_train_003266 | Implement the Python class `SIConfiger` described below.
Class description:
Supports site-level config for the Smart Grid PV Inverter project. The default path is ~/.smart-inverter.cfg. Usage: configer = SIConfiger()
Method signatures and docstrings:
- def __init__(self): Constructor.
- def configOptionValue(self, se... | Implement the Python class `SIConfiger` described below.
Class description:
Supports site-level config for the Smart Grid PV Inverter project. The default path is ~/.smart-inverter.cfg. Usage: configer = SIConfiger()
Method signatures and docstrings:
- def __init__(self): Constructor.
- def configOptionValue(self, se... | 34c94e304373e16bfe7313905a432ce979ffed77 | <|skeleton|>
class SIConfiger:
"""Supports site-level config for the Smart Grid PV Inverter project. The default path is ~/.smart-inverter.cfg. Usage: configer = SIConfiger()"""
def __init__(self):
"""Constructor."""
<|body_0|>
def configOptionValue(self, section, option):
"""Get a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SIConfiger:
"""Supports site-level config for the Smart Grid PV Inverter project. The default path is ~/.smart-inverter.cfg. Usage: configer = SIConfiger()"""
def __init__(self):
"""Constructor."""
self._config = ConfigParser.ConfigParser()
self.logger = SEKLogger(__name__, 'INFO'... | the_stack_v2_python_sparse | src/si_configer.py | Hawaii-Smart-Energy-Project/Smart-Grid-PV-Inverter | train | 0 |
94bee6a377ebd61106d4c5da29f84a1645f56fda | [
"args = parser.parse_args()\nrequest_id = args.get('request_id')\nstatus_num = args.get('status_num')\npage = args.get('pgnum')\nif not page:\n page = 1\noptions = {'page': page, 'request_id': request_id, 'status_num': status_num}\nif log_list_c(options=options):\n request_logs, pg = log_list_c(options=option... | <|body_start_0|>
args = parser.parse_args()
request_id = args.get('request_id')
status_num = args.get('status_num')
page = args.get('pgnum')
if not page:
page = 1
options = {'page': page, 'request_id': request_id, 'status_num': status_num}
if log_list_... | LogRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogRequest:
def get(self):
"""获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: descrip... | stack_v2_sparse_classes_75kplus_train_069371 | 3,392 | no_license | [
{
"docstring": "获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: description: A single logs item schema: id: R... | 2 | stack_v2_sparse_classes_30k_train_015923 | Implement the Python class `LogRequest` described below.
Class description:
Implement the LogRequest class.
Method signatures and docstrings:
- def get(self): 获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page ty... | Implement the Python class `LogRequest` described below.
Class description:
Implement the LogRequest class.
Method signatures and docstrings:
- def get(self): 获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page ty... | 73246bbd492fd991e0329b9a011b5380b11a1618 | <|skeleton|>
class LogRequest:
def get(self):
"""获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: descrip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogRequest:
def get(self):
"""获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: description: A single... | the_stack_v2_python_sparse | app/main/base/apis/request_logs.py | zhouliang0v0/naguan-kpy | train | 0 | |
54c51209b13707160e6bce9db7d81ae055e9972d | [
"self.occupancy_function = occupancy_function\nself.mesh = mesh\nself.weights = weights\nwf = WeightingFunctionPointwise(mesh.vertices, weights)\nself.lbs_deformer = LBSDeformer(wf)",
"posed_vertices = self.lbs_deformer.apply_lbs(self.mesh.vertices, pose)\nresult = dict()\npsb = PointSamplerBox(self.mesh.bounds)\... | <|body_start_0|>
self.occupancy_function = occupancy_function
self.mesh = mesh
self.weights = weights
wf = WeightingFunctionPointwise(mesh.vertices, weights)
self.lbs_deformer = LBSDeformer(wf)
<|end_body_0|>
<|body_start_1|>
posed_vertices = self.lbs_deformer.apply_lbs(... | Class for creating sample data for use in training the weight network (W_omega) | WeightTrainSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightTrainSampler:
"""Class for creating sample data for use in training the weight network (W_omega)"""
def __init__(self, occupancy_function, mesh, weights):
""":param occupancy_function, OccupancyFunction, to use when calculating the occupancy values of sample points :param mesh:... | stack_v2_sparse_classes_75kplus_train_069372 | 2,985 | permissive | [
{
"docstring": ":param occupancy_function, OccupancyFunction, to use when calculating the occupancy values of sample points :param mesh: Trimesh.Mesh, mesh to sample from :param weights: Numpy array-like, VxB, vertex weights. (Perhaps should be WeightingFunction)",
"name": "__init__",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_039526 | Implement the Python class `WeightTrainSampler` described below.
Class description:
Class for creating sample data for use in training the weight network (W_omega)
Method signatures and docstrings:
- def __init__(self, occupancy_function, mesh, weights): :param occupancy_function, OccupancyFunction, to use when calcu... | Implement the Python class `WeightTrainSampler` described below.
Class description:
Class for creating sample data for use in training the weight network (W_omega)
Method signatures and docstrings:
- def __init__(self, occupancy_function, mesh, weights): :param occupancy_function, OccupancyFunction, to use when calcu... | c6568818ec8acdb0fe4bd8d197278f0abb361d0b | <|skeleton|>
class WeightTrainSampler:
"""Class for creating sample data for use in training the weight network (W_omega)"""
def __init__(self, occupancy_function, mesh, weights):
""":param occupancy_function, OccupancyFunction, to use when calculating the occupancy values of sample points :param mesh:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeightTrainSampler:
"""Class for creating sample data for use in training the weight network (W_omega)"""
def __init__(self, occupancy_function, mesh, weights):
""":param occupancy_function, OccupancyFunction, to use when calculating the occupancy values of sample points :param mesh: Trimesh.Mesh... | the_stack_v2_python_sparse | NiLBS/sampling/weight_train_sampler.py | joemarch010/NiLBS | train | 2 |
2c56abeb2396749edb0ac6a156b985fc6cf2b939 | [
"form_opts = self.request.GET.copy()\ntry:\n del form_opts['page']\nexcept KeyError:\n pass\nself.form = self.form_class(form_opts or self.form_class.defaults)\nif self.form.is_valid():\n search_opts = self.form.cleaned_data\n if search_opts['content_type'] != 'all':\n if search_opts['content_typ... | <|body_start_0|>
form_opts = self.request.GET.copy()
try:
del form_opts['page']
except KeyError:
pass
self.form = self.form_class(form_opts or self.form_class.defaults)
if self.form.is_valid():
search_opts = self.form.cleaned_data
i... | SearchView | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchView:
def get(self, *args, **kwargs):
"""Process form for :class:`SearchView`."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Retrieve Solr queries for :class:`SearchView` context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form_o... | stack_v2_sparse_classes_75kplus_train_069373 | 37,410 | permissive | [
{
"docstring": "Process form for :class:`SearchView`.",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Retrieve Solr queries for :class:`SearchView` context.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021311 | Implement the Python class `SearchView` described below.
Class description:
Implement the SearchView class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): Process form for :class:`SearchView`.
- def get_context_data(self, **kwargs): Retrieve Solr queries for :class:`SearchView` context. | Implement the Python class `SearchView` described below.
Class description:
Implement the SearchView class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): Process form for :class:`SearchView`.
- def get_context_data(self, **kwargs): Retrieve Solr queries for :class:`SearchView` context.
<|skelet... | 6371bb1266d7751af59aeaa3426ef7ac02a1fe17 | <|skeleton|>
class SearchView:
def get(self, *args, **kwargs):
"""Process form for :class:`SearchView`."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Retrieve Solr queries for :class:`SearchView` context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchView:
def get(self, *args, **kwargs):
"""Process form for :class:`SearchView`."""
form_opts = self.request.GET.copy()
try:
del form_opts['page']
except KeyError:
pass
self.form = self.form_class(form_opts or self.form_class.defaults)
... | the_stack_v2_python_sparse | derrida/books/views.py | Princeton-CDH/derrida-django | train | 13 | |
03ac7aefade9c2cdcb7d33608e9c6218a537d7fd | [
"dummy_node = ListNode(0, head)\npre_node = dummy_node\nwhile pre_node.next and pre_node.next.next:\n if pre_node.next.val == pre_node.next.next.val:\n duplicate_node = pre_node.next\n while duplicate_node.next and duplicate_node.val == duplicate_node.next.val:\n duplicate_node.next = du... | <|body_start_0|>
dummy_node = ListNode(0, head)
pre_node = dummy_node
while pre_node.next and pre_node.next.next:
if pre_node.next.val == pre_node.next.next.val:
duplicate_node = pre_node.next
while duplicate_node.next and duplicate_node.val == duplica... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy_node = ListNode(0, h... | stack_v2_sparse_classes_75kplus_train_069374 | 1,904 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates1",
"signature": "def deleteDuplicates1(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000970 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates1(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates1(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 9d394cd2862703cfb7a7b505b35deda7450a692e | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
dummy_node = ListNode(0, head)
pre_node = dummy_node
while pre_node.next and pre_node.next.next:
if pre_node.next.val == pre_node.next.next.val:
duplicate_node = ... | the_stack_v2_python_sparse | 82.删除排序链表中的重复元素-ii.py | Ezi4Zy/leetcode | train | 0 | |
71d305bfd850dbee94b3f4b3c6a359dc403a8af3 | [
"mongo = database.MongoDBConnection()\nwith mongo:\n db = mongo.connection.HPNortonDatabase\n products = db['products']\n customers = db['customers']\n rentals = db['rentals']\nproducts.drop()\ncustomers.drop()\nrentals.drop()",
"directory_path = 'data'\ntuple1, tuple2 = database.import_data(directory... | <|body_start_0|>
mongo = database.MongoDBConnection()
with mongo:
db = mongo.connection.HPNortonDatabase
products = db['products']
customers = db['customers']
rentals = db['rentals']
products.drop()
customers.drop()
rentals.drop()
<... | Tests for the database module | DatabaseTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseTests:
"""Tests for the database module"""
def setUp(self):
"""Sets up database for each test"""
<|body_0|>
def test_import_data(self):
"""Tests the import_data function"""
<|body_1|>
def test_show_available_products(self):
"""Tests t... | stack_v2_sparse_classes_75kplus_train_069375 | 3,519 | no_license | [
{
"docstring": "Sets up database for each test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the import_data function",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "Tests the show_available_products module",... | 4 | stack_v2_sparse_classes_30k_train_048878 | Implement the Python class `DatabaseTests` described below.
Class description:
Tests for the database module
Method signatures and docstrings:
- def setUp(self): Sets up database for each test
- def test_import_data(self): Tests the import_data function
- def test_show_available_products(self): Tests the show_availab... | Implement the Python class `DatabaseTests` described below.
Class description:
Tests for the database module
Method signatures and docstrings:
- def setUp(self): Sets up database for each test
- def test_import_data(self): Tests the import_data function
- def test_show_available_products(self): Tests the show_availab... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class DatabaseTests:
"""Tests for the database module"""
def setUp(self):
"""Sets up database for each test"""
<|body_0|>
def test_import_data(self):
"""Tests the import_data function"""
<|body_1|>
def test_show_available_products(self):
"""Tests t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseTests:
"""Tests for the database module"""
def setUp(self):
"""Sets up database for each test"""
mongo = database.MongoDBConnection()
with mongo:
db = mongo.connection.HPNortonDatabase
products = db['products']
customers = db['customers'... | the_stack_v2_python_sparse | students/amirg/lesson09/assignment/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
e0d3fd0e0b7563cdde1016e0236299cb0d3b6369 | [
"self.screen = turtle.Screen()\nself.screen.bgcolor('lightgrey')\nself.turtle = turtle.Turtle(shape='turtle')\nself.turtle.pensize(3)",
"self.turtle.penup()\nself.turtle.setposition(x, y)\nself.turtle.pendown()\nself.turtle.color(color)\nself.turtle.pensize(10)\nself.turtle.circle(radius)",
"positions = [(0, 0,... | <|body_start_0|>
self.screen = turtle.Screen()
self.screen.bgcolor('lightgrey')
self.turtle = turtle.Turtle(shape='turtle')
self.turtle.pensize(3)
<|end_body_0|>
<|body_start_1|>
self.turtle.penup()
self.turtle.setposition(x, y)
self.turtle.pendown()
self... | MyTurtle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyTurtle:
def __init__(self):
"""Turtle Constructor"""
<|body_0|>
def draw_circle(self, x, y, color, radius=50):
"""Moves the turtle to the correct position and draws a circle"""
<|body_1|>
def draw_olympic_symbol(self):
"""Iterates over a set of... | stack_v2_sparse_classes_75kplus_train_069376 | 1,583 | permissive | [
{
"docstring": "Turtle Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Moves the turtle to the correct position and draws a circle",
"name": "draw_circle",
"signature": "def draw_circle(self, x, y, color, radius=50)"
},
{
"docstring": "Itera... | 4 | stack_v2_sparse_classes_30k_train_019391 | Implement the Python class `MyTurtle` described below.
Class description:
Implement the MyTurtle class.
Method signatures and docstrings:
- def __init__(self): Turtle Constructor
- def draw_circle(self, x, y, color, radius=50): Moves the turtle to the correct position and draws a circle
- def draw_olympic_symbol(self... | Implement the Python class `MyTurtle` described below.
Class description:
Implement the MyTurtle class.
Method signatures and docstrings:
- def __init__(self): Turtle Constructor
- def draw_circle(self, x, y, color, radius=50): Moves the turtle to the correct position and draws a circle
- def draw_olympic_symbol(self... | 63b448a35c5668790720d0fe414600510b9fe61a | <|skeleton|>
class MyTurtle:
def __init__(self):
"""Turtle Constructor"""
<|body_0|>
def draw_circle(self, x, y, color, radius=50):
"""Moves the turtle to the correct position and draws a circle"""
<|body_1|>
def draw_olympic_symbol(self):
"""Iterates over a set of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyTurtle:
def __init__(self):
"""Turtle Constructor"""
self.screen = turtle.Screen()
self.screen.bgcolor('lightgrey')
self.turtle = turtle.Turtle(shape='turtle')
self.turtle.pensize(3)
def draw_circle(self, x, y, color, radius=50):
"""Moves the turtle to th... | the_stack_v2_python_sparse | algorithm/python-algorithm/other-tools/turtle-graphics/drawOlypicSymbol.py | wangdingqiao/programmer-evolution-plan | train | 4 | |
5a625280f2b7359100e6b7ab4cc1ebf2959f956e | [
"self._click_add_new_button2_()\nself._set_product_name_(productname)\nself._set_meta_tag_(keywords)\nself._click_data_tab_()\nself._set_model_name_(modelname)\nself._click_save_button_()",
"self._click_edit_button_()\nself._clear_product_name_()\nself._set_product_name_(productname)\nself._clear_meta_tag_()\nsel... | <|body_start_0|>
self._click_add_new_button2_()
self._set_product_name_(productname)
self._set_meta_tag_(keywords)
self._click_data_tab_()
self._set_model_name_(modelname)
self._click_save_button_()
<|end_body_0|>
<|body_start_1|>
self._click_edit_button_()
... | Managing product operations | ProductManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductManager:
"""Managing product operations"""
def add_new_product(self, productname, keywords, modelname):
"""Add new product to site"""
<|body_0|>
def edit_product(self, productname, keywords, modelname):
"""Edit created product"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_069377 | 6,654 | permissive | [
{
"docstring": "Add new product to site",
"name": "add_new_product",
"signature": "def add_new_product(self, productname, keywords, modelname)"
},
{
"docstring": "Edit created product",
"name": "edit_product",
"signature": "def edit_product(self, productname, keywords, modelname)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045068 | Implement the Python class `ProductManager` described below.
Class description:
Managing product operations
Method signatures and docstrings:
- def add_new_product(self, productname, keywords, modelname): Add new product to site
- def edit_product(self, productname, keywords, modelname): Edit created product | Implement the Python class `ProductManager` described below.
Class description:
Managing product operations
Method signatures and docstrings:
- def add_new_product(self, productname, keywords, modelname): Add new product to site
- def edit_product(self, productname, keywords, modelname): Edit created product
<|skele... | 510a4f1971b35048d760fcc45098e511b81bea31 | <|skeleton|>
class ProductManager:
"""Managing product operations"""
def add_new_product(self, productname, keywords, modelname):
"""Add new product to site"""
<|body_0|>
def edit_product(self, productname, keywords, modelname):
"""Edit created product"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductManager:
"""Managing product operations"""
def add_new_product(self, productname, keywords, modelname):
"""Add new product to site"""
self._click_add_new_button2_()
self._set_product_name_(productname)
self._set_meta_tag_(keywords)
self._click_data_tab_()
... | the_stack_v2_python_sparse | SeleniumCloud/models/page_objects/page_objects.py | BahrmaLe/otus_python_homework | train | 1 |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryLocatorV2.from_string(lib_key_str)\ntext_search = request.query_params.get('text_search', None)\nblock_types = request.query_params.getlist('block_type') or None\napi.require_permission_for_library_key(key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY)\nresult = api.get_library_blocks(key, ... | <|body_start_0|>
key = LibraryLocatorV2.from_string(lib_key_str)
text_search = request.query_params.get('text_search', None)
block_types = request.query_params.getlist('block_type') or None
api.require_permission_for_library_key(key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRAR... | Views to work with XBlocks in a specific content library. | LibraryBlocksView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryBlocksView:
"""Views to work with XBlocks in a specific content library."""
def get(self, request, lib_key_str):
"""Get the list of all top-level blocks in this content library"""
<|body_0|>
def post(self, request, lib_key_str):
"""Add a new XBlock to this... | stack_v2_sparse_classes_75kplus_train_069378 | 42,120 | permissive | [
{
"docstring": "Get the list of all top-level blocks in this content library",
"name": "get",
"signature": "def get(self, request, lib_key_str)"
},
{
"docstring": "Add a new XBlock to this content library",
"name": "post",
"signature": "def post(self, request, lib_key_str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041542 | Implement the Python class `LibraryBlocksView` described below.
Class description:
Views to work with XBlocks in a specific content library.
Method signatures and docstrings:
- def get(self, request, lib_key_str): Get the list of all top-level blocks in this content library
- def post(self, request, lib_key_str): Add... | Implement the Python class `LibraryBlocksView` described below.
Class description:
Views to work with XBlocks in a specific content library.
Method signatures and docstrings:
- def get(self, request, lib_key_str): Get the list of all top-level blocks in this content library
- def post(self, request, lib_key_str): Add... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryBlocksView:
"""Views to work with XBlocks in a specific content library."""
def get(self, request, lib_key_str):
"""Get the list of all top-level blocks in this content library"""
<|body_0|>
def post(self, request, lib_key_str):
"""Add a new XBlock to this... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LibraryBlocksView:
"""Views to work with XBlocks in a specific content library."""
def get(self, request, lib_key_str):
"""Get the list of all top-level blocks in this content library"""
key = LibraryLocatorV2.from_string(lib_key_str)
text_search = request.query_params.get('text_s... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
5d34bd06a6c6d25ddb1504b9a11774fa159c88f1 | [
"super(DiffSmoothedCELoss, self).__init__(**kw)\nself.reduction, self.ignore_indices = (reduction, ignore_index)\nself.mode = mode\nself.alpha, self.beta = (alpha, beta)\nself.kl = torch.nn.KLDivLoss(reduction='none')\nself.logsm = torch.nn.LogSoftmax(-1) if self.mode == 'logits' else None\nself.sm = torch.nn.Softm... | <|body_start_0|>
super(DiffSmoothedCELoss, self).__init__(**kw)
self.reduction, self.ignore_indices = (reduction, ignore_index)
self.mode = mode
self.alpha, self.beta = (alpha, beta)
self.kl = torch.nn.KLDivLoss(reduction='none')
self.logsm = torch.nn.LogSoftmax(-1) if se... | DiffSmoothedCELoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiffSmoothedCELoss:
def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw):
""":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform... | stack_v2_sparse_classes_75kplus_train_069379 | 20,169 | permissive | [
{
"docstring": ":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform distribution when mixing target for incorrectly predicted tokens (normal label smoothing) :param mode: :param kw:",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_004546 | Implement the Python class `DiffSmoothedCELoss` described below.
Class description:
Implement the DiffSmoothedCELoss class.
Method signatures and docstrings:
- def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw): :param reduction: :param ignore_index: :param alpha: weight... | Implement the Python class `DiffSmoothedCELoss` described below.
Class description:
Implement the DiffSmoothedCELoss class.
Method signatures and docstrings:
- def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw): :param reduction: :param ignore_index: :param alpha: weight... | 8cf2e697830ef09dca40692e7d254b61f9ffdf8d | <|skeleton|>
class DiffSmoothedCELoss:
def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw):
""":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiffSmoothedCELoss:
def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw):
""":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform distribution ... | the_stack_v2_python_sparse | kbcqa/method_ir/grounding/semantic_matching/qelos/loss.py | BayLee001/SkeletonKBQA | train | 0 | |
8126a329e0e429b4df93e720052b5c970961c734 | [
"super().__init__(parent)\nself['show'] = 'headings'\nself['columns'] = [column['name'] for column in columns]\nfor column in columns:\n self.heading(column['name'], text=column['title'])\n self.column(column['name'], anchor=column['anchor'])\ntry:\n getattr(self, 'columns')\nexcept AttributeError:\n pa... | <|body_start_0|>
super().__init__(parent)
self['show'] = 'headings'
self['columns'] = [column['name'] for column in columns]
for column in columns:
self.heading(column['name'], text=column['title'])
self.column(column['name'], anchor=column['anchor'])
try:... | CustomTreeview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomTreeview:
def __init__(self, parent, columns):
"""Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts"""
<|body_0|>
def insert(self, parent, index, tags=None, **kwargs):
"""Call super() insert wi... | stack_v2_sparse_classes_75kplus_train_069380 | 9,918 | no_license | [
{
"docstring": "Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts",
"name": "__init__",
"signature": "def __init__(self, parent, columns)"
},
{
"docstring": "Call super() insert with convenient value specifications.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_026890 | Implement the Python class `CustomTreeview` described below.
Class description:
Implement the CustomTreeview class.
Method signatures and docstrings:
- def __init__(self, parent, columns): Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts
- def inser... | Implement the Python class `CustomTreeview` described below.
Class description:
Implement the CustomTreeview class.
Method signatures and docstrings:
- def __init__(self, parent, columns): Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts
- def inser... | 3ba9965a6d164d3fa1704015176394e26f0c3560 | <|skeleton|>
class CustomTreeview:
def __init__(self, parent, columns):
"""Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts"""
<|body_0|>
def insert(self, parent, index, tags=None, **kwargs):
"""Call super() insert wi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomTreeview:
def __init__(self, parent, columns):
"""Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts"""
super().__init__(parent)
self['show'] = 'headings'
self['columns'] = [column['name'] for column in co... | the_stack_v2_python_sparse | autograde/aggui.py | AndrewMHenry/capstone-ag | train | 0 | |
83d11964d0b2bf3a02d6bf217008b0f883e4a46a | [
"if not select_sort:\n select_sort = 'Id order'\nif table:\n View.tab_view(title, cls._sort(table, select_sort), columns)",
"if select_sort == 'Number order':\n table = sorted(table, key=lambda x: x['number'], reverse=False)\nif select_sort == 'Alphabetical order':\n table = sorted(table, key=lambda i... | <|body_start_0|>
if not select_sort:
select_sort = 'Id order'
if table:
View.tab_view(title, cls._sort(table, select_sort), columns)
<|end_body_0|>
<|body_start_1|>
if select_sort == 'Number order':
table = sorted(table, key=lambda x: x['number'], reverse=Fal... | class for make tables | TableService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableService:
"""class for make tables"""
def table(cls, title, columns, table, select_sort=None):
"""Method to create an array"""
<|body_0|>
def _sort(cls, table, select_sort):
"""Private method for sorting lists for arrays"""
<|body_1|>
def table_s... | stack_v2_sparse_classes_75kplus_train_069381 | 3,004 | no_license | [
{
"docstring": "Method to create an array",
"name": "table",
"signature": "def table(cls, title, columns, table, select_sort=None)"
},
{
"docstring": "Private method for sorting lists for arrays",
"name": "_sort",
"signature": "def _sort(cls, table, select_sort)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_024182 | Implement the Python class `TableService` described below.
Class description:
class for make tables
Method signatures and docstrings:
- def table(cls, title, columns, table, select_sort=None): Method to create an array
- def _sort(cls, table, select_sort): Private method for sorting lists for arrays
- def table_sort_... | Implement the Python class `TableService` described below.
Class description:
class for make tables
Method signatures and docstrings:
- def table(cls, title, columns, table, select_sort=None): Method to create an array
- def _sort(cls, table, select_sort): Private method for sorting lists for arrays
- def table_sort_... | 0e906ee6d94372b8ff2acc0067008c7ace9eb51a | <|skeleton|>
class TableService:
"""class for make tables"""
def table(cls, title, columns, table, select_sort=None):
"""Method to create an array"""
<|body_0|>
def _sort(cls, table, select_sort):
"""Private method for sorting lists for arrays"""
<|body_1|>
def table_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TableService:
"""class for make tables"""
def table(cls, title, columns, table, select_sort=None):
"""Method to create an array"""
if not select_sort:
select_sort = 'Id order'
if table:
View.tab_view(title, cls._sort(table, select_sort), columns)
def _... | the_stack_v2_python_sparse | app/services/table_service.py | Arnaud290/OC_P4 | train | 0 |
15f653a284dadeca37efc9ab6238865f0db0998a | [
"self.deg, self.ntheta, self.nphi = (deg, ntheta, nphi)\nif self.ntheta < deg:\n self.ntheta = deg\nif self.nphi < 2 * deg - 1:\n self.nphi = 2 * deg - 1\nself.thetas, self.weights = quad.gaussleg(self.ntheta)",
"if forward:\n cscale = (1j ** (i % 4) for i in range(1, self.deg + 1))\nelse:\n cscale = ... | <|body_start_0|>
self.deg, self.ntheta, self.nphi = (deg, ntheta, nphi)
if self.ntheta < deg:
self.ntheta = deg
if self.nphi < 2 * deg - 1:
self.nphi = 2 * deg - 1
self.thetas, self.weights = quad.gaussleg(self.ntheta)
<|end_body_0|>
<|body_start_1|>
if f... | Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients. | SHTransform | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SHTransform:
"""Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients."""
def __init__(self, deg, ntheta=0, nphi=0):
"""Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar a... | stack_v2_sparse_classes_75kplus_train_069382 | 4,016 | permissive | [
{
"docstring": "Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar and nphi azimuthal angular samples.",
"name": "__init__",
"signature": "def __init__(self, deg, ntheta=0, nphi=0)"
},
{
"docstring": "Scale the spherical harmonic coefficients to relate ... | 4 | stack_v2_sparse_classes_30k_train_048453 | Implement the Python class `SHTransform` described below.
Class description:
Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients.
Method signatures and docstrings:
- def __init__(self, deg, ntheta=0, nphi=0): Establishes a harmonic transform betwe... | Implement the Python class `SHTransform` described below.
Class description:
Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients.
Method signatures and docstrings:
- def __init__(self, deg, ntheta=0, nphi=0): Establishes a harmonic transform betwe... | 5fabc9c1f410bf49b674bfb4427fe1f05ad251ed | <|skeleton|>
class SHTransform:
"""Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients."""
def __init__(self, deg, ntheta=0, nphi=0):
"""Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SHTransform:
"""Encapsulates a spherical harmonic transform to convert between spherical harmonic coefficients and plane-wave coefficients."""
def __init__(self, deg, ntheta=0, nphi=0):
"""Establishes a harmonic transform between coefficients of maximum degree deg with ntheta polar and nphi azimu... | the_stack_v2_python_sparse | pycwp/shtransform.py | ahesford/pycwp | train | 0 |
03ea92b7d3a998b9eec90f5254ee8546e829c74b | [
"self.log = logger.getLogger(log_name)\nself.shell = shell.ShellCommands(log_name=log_name)\nself.distro = None\nself.packages_dict = packages_dict\nself.install_process = {'apt': \"apt-get update && apt-get -o Dpkg::Options:='--force-confold' -o Dpkg::Options:='--force-confdef' -y install %s\", 'yum': 'yum -y inst... | <|body_start_0|>
self.log = logger.getLogger(log_name)
self.shell = shell.ShellCommands(log_name=log_name)
self.distro = None
self.packages_dict = packages_dict
self.install_process = {'apt': "apt-get update && apt-get -o Dpkg::Options:='--force-confold' -o Dpkg::Options:='--forc... | PackageInstaller | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageInstaller:
def __init__(self, packages_dict, log_name=__name__):
"""Install packages on a local Linux Operating System. :param packages_dict: ``dict`` :param log_name: ``str`` This is used to log against an existing log handler."""
<|body_0|>
def _installer(self, pack... | stack_v2_sparse_classes_75kplus_train_069383 | 3,299 | permissive | [
{
"docstring": "Install packages on a local Linux Operating System. :param packages_dict: ``dict`` :param log_name: ``str`` This is used to log against an existing log handler.",
"name": "__init__",
"signature": "def __init__(self, packages_dict, log_name=__name__)"
},
{
"docstring": "Install op... | 3 | stack_v2_sparse_classes_30k_train_034132 | Implement the Python class `PackageInstaller` described below.
Class description:
Implement the PackageInstaller class.
Method signatures and docstrings:
- def __init__(self, packages_dict, log_name=__name__): Install packages on a local Linux Operating System. :param packages_dict: ``dict`` :param log_name: ``str`` ... | Implement the Python class `PackageInstaller` described below.
Class description:
Implement the PackageInstaller class.
Method signatures and docstrings:
- def __init__(self, packages_dict, log_name=__name__): Install packages on a local Linux Operating System. :param packages_dict: ``dict`` :param log_name: ``str`` ... | 5038111ce02521caa2558117e3bae9e1e806d315 | <|skeleton|>
class PackageInstaller:
def __init__(self, packages_dict, log_name=__name__):
"""Install packages on a local Linux Operating System. :param packages_dict: ``dict`` :param log_name: ``str`` This is used to log against an existing log handler."""
<|body_0|>
def _installer(self, pack... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PackageInstaller:
def __init__(self, packages_dict, log_name=__name__):
"""Install packages on a local Linux Operating System. :param packages_dict: ``dict`` :param log_name: ``str`` This is used to log against an existing log handler."""
self.log = logger.getLogger(log_name)
self.shel... | the_stack_v2_python_sparse | cloudlib/package_installer.py | cloudnull/cloudlib | train | 0 | |
530c32358ad998b35ff6764ec497e7c99196d793 | [
"path = None\nif self.oargs_use_wc:\n path = os.getcwd()\nreturn path",
"if self.func_defaults is not None:\n for k, v in self.func_defaults.iteritems():\n info.add(k, v)\nfor i in self.__dict__.keys():\n if i.startswith('oargs') or i in info or i in self.oargs or (i == 'func_defaults'):\n ... | <|body_start_0|>
path = None
if self.oargs_use_wc:
path = os.getcwd()
return path
<|end_body_0|>
<|body_start_1|>
if self.func_defaults is not None:
for k, v in self.func_defaults.iteritems():
info.add(k, v)
for i in self.__dict__.keys():
... | Resolves osc url-like arguments. | _OscNamespace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _OscNamespace:
"""Resolves osc url-like arguments."""
def _path(self):
"""Returns a path. If the command is not context sensitive None is returned."""
<|body_0|>
def _add_items(self, info):
"""Add parsed items to the info object."""
<|body_1|>
def _r... | stack_v2_sparse_classes_75kplus_train_069384 | 4,491 | no_license | [
{
"docstring": "Returns a path. If the command is not context sensitive None is returned.",
"name": "_path",
"signature": "def _path(self)"
},
{
"docstring": "Add parsed items to the info object.",
"name": "_add_items",
"signature": "def _add_items(self, info)"
},
{
"docstring": ... | 5 | stack_v2_sparse_classes_30k_val_003024 | Implement the Python class `_OscNamespace` described below.
Class description:
Resolves osc url-like arguments.
Method signatures and docstrings:
- def _path(self): Returns a path. If the command is not context sensitive None is returned.
- def _add_items(self, info): Add parsed items to the info object.
- def _resol... | Implement the Python class `_OscNamespace` described below.
Class description:
Resolves osc url-like arguments.
Method signatures and docstrings:
- def _path(self): Returns a path. If the command is not context sensitive None is returned.
- def _add_items(self, info): Add parsed items to the info object.
- def _resol... | fd75a75371ae33740a68913ca8ab64a9e8e6654a | <|skeleton|>
class _OscNamespace:
"""Resolves osc url-like arguments."""
def _path(self):
"""Returns a path. If the command is not context sensitive None is returned."""
<|body_0|>
def _add_items(self, info):
"""Add parsed items to the info object."""
<|body_1|>
def _r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _OscNamespace:
"""Resolves osc url-like arguments."""
def _path(self):
"""Returns a path. If the command is not context sensitive None is returned."""
path = None
if self.oargs_use_wc:
path = os.getcwd()
return path
def _add_items(self, info):
"""A... | the_stack_v2_python_sparse | osc2/cli/parse.py | openSUSE/osc2 | train | 16 |
d9c3c4cae259d1e1385aa58aec2e53d8bb97f985 | [
"if isinstance(cache, DiskCache):\n return cache\nreturn DiskCache(directory=self.path, min_file_size=0, size_limit=self.maxsize, eviction_policy=self.eviction)",
"if self.maxsize == 0:\n return\nwith self.newcache(cache) as disk:\n if disk.get(VERSION_KEY) != VERSION:\n LOGS.info('%s version is i... | <|body_start_0|>
if isinstance(cache, DiskCache):
return cache
return DiskCache(directory=self.path, min_file_size=0, size_limit=self.maxsize, eviction_policy=self.eviction)
<|end_body_0|>
<|body_start_1|>
if self.maxsize == 0:
return
with self.newcache(cache) as... | The disk cache configuration | DiskCacheConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiskCacheConfig:
"""The disk cache configuration"""
def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache:
"""create new cache"""
<|body_0|>
def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APPVERSION, cache: Optional[DiskCac... | stack_v2_sparse_classes_75kplus_train_069385 | 9,735 | no_license | [
{
"docstring": "create new cache",
"name": "newcache",
"signature": "def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache"
},
{
"docstring": "add items to the disk",
"name": "insert",
"signature": "def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version... | 6 | stack_v2_sparse_classes_30k_train_016577 | Implement the Python class `DiskCacheConfig` described below.
Class description:
The disk cache configuration
Method signatures and docstrings:
- def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache: create new cache
- def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APP... | Implement the Python class `DiskCacheConfig` described below.
Class description:
The disk cache configuration
Method signatures and docstrings:
- def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache: create new cache
- def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APP... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class DiskCacheConfig:
"""The disk cache configuration"""
def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache:
"""create new cache"""
<|body_0|>
def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APPVERSION, cache: Optional[DiskCac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiskCacheConfig:
"""The disk cache configuration"""
def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache:
"""create new cache"""
if isinstance(cache, DiskCache):
return cache
return DiskCache(directory=self.path, min_file_size=0, size_limit=self.maxsize, ev... | the_stack_v2_python_sparse | src/peakcalling/model/_diskcache.py | depixusgenome/trackanalysis | train | 0 |
245291b50f077493e21386d9a873b85fbf131dd6 | [
"self.data = []\nif data is not None:\n if type(data) != list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n self.lambtha = 1 / (sum(data) / len(data))\nelif lambtha >= 1:\n self.lambtha = float(lambtha)\nelse:\n r... | <|body_start_0|>
self.data = []
if data is not None:
if type(data) != list:
raise TypeError('data must be a list')
if len(data) < 2:
raise ValueError('data must contain multiple values')
self.lambtha = 1 / (sum(data) / len(data))
... | This class is to represent a exponencial distribution | Exponential | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""This class is to represent a exponencial distribution"""
def __init__(self, data=None, lambtha=1.0):
"""All begins here"""
<|body_0|>
def pdf(self, x):
"""Method to calculate the pdf"""
<|body_1|>
def cdf(self, x):
"""This met... | stack_v2_sparse_classes_75kplus_train_069386 | 1,228 | permissive | [
{
"docstring": "All begins here",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Method to calculate the pdf",
"name": "pdf",
"signature": "def pdf(self, x)"
},
{
"docstring": "This method calculates the CDF",
"name": "cdf",
... | 3 | stack_v2_sparse_classes_30k_train_041500 | Implement the Python class `Exponential` described below.
Class description:
This class is to represent a exponencial distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): All begins here
- def pdf(self, x): Method to calculate the pdf
- def cdf(self, x): This method calculates ... | Implement the Python class `Exponential` described below.
Class description:
This class is to represent a exponencial distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): All begins here
- def pdf(self, x): Method to calculate the pdf
- def cdf(self, x): This method calculates ... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class Exponential:
"""This class is to represent a exponencial distribution"""
def __init__(self, data=None, lambtha=1.0):
"""All begins here"""
<|body_0|>
def pdf(self, x):
"""Method to calculate the pdf"""
<|body_1|>
def cdf(self, x):
"""This met... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exponential:
"""This class is to represent a exponencial distribution"""
def __init__(self, data=None, lambtha=1.0):
"""All begins here"""
self.data = []
if data is not None:
if type(data) != list:
raise TypeError('data must be a list')
if l... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | linkem97/holbertonschool-machine_learning | train | 0 |
1df49ac3c6e3effb17700ceb5a0339a69aea3d50 | [
"super(BaseCharmKeystoneSAMLMellonTest, cls).setUpClass()\ncls.application_name = application_name\ncls.test_saml_idp_app_name = test_saml_idp_app_name\ncls.horizon_idp_option_name = horizon_idp_option_name\ncls.horizon_idp_display_name = horizon_idp_display_name\ncls.action = 'get-sp-metadata'\ncls.current_release... | <|body_start_0|>
super(BaseCharmKeystoneSAMLMellonTest, cls).setUpClass()
cls.application_name = application_name
cls.test_saml_idp_app_name = test_saml_idp_app_name
cls.horizon_idp_option_name = horizon_idp_option_name
cls.horizon_idp_display_name = horizon_idp_display_name
... | Charm Keystone SAML Mellon tests. | BaseCharmKeystoneSAMLMellonTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseCharmKeystoneSAMLMellonTest:
"""Charm Keystone SAML Mellon tests."""
def setUpClass(cls, application_name='keystone-saml-mellon', test_saml_idp_app_name='test-saml-idp', horizon_idp_option_name='myidp_mapped', horizon_idp_display_name='myidp via mapped'):
"""Run class setup for r... | stack_v2_sparse_classes_75kplus_train_069387 | 14,567 | permissive | [
{
"docstring": "Run class setup for running Keystone SAML Mellon charm tests.",
"name": "setUpClass",
"signature": "def setUpClass(cls, application_name='keystone-saml-mellon', test_saml_idp_app_name='test-saml-idp', horizon_idp_option_name='myidp_mapped', horizon_idp_display_name='myidp via mapped')"
... | 4 | stack_v2_sparse_classes_30k_train_005393 | Implement the Python class `BaseCharmKeystoneSAMLMellonTest` described below.
Class description:
Charm Keystone SAML Mellon tests.
Method signatures and docstrings:
- def setUpClass(cls, application_name='keystone-saml-mellon', test_saml_idp_app_name='test-saml-idp', horizon_idp_option_name='myidp_mapped', horizon_id... | Implement the Python class `BaseCharmKeystoneSAMLMellonTest` described below.
Class description:
Charm Keystone SAML Mellon tests.
Method signatures and docstrings:
- def setUpClass(cls, application_name='keystone-saml-mellon', test_saml_idp_app_name='test-saml-idp', horizon_idp_option_name='myidp_mapped', horizon_id... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class BaseCharmKeystoneSAMLMellonTest:
"""Charm Keystone SAML Mellon tests."""
def setUpClass(cls, application_name='keystone-saml-mellon', test_saml_idp_app_name='test-saml-idp', horizon_idp_option_name='myidp_mapped', horizon_idp_display_name='myidp via mapped'):
"""Run class setup for r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseCharmKeystoneSAMLMellonTest:
"""Charm Keystone SAML Mellon tests."""
def setUpClass(cls, application_name='keystone-saml-mellon', test_saml_idp_app_name='test-saml-idp', horizon_idp_option_name='myidp_mapped', horizon_idp_display_name='myidp via mapped'):
"""Run class setup for running Keysto... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/saml_mellon/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
20b168d7fda2ee27e2a95c78a81d0db73da17901 | [
"self.cluster = cluster\nself.config = cluster_config\nself.api_client = client.ApiClient(self.config)\nself.graph = Graph(root=self.cluster)",
"collectors = set(all_collectors.keys())\nif len(ArgumentParser.args.k8s_collect) > 0:\n collectors = set(ArgumentParser.args.k8s_collect).intersection(collectors)\nif... | <|body_start_0|>
self.cluster = cluster
self.config = cluster_config
self.api_client = client.ApiClient(self.config)
self.graph = Graph(root=self.cluster)
<|end_body_0|>
<|body_start_1|>
collectors = set(all_collectors.keys())
if len(ArgumentParser.args.k8s_collect) > 0:... | Collects a single Kubernetes Cluster. Responsible for collecting all the resources of an individual cluster. Builds up its own local graph which is then taken by collect_cluster() and merged with the plugin graph. This way we can have many instances of KubernetesCollector running in parallel. All building up individual... | KubernetesCollector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KubernetesCollector:
"""Collects a single Kubernetes Cluster. Responsible for collecting all the resources of an individual cluster. Builds up its own local graph which is then taken by collect_cluster() and merged with the plugin graph. This way we can have many instances of KubernetesCollector ... | stack_v2_sparse_classes_75kplus_train_069388 | 2,517 | permissive | [
{
"docstring": "Args: cluster: The K8S cluster resource object this cluster collector is going to collect.",
"name": "__init__",
"signature": "def __init__(self, cluster: KubernetesCluster, cluster_config: client.Configuration) -> None"
},
{
"docstring": "Runs the actual resource collection acro... | 2 | stack_v2_sparse_classes_30k_train_015324 | Implement the Python class `KubernetesCollector` described below.
Class description:
Collects a single Kubernetes Cluster. Responsible for collecting all the resources of an individual cluster. Builds up its own local graph which is then taken by collect_cluster() and merged with the plugin graph. This way we can have... | Implement the Python class `KubernetesCollector` described below.
Class description:
Collects a single Kubernetes Cluster. Responsible for collecting all the resources of an individual cluster. Builds up its own local graph which is then taken by collect_cluster() and merged with the plugin graph. This way we can have... | 17817d3fbc85a4547a288d85551f7e490ae72c91 | <|skeleton|>
class KubernetesCollector:
"""Collects a single Kubernetes Cluster. Responsible for collecting all the resources of an individual cluster. Builds up its own local graph which is then taken by collect_cluster() and merged with the plugin graph. This way we can have many instances of KubernetesCollector ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KubernetesCollector:
"""Collects a single Kubernetes Cluster. Responsible for collecting all the resources of an individual cluster. Builds up its own local graph which is then taken by collect_cluster() and merged with the plugin graph. This way we can have many instances of KubernetesCollector running in pa... | the_stack_v2_python_sparse | plugins/k8s/cloudkeeper_plugin_k8s/collector.py | asher-lab/cloudkeeper | train | 0 |
5e8b9932734bec2eac26839189e7c997956ec95b | [
"if request.version == 'v6':\n return self.retrieve_impl(request, file_id)\nelif request.version == 'v7':\n return self.retrieve_impl(request, file_id)\nraise Http404()",
"try:\n scale_file = ScaleFile.objects.get_details(file_id)\nexcept ScaleFile.DoesNotExist:\n raise Http404\nserializer = self.get_... | <|body_start_0|>
if request.version == 'v6':
return self.retrieve_impl(request, file_id)
elif request.version == 'v7':
return self.retrieve_impl(request, file_id)
raise Http404()
<|end_body_0|>
<|body_start_1|>
try:
scale_file = ScaleFile.objects.get_... | This view is the endpoint for retrieving details of a scale file. | FileDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDetailsView:
"""This view is the endpoint for retrieving details of a scale file."""
def retrieve(self, request, file_id):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id... | stack_v2_sparse_classes_75kplus_train_069389 | 19,677 | permissive | [
{
"docstring": "Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id: The id of the file :type file_id: int encoded as a string :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to s... | 2 | stack_v2_sparse_classes_30k_train_031182 | Implement the Python class `FileDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a scale file.
Method signatures and docstrings:
- def retrieve(self, request, file_id): Determine api version and call specific method :param request: the HTTP POST request :type reques... | Implement the Python class `FileDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a scale file.
Method signatures and docstrings:
- def retrieve(self, request, file_id): Determine api version and call specific method :param request: the HTTP POST request :type reques... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class FileDetailsView:
"""This view is the endpoint for retrieving details of a scale file."""
def retrieve(self, request, file_id):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileDetailsView:
"""This view is the endpoint for retrieving details of a scale file."""
def retrieve(self, request, file_id):
"""Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :param file_id: The id of t... | the_stack_v2_python_sparse | scale/storage/views.py | kfconsultant/scale | train | 0 |
8f3acc97bb4a060670adfcbc31f9008c689bfa0c | [
"for obj in objs:\n obj.save_tracked_fields()\nobjs = super().bulk_create(objs, **kwargs)\nif objs:\n model = type(objs[0])\n model.call_post_bulk_create(objs, using=self.db)\nreturn objs",
"with transaction.atomic():\n current_dt = timezone.now()\n result = queryset.update(cqrs_revision=F('cqrs_re... | <|body_start_0|>
for obj in objs:
obj.save_tracked_fields()
objs = super().bulk_create(objs, **kwargs)
if objs:
model = type(objs[0])
model.call_post_bulk_create(objs, using=self.db)
return objs
<|end_body_0|>
<|body_start_1|>
with transaction... | MasterManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MasterManager:
def bulk_create(self, objs, **kwargs):
"""Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bul... | stack_v2_sparse_classes_75kplus_train_069390 | 11,329 | permissive | [
{
"docstring": "Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bulk create kwargs",
"name": "bulk_create",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_021135 | Implement the Python class `MasterManager` described below.
Class description:
Implement the MasterManager class.
Method signatures and docstrings:
- def bulk_create(self, objs, **kwargs): Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client ... | Implement the Python class `MasterManager` described below.
Class description:
Implement the MasterManager class.
Method signatures and docstrings:
- def bulk_create(self, objs, **kwargs): Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client ... | c69c81fec47f469e539ed4dc1faa543a7cfd491d | <|skeleton|>
class MasterManager:
def bulk_create(self, objs, **kwargs):
"""Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MasterManager:
def bulk_create(self, objs, **kwargs):
"""Custom bulk create method to support sending of create signals. This can be used only in cases, when IDs are generated on client or DB returns IDs. :param django.db.models.Model objs: List of objects for creation :param kwargs: Bulk create kwarg... | the_stack_v2_python_sparse | dj_cqrs/managers.py | net-free/django-cqrs | train | 0 | |
779e6839dc10c3c81f54eb477406e822a2a8eb44 | [
"super().__init__(logger=logger, config=config, timezone=timezone, max_length=max_length)\nself.user_dic = user_dic or config.get('janome_userdic') if config else None\nif self.user_dic:\n self.tokenizer = Tokenizer(self.user_dic, udic_enc='utf8')\nelse:\n self.tokenizer = Tokenizer()",
"if self.validate(te... | <|body_start_0|>
super().__init__(logger=logger, config=config, timezone=timezone, max_length=max_length)
self.user_dic = user_dic or config.get('janome_userdic') if config else None
if self.user_dic:
self.tokenizer = Tokenizer(self.user_dic, udic_enc='utf8')
else:
... | Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger | JanomeTagger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_069391 | 3,694 | permissive | [
{
"docstring": "Parameters ---------- config : Config, default None Configuration timezone : timezone, default None Timezone logger : Logger, default None Logger max_length : int, default 1000 Max length of the text to parse user_dic : str, default None Path to user dictionary (MeCab IPADIC format)",
"name"... | 2 | stack_v2_sparse_classes_30k_train_020117 | Implement the Python class `JanomeTagger` described below.
Class description:
Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger
Method signatures and docstrings:
- def __init__(self, config=None, timezone=None, logger=None,... | Implement the Python class `JanomeTagger` described below.
Class description:
Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger
Method signatures and docstrings:
- def __init__(self, config=None, timezone=None, logger=None,... | dd8cd7d244b6e6e4133c8e73d637ded8a8c6846f | <|skeleton|>
class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
"""Parameters... | the_stack_v2_python_sparse | minette/tagger/janometagger.py | uezo/minette-python | train | 33 |
0b3068aec1ecc933b9a2f6b3b587809c033a5e3e | [
"if xsID in self:\n return dict.__getitem__(self, xsID)\nxsType = xsID[0]\nbuGroup = xsID[1]\nexistingXsOpts = [xsOpt for xsOpt in self.values() if xsOpt.xsType == xsType and xsOpt.buGroup < buGroup]\nif not any(existingXsOpts):\n return self._getDefault(xsID)\nelse:\n return sorted(existingXsOpts, key=lam... | <|body_start_0|>
if xsID in self:
return dict.__getitem__(self, xsID)
xsType = xsID[0]
buGroup = xsID[1]
existingXsOpts = [xsOpt for xsOpt in self.values() if xsOpt.xsType == xsType and xsOpt.buGroup < buGroup]
if not any(existingXsOpts):
return self._getD... | The container that holds the multiple individual XS settings for different ids. This is what the value of the cs setting is set to. It handles reading/writing the settings to file as well as some other special behavior. | XSSettings | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XSSettings:
"""The container that holds the multiple individual XS settings for different ids. This is what the value of the cs setting is set to. It handles reading/writing the settings to file as well as some other special behavior."""
def __getitem__(self, xsID):
"""Return the sto... | stack_v2_sparse_classes_75kplus_train_069392 | 11,956 | permissive | [
{
"docstring": "Return the stored settings of the same xs type and the lowest burnup group if they exist. Notes ----- 1. If `AA` and `AB` exist, but `AC` is created, then the intended behavior is that `AC` settings will be set to the settings in `AA`. 2. If only `YZ' exists and `YA` is created, then the intende... | 3 | stack_v2_sparse_classes_30k_train_022984 | Implement the Python class `XSSettings` described below.
Class description:
The container that holds the multiple individual XS settings for different ids. This is what the value of the cs setting is set to. It handles reading/writing the settings to file as well as some other special behavior.
Method signatures and ... | Implement the Python class `XSSettings` described below.
Class description:
The container that holds the multiple individual XS settings for different ids. This is what the value of the cs setting is set to. It handles reading/writing the settings to file as well as some other special behavior.
Method signatures and ... | 6c4fea1ca9d256a2599efd52af5e5ebe9860d192 | <|skeleton|>
class XSSettings:
"""The container that holds the multiple individual XS settings for different ids. This is what the value of the cs setting is set to. It handles reading/writing the settings to file as well as some other special behavior."""
def __getitem__(self, xsID):
"""Return the sto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XSSettings:
"""The container that holds the multiple individual XS settings for different ids. This is what the value of the cs setting is set to. It handles reading/writing the settings to file as well as some other special behavior."""
def __getitem__(self, xsID):
"""Return the stored settings ... | the_stack_v2_python_sparse | armi/physics/neutronics/crossSectionSettings.py | paulromano/armi | train | 1 |
a414b7cf1d122c7b9ed9c5c5b7791a718cf61a23 | [
"QtCore.QThread.__init__(self, parent)\nself.uid = uid\nself.limit = limit\nself.text_analysis = TextAnalysisCore.VKTextAnalysis(vk_session, dicts_need=dicts_need)\nself.dictReady.connect(callback)\nself.close = False",
"for element in self.text_analysis.check_wall_iterable(self.uid, limit=self.limit):\n if se... | <|body_start_0|>
QtCore.QThread.__init__(self, parent)
self.uid = uid
self.limit = limit
self.text_analysis = TextAnalysisCore.VKTextAnalysis(vk_session, dicts_need=dicts_need)
self.dictReady.connect(callback)
self.close = False
<|end_body_0|>
<|body_start_1|>
fo... | Поток выполнения проверки текста | TextAnalysisWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextAnalysisWorker:
"""Поток выполнения проверки текста"""
def __init__(self, vk_session, uid, callback, dicts_need, limit=2500, parent=None):
"""Конструктор потока :param vk_session: VkApi объект :param uid: id пользователя или группы :param callback: функция, которая исполнится по ... | stack_v2_sparse_classes_75kplus_train_069393 | 8,984 | permissive | [
{
"docstring": "Конструктор потока :param vk_session: VkApi объект :param uid: id пользователя или группы :param callback: функция, которая исполнится по завершении :param dicts_need: какие словари нужны :param limit: максимальное количество загружаемых записей :param parent: родительский объект",
"name": "... | 2 | null | Implement the Python class `TextAnalysisWorker` described below.
Class description:
Поток выполнения проверки текста
Method signatures and docstrings:
- def __init__(self, vk_session, uid, callback, dicts_need, limit=2500, parent=None): Конструктор потока :param vk_session: VkApi объект :param uid: id пользователя ил... | Implement the Python class `TextAnalysisWorker` described below.
Class description:
Поток выполнения проверки текста
Method signatures and docstrings:
- def __init__(self, vk_session, uid, callback, dicts_need, limit=2500, parent=None): Конструктор потока :param vk_session: VkApi объект :param uid: id пользователя ил... | 23bfedc490c99d488078039b9aab1c7cd3defce9 | <|skeleton|>
class TextAnalysisWorker:
"""Поток выполнения проверки текста"""
def __init__(self, vk_session, uid, callback, dicts_need, limit=2500, parent=None):
"""Конструктор потока :param vk_session: VkApi объект :param uid: id пользователя или группы :param callback: функция, которая исполнится по ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextAnalysisWorker:
"""Поток выполнения проверки текста"""
def __init__(self, vk_session, uid, callback, dicts_need, limit=2500, parent=None):
"""Конструктор потока :param vk_session: VkApi объект :param uid: id пользователя или группы :param callback: функция, которая исполнится по завершении :p... | the_stack_v2_python_sparse | VKTextAnalisys/TextAnalysisAdditionalWidgets.py | vasili8m/VKAnalysis | train | 0 |
9f95cf977af74443652f7e7c38da58eac95ac980 | [
"resp = None\nfor i in range(4):\n try:\n resp = requests.get(url, params=params, timeout=5)\n except requests.Timeout:\n trimmed_params = {k: v for k, v in list(params.items()) if k not in list(ST_BASE_PARAMS.keys())}\n log.error('GET Timeout to {} w/ {}'.format(url[len(ST_BASE_URL):], t... | <|body_start_0|>
resp = None
for i in range(4):
try:
resp = requests.get(url, params=params, timeout=5)
except requests.Timeout:
trimmed_params = {k: v for k, v in list(params.items()) if k not in list(ST_BASE_PARAMS.keys())}
log.er... | Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON | Requests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requests:
"""Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON"""
def get_json(url, params=None):
"""Uses tries to GET a few times before giving up if a timeout. returns JSON"""
<|body_0|>
def post_json(url, params=None, deadline... | stack_v2_sparse_classes_75kplus_train_069394 | 3,330 | no_license | [
{
"docstring": "Uses tries to GET a few times before giving up if a timeout. returns JSON",
"name": "get_json",
"signature": "def get_json(url, params=None)"
},
{
"docstring": "Tries to post a couple times in a loop before giving up if a timeout.",
"name": "post_json",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_037387 | Implement the Python class `Requests` described below.
Class description:
Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON
Method signatures and docstrings:
- def get_json(url, params=None): Uses tries to GET a few times before giving up if a timeout. returns JSON
- def post... | Implement the Python class `Requests` described below.
Class description:
Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON
Method signatures and docstrings:
- def get_json(url, params=None): Uses tries to GET a few times before giving up if a timeout. returns JSON
- def post... | 3938c276a6df5759b055712072bfde983a7ce66a | <|skeleton|>
class Requests:
"""Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON"""
def get_json(url, params=None):
"""Uses tries to GET a few times before giving up if a timeout. returns JSON"""
<|body_0|>
def post_json(url, params=None, deadline... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Requests:
"""Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON"""
def get_json(url, params=None):
"""Uses tries to GET a few times before giving up if a timeout. returns JSON"""
resp = None
for i in range(4):
try:
... | the_stack_v2_python_sparse | Scrapers/stocktwitScraper.py | webclinic017/SP_DayTrading | train | 1 |
475e023c4ef2a34c26b5fdb893aa7911932cd860 | [
"def decorator(subclass):\n cls.subclasses[texture_type] = subclass\n return subclass\nreturn decorator",
"texture_type = params.pop('texture_type')\nif texture_type not in cls.subclasses:\n raise ValueError('Texture not implemented: ' + texture_type)\nreturn cls.subclasses[texture_type](**params)"
] | <|body_start_0|>
def decorator(subclass):
cls.subclasses[texture_type] = subclass
return subclass
return decorator
<|end_body_0|>
<|body_start_1|>
texture_type = params.pop('texture_type')
if texture_type not in cls.subclasses:
raise ValueError('Textu... | Class to register Textures. | TextureGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextureGenerator:
"""Class to register Textures."""
def register_subclass(cls, texture_type):
"""Registers a class Texture"""
<|body_0|>
def create(cls, **params):
"""Create a new instance of Class Texture based on its parameters."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_069395 | 12,985 | permissive | [
{
"docstring": "Registers a class Texture",
"name": "register_subclass",
"signature": "def register_subclass(cls, texture_type)"
},
{
"docstring": "Create a new instance of Class Texture based on its parameters.",
"name": "create",
"signature": "def create(cls, **params)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021075 | Implement the Python class `TextureGenerator` described below.
Class description:
Class to register Textures.
Method signatures and docstrings:
- def register_subclass(cls, texture_type): Registers a class Texture
- def create(cls, **params): Create a new instance of Class Texture based on its parameters. | Implement the Python class `TextureGenerator` described below.
Class description:
Class to register Textures.
Method signatures and docstrings:
- def register_subclass(cls, texture_type): Registers a class Texture
- def create(cls, **params): Create a new instance of Class Texture based on its parameters.
<|skeleton... | 6677b3c0adcd1f456e13bc30f5a012578a7bb0b5 | <|skeleton|>
class TextureGenerator:
"""Class to register Textures."""
def register_subclass(cls, texture_type):
"""Registers a class Texture"""
<|body_0|>
def create(cls, **params):
"""Create a new instance of Class Texture based on its parameters."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextureGenerator:
"""Class to register Textures."""
def register_subclass(cls, texture_type):
"""Registers a class Texture"""
def decorator(subclass):
cls.subclasses[texture_type] = subclass
return subclass
return decorator
def create(cls, **params):
... | the_stack_v2_python_sparse | src/simple_playgrounds/common/texture.py | dtbinh/simple-playgrounds | train | 0 |
f73c8be6fd5be04eb80d06ca71f8149e70526fdc | [
"X, y = check_X_y(X, y, accept_sparse='csc', dtype=np.float32, multi_output=1)\nsuper(BaseForestQuantileRegressor, self).fit(X, y)\nself.y_train_ = y\nself.y_train_leaves_ = -np.ones((self.n_estimators, len(y)), dtype=np.int32)\nself.y_weights_ = np.zeros_like(self.y_train_leaves_, dtype=np.float32)\nfor i, est in ... | <|body_start_0|>
X, y = check_X_y(X, y, accept_sparse='csc', dtype=np.float32, multi_output=1)
super(BaseForestQuantileRegressor, self).fit(X, y)
self.y_train_ = y
self.y_train_leaves_ = -np.ones((self.n_estimators, len(y)), dtype=np.int32)
self.y_weights_ = np.zeros_like(self.y_... | BaseForestQuantileRegressor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseForestQuantileRegressor:
def fit(self, X, y):
"""Build a forest from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse ma... | stack_v2_sparse_classes_75kplus_train_069396 | 12,551 | permissive | [
{
"docstring": "Build a forest from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csc_matrix``. y : array-like, ... | 2 | null | Implement the Python class `BaseForestQuantileRegressor` described below.
Class description:
Implement the BaseForestQuantileRegressor class.
Method signatures and docstrings:
- def fit(self, X, y): Build a forest from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples,... | Implement the Python class `BaseForestQuantileRegressor` described below.
Class description:
Implement the BaseForestQuantileRegressor class.
Method signatures and docstrings:
- def fit(self, X, y): Build a forest from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples,... | a87db29eb786a48a48c0660fe7b2e365aa6b51a8 | <|skeleton|>
class BaseForestQuantileRegressor:
def fit(self, X, y):
"""Build a forest from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseForestQuantileRegressor:
def fit(self, X, y):
"""Build a forest from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provid... | the_stack_v2_python_sparse | test_func/_QRF.py | RunzheStat/TestMDP | train | 13 | |
8aaeddc4e2264e4ecb22fa13459717b0c5346d39 | [
"inputs = [softmax_input, ground_truth]\nself.get_and_assert_common_shape_in_list(inputs)\nself.softmax_input = softmax_input\nself.ground_truth = ground_truth\nshape = ()\nsuper().__init__(inputs, shape)",
"x = self.softmax_input.evaluate(context)\ny = self.ground_truth.evaluate(context)\ndot = np.dot(x, y)\ny_s... | <|body_start_0|>
inputs = [softmax_input, ground_truth]
self.get_and_assert_common_shape_in_list(inputs)
self.softmax_input = softmax_input
self.ground_truth = ground_truth
shape = ()
super().__init__(inputs, shape)
<|end_body_0|>
<|body_start_1|>
x = self.softma... | Applies softmax to an input value, and computes cross entropy of a that using a ground truth value. | SoftMaxCrossEntropy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftMaxCrossEntropy:
"""Applies softmax to an input value, and computes cross entropy of a that using a ground truth value."""
def __init__(self, softmax_input, ground_truth):
"""softmax_input: The input node used to compute softmax. Not a node that computes softmax. ground_truth: Th... | stack_v2_sparse_classes_75kplus_train_069397 | 2,139 | no_license | [
{
"docstring": "softmax_input: The input node used to compute softmax. Not a node that computes softmax. ground_truth: The value the softmax should should approximate.",
"name": "__init__",
"signature": "def __init__(self, softmax_input, ground_truth)"
},
{
"docstring": "Computes J = cross_entro... | 3 | null | Implement the Python class `SoftMaxCrossEntropy` described below.
Class description:
Applies softmax to an input value, and computes cross entropy of a that using a ground truth value.
Method signatures and docstrings:
- def __init__(self, softmax_input, ground_truth): softmax_input: The input node used to compute so... | Implement the Python class `SoftMaxCrossEntropy` described below.
Class description:
Applies softmax to an input value, and computes cross entropy of a that using a ground truth value.
Method signatures and docstrings:
- def __init__(self, softmax_input, ground_truth): softmax_input: The input node used to compute so... | 1d1aad7997154acb36d8a5f87007ceaf6bd50dcd | <|skeleton|>
class SoftMaxCrossEntropy:
"""Applies softmax to an input value, and computes cross entropy of a that using a ground truth value."""
def __init__(self, softmax_input, ground_truth):
"""softmax_input: The input node used to compute softmax. Not a node that computes softmax. ground_truth: Th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoftMaxCrossEntropy:
"""Applies softmax to an input value, and computes cross entropy of a that using a ground truth value."""
def __init__(self, softmax_input, ground_truth):
"""softmax_input: The input node used to compute softmax. Not a node that computes softmax. ground_truth: The value the s... | the_stack_v2_python_sparse | tensorslow/tensor/cost_functions/soft_max_cross_entropy.py | matill/tensor-slow | train | 2 |
23a5e10db8c624438e883e159dcc9db0e04cc3d9 | [
"data = deserialize(serializers.CommentsListParamsSerializer, request.query_params).data\nif request.user.username != data['username']:\n if not request.user.is_staff:\n raise PermissionDenied()\n try:\n user = User.objects.get(username=data['username'])\n except User.DoesNotExist:\n r... | <|body_start_0|>
data = deserialize(serializers.CommentsListParamsSerializer, request.query_params).data
if request.user.username != data['username']:
if not request.user.is_staff:
raise PermissionDenied()
try:
user = User.objects.get(username=data... | CommentsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsView:
def get(self, request, format=None):
"""Получение комментариев пользователя под определенным заданием"""
<|body_0|>
def post(self, request, format=None):
"""Публикация комментария под заданием пользователя"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_069398 | 13,598 | no_license | [
{
"docstring": "Получение комментариев пользователя под определенным заданием",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Публикация комментария под заданием пользователя",
"name": "post",
"signature": "def post(self, request, format=None)"
}
... | 2 | null | Implement the Python class `CommentsView` described below.
Class description:
Implement the CommentsView class.
Method signatures and docstrings:
- def get(self, request, format=None): Получение комментариев пользователя под определенным заданием
- def post(self, request, format=None): Публикация комментария под зада... | Implement the Python class `CommentsView` described below.
Class description:
Implement the CommentsView class.
Method signatures and docstrings:
- def get(self, request, format=None): Получение комментариев пользователя под определенным заданием
- def post(self, request, format=None): Публикация комментария под зада... | c5f60f8c54efb10822ba63ccc88e84ff52c22110 | <|skeleton|>
class CommentsView:
def get(self, request, format=None):
"""Получение комментариев пользователя под определенным заданием"""
<|body_0|>
def post(self, request, format=None):
"""Публикация комментария под заданием пользователя"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentsView:
def get(self, request, format=None):
"""Получение комментариев пользователя под определенным заданием"""
data = deserialize(serializers.CommentsListParamsSerializer, request.query_params).data
if request.user.username != data['username']:
if not request.user.i... | the_stack_v2_python_sparse | app/judge/api/views.py | Sapunov/edujudge | train | 0 | |
9596e639c0134c1d7b9729800a712ba6c60ac25c | [
"n = len(w)\nself.sums = [0] * n\nself.sums[0] = w[0]\nfor i in range(1, n):\n self.sums[i] = self.sums[i - 1] + w[i]",
"p = random.randint(1, self.sums[-1])\nl, r = (0, len(self.sums) - 1)\nwhile l < r:\n mid = l + r >> 1\n if self.sums[mid] >= p:\n r = mid\n else:\n l = mid + 1\nreturn... | <|body_start_0|>
n = len(w)
self.sums = [0] * n
self.sums[0] = w[0]
for i in range(1, n):
self.sums[i] = self.sums[i - 1] + w[i]
<|end_body_0|>
<|body_start_1|>
p = random.randint(1, self.sums[-1])
l, r = (0, len(self.sums) - 1)
while l < r:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(w)
self.sums = [0] * n
self.sums[0] = w[0]
for i in range(1, n):... | stack_v2_sparse_classes_75kplus_train_069399 | 1,013 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046284 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 692bf0e5aab402d55463274e99ab4d0ed56ce64c | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
n = len(w)
self.sums = [0] * n
self.sums[0] = w[0]
for i in range(1, n):
self.sums[i] = self.sums[i - 1] + w[i]
def pickIndex(self):
""":rtype: int"""
p = random.randint(1, self.s... | the_stack_v2_python_sparse | 528-random_pick_with_weight.py | WweiL/LeetCode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.